eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! MCP: model tools from a server that speaks JSON-RPC, over a pipe or over HTTP.
//!
//! Three messages do all the work — `initialize`, `tools/list`, `tools/call` — and everything else
//! in the protocol (resources, prompts, sampling, roots) is deliberately not implemented: this build
//! adds tools, and a half-implemented capability is worse than an absent one.
//!
//! **Two transports, one shape.** `transport = "stdio"` (the default) starts a process per `[[mcp]]`
//! entry and speaks newline-delimited JSON-RPC to its stdin/stdout. `transport = "http"` posts the
//! same messages to `url` — Streamable HTTP, a JSON body or an event stream back, `Mcp-Session-Id`
//! carried once the server hands one out (`#502`). The reason is not symmetry: a server that speaks
//! only HTTP (Home Assistant's `mcp_server`) cannot be reached at all otherwise, and the alternative
//! — spawning `uvx mcp-proxy` to fake a pipe over HTTP — is a second runtime dependency for a
//! transport this build can speak itself.
//!
//! Three decisions worth knowing:
//!
//! * **One connection, serialised.** A stdio server is a single pipe: two questions on it at once
//!   have no way to say which answer is whose beyond the id, and most servers are single-threaded
//!   anyway. Calls take a mutex, so `[tools] concurrency` buys nothing for MCP and nothing breaks.
//! * **The server outlives the call, not the process.** It is spawned on first use and killed when
//!   the agent process ends (or when a call times out, which poisons the pipe). The next call after
//!   a crash starts it again, so a server that segfaults costs one failed call, not a dead session.
//! * **Blocking I/O, called from `spawn_blocking`.** The registry is async; the pipe is not. Reading
//!   a line has no timeout in std, so the timeout is a `recv_timeout` on a channel fed by a reader
//!   thread — and on timeout the child is killed, which is the only way to unblock a stuck read
//!   without leaking a thread per hung server.

use crate::config::Policy;
use crate::tools::{Tool, ToolError};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Write};
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// The MCP revision this client was written against. A server that answers with another one is
/// used as it is: `tools/list` and `tools/call` have not changed shape, and refusing an unknown
/// revision would break on every minor revision for no gain.
pub const PROTOCOL: &str = "2024-11-05";

/// The `.env` values the config loaded, as a `token_env` variable resolves them (`#516`).
///
/// A token variable is looked up in the process environment **first** and here **second** — the
/// order `doctor`'s credential check and `auth::Credentials::resolve` already use. The order is
/// the point: a secret stored where eclipse says secrets live must be found by every reader, not
/// by most of them, and the environment has to stay the way to override one file for one run.
pub type Secrets = BTreeMap<String, String>;

/// How much of a server's stderr is kept for an error message. Enough to see a stack trace start.
const STDERR_KEEP: usize = 4_000;

/// How this build reaches a server (`#502`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Transport {
    /// A process this build starts, spoken to over its stdin/stdout in newline-delimited JSON-RPC.
    #[default]
    Stdio,
    /// Streamable HTTP: one `POST` per message, answered with a JSON body or an event stream.
    Http,
}

impl Transport {
    pub fn as_str(&self) -> &'static str {
        match self {
            Transport::Stdio => "stdio",
            Transport::Http => "http",
        }
    }
}

/// One `[[mcp]]` entry — in a plugin manifest, or in `config.toml` (`#352`).
///
/// Serializing it back out is what lets `config show` print the file it loaded, and what lets
/// `eclipse mcp add` write an entry the loader reads again.
#[derive(Debug, Clone, PartialEq, Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Spec {
    /// The server's name in `source = "plugin:mcp:<name>"` and in messages.
    pub name: String,
    /// How to reach it. The default is what every manifest written before `#502` means.
    #[serde(default)]
    pub transport: Transport,
    /// The program to start, for `transport = "stdio"`. Refused on the HTTP transport.
    #[serde(default)]
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    /// Names copied from the agent's environment (never `KEY=VALUE`, so a manifest cannot carry a
    /// secret and cannot overwrite `PATH` with something it ships).
    #[serde(default)]
    pub env: Vec<String>,
    /// Where the server runs. Defaults to the workspace, like a plugin command.
    #[serde(default)]
    pub cwd: crate::plugins::Cwd,
    /// The endpoint for `transport = "http"`. Required there, refused on stdio.
    #[serde(default)]
    pub url: Option<String>,
    /// The **name of an environment variable** holding a bearer token (`token_env = "HA_TOKEN"`).
    ///
    /// Never the token itself: `env` already refuses `KEY=VALUE` so a manifest cannot carry a
    /// secret, and that property has to survive the HTTP transport or a manifest becomes a place
    /// where credentials are written down (`#502`).
    #[serde(default)]
    pub token_env: Option<String>,
    /// Ceiling for one call, clamped like any plugin timeout.
    #[serde(default)]
    pub timeout_secs: Option<u64>,
    /// Policy for every tool this server offers; `ask` unless the manifest says otherwise.
    #[serde(default = "default_policy")]
    pub policy: Policy,
    /// Per-tool overrides, by the name the *server* uses: `policies = { read_text_file = "allow" }`.
    #[serde(default)]
    pub policies: BTreeMap<String, Policy>,
    /// Prefix for the registered name, for servers whose tool names are too generic to live beside
    /// `shell` and `write_file` (`prefix = "fs_"`).
    #[serde(default)]
    pub prefix: String,
    /// Replace a built-in or another plugin's tool of the same name.
    #[serde(default, rename = "override")]
    pub override_builtin: bool,
    /// Do not start this server at all.
    #[serde(default)]
    pub disabled: bool,
}

fn default_policy() -> Policy {
    Policy::Ask
}

impl Spec {
    /// The one place a `[[mcp]]` entry is checked (`#502`), for the transport it names *and* for
    /// the fields that belong to the other one. An entry that mixes them is refused with a reason
    /// naming both, rather than a half-ignored setting that looks configured and is not.
    ///
    /// The messages use backticks, not quotes: they are read in a terminal next to the file they
    /// are about, and a key name is clearer in the same style the rest of the errors use.
    pub fn validate(&self) -> Result<(), String> {
        let url = self.url.as_deref().map(str::trim).filter(|u| !u.is_empty());
        let command = self.command.trim();
        match self.transport {
            Transport::Stdio => {
                if url.is_some() {
                    return Err(
                        "`url` belongs to the http transport, and this entry is stdio: a stdio \
                         server names `command`"
                            .to_string(),
                    );
                }
                if command.is_empty() {
                    return Err(
                        "no `command` given (an endpoint would need `transport = http` and a \
                         `url`)"
                            .to_string(),
                    );
                }
                Ok(())
            }
            Transport::Http => {
                if !command.is_empty() || !self.args.is_empty() {
                    return Err(
                        "`command`/`args` belong to the stdio transport, and this entry is http: \
                         an HTTP server names `url`"
                            .to_string(),
                    );
                }
                let Some(url) = url else {
                    return Err("`transport = http` with no `url` to post to".to_string());
                };
                if !(url.starts_with("http://") || url.starts_with("https://")) {
                    return Err(format!(
                        "`url` = {url:?} is not an http:// or https:// endpoint"
                    ));
                }
                Ok(())
            }
        }
    }

    /// The token, read from the variable `token_env` names: the process environment first, the
    /// `secrets` the config loaded from `.env` second (`#516`).
    ///
    /// `Ok(None)` when the entry asks for no token; an entry that names a variable neither place
    /// sets is an error, because the alternative is a 401 that reads like a server problem. The
    /// refusal names the variable and never the value — a token in an error message is a token in
    /// a log. An empty value is absent, exactly as `Dotenv::load` treats it.
    fn token(&self, secrets: &Secrets) -> Result<Option<String>, String> {
        let Some(key) = self.token_key() else {
            return Ok(None);
        };
        match self.token_source(secrets) {
            TokenSource::NotUsed => Ok(None),
            TokenSource::Env => Ok(std::env::var(key).ok()),
            TokenSource::Dotenv => Ok(secrets.get(key).cloned()),
            TokenSource::Unset => Err(format!(
                "`token_env = {key:?}` names a variable that is set neither in the environment nor \
                 in `.env` (or is empty); this build never reads a token from the manifest itself"
            )),
        }
    }

    /// The variable `token_env` names, trimmed, or `None` when the entry asks for no token.
    fn token_key(&self) -> Option<&str> {
        self.token_env
            .as_deref()
            .map(str::trim)
            .filter(|k| !k.is_empty())
    }

    /// Where [`Self::token`] would read the token from — the one-word answer a listing shows
    /// (`#517`), so a server that cannot authenticate says so where it is listed rather than only
    /// when somebody presses *test*. Never the value.
    pub fn token_source(&self, secrets: &Secrets) -> TokenSource {
        let Some(key) = self.token_key() else {
            return TokenSource::NotUsed;
        };
        // The same order, and the same "empty is absent" rule, as `token`: one lookup, described.
        if std::env::var(key).is_ok_and(|v| !v.trim().is_empty()) {
            TokenSource::Env
        } else if secrets.get(key).is_some_and(|v| !v.trim().is_empty()) {
            TokenSource::Dotenv
        } else {
            TokenSource::Unset
        }
    }
}

/// Where a `token_env` variable resolves, as a word (`#517`). The value itself is never carried
/// past [`Spec::token`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenSource {
    /// The entry asks for no token.
    NotUsed,
    /// It resolves from the process environment.
    Env,
    /// It resolves from the `.env` the config loaded.
    Dotenv,
    /// It is named and resolves nowhere: this server cannot authenticate as configured.
    Unset,
}

impl TokenSource {
    /// The word a listing prints. `unset` is the one that means "this will fail".
    pub fn as_str(&self) -> &'static str {
        match self {
            TokenSource::NotUsed => "none",
            TokenSource::Env => "env",
            TokenSource::Dotenv => ".env",
            TokenSource::Unset => "unset",
        }
    }
}

/// A tool as the server described it, before this build puts it in the registry.
#[derive(Debug, Clone, Deserialize)]
pub struct RemoteTool {
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default, rename = "inputSchema")]
    pub input_schema: Option<Value>,
}

/// A connection to one server: a pipe into a process, or an HTTP endpoint.
enum Conn {
    Pipe(Pipe),
    Http(Http),
}

/// A process this build started, spoken to in newline-delimited JSON-RPC.
struct Pipe {
    child: Child,
    stdin: ChildStdin,
    /// Messages the reader thread has parsed and handed over, in arrival order.
    rx: mpsc::Receiver<Value>,
}

/// A Streamable HTTP session (`#502`).
///
/// There is no process and no pipe: each message is its own `POST`, and the only state the protocol
/// keeps between them is the session id the server may hand out on `initialize`.
struct Http {
    client: reqwest::Client,
    url: String,
    /// `Mcp-Session-Id`, once the server has given one out.
    session: Option<String>,
    /// The bearer token, already read from the variable `token_env` named.
    token: Option<String>,
    /// Set when the server says it does not know this session. The id is sent on every later call, so
    /// the connection is dropped rather than reused (`#568`); nothing is half-read over HTTP, which is
    /// why this is a flag and not the pipe's poison.
    expired: Arc<AtomicBool>,
}

impl Drop for Pipe {
    fn drop(&mut self) {
        // Dropping a `Child` leaves it running, so a connection that ends — a timeout, a crash, the
        // agent exiting — has to say so. This is the only place a server process dies.
        //
        // `#418`: killing the *direct* child was not enough. A server started through `npx` or
        // `sh -c` is a grandchild, it inherits the stdout pipe, and it outlives its parent — so the
        // reader thread stayed blocked on a pipe nobody would ever write to again, for the life of
        // the process. The server is started in its own process group, so the group and the tree go
        // together, and the direct child is still killed for the group-less (non-unix) path.
        #[cfg(unix)]
        crate::tools::pgroup::kill_now(self.child.id());
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// The longest line a server may send. A JSON-RPC message is a line, and a tool result can be
/// large — but not gigabytes: `BufReader::lines()` allocated whatever arrived with no newline in
/// sight, so a server that never sent one could exhaust memory before any cap was consulted
/// (`#418`). Past this the line is discarded and reported, not buffered.
const MAX_LINE: usize = 8 * 1024 * 1024;

/// How many parsed messages may wait between the reader thread and the request that reads them.
/// Unbounded was the default, which let a chatty server queue without limit; a full queue now stops
/// the reader, which stops the server on its next write — back-pressure instead of growth.
const LINE_QUEUE: usize = 64;

/// One line, or the fact that it was too long to keep.
enum Line {
    Text(String),
    TooLong(usize),
}

/// Read one `\n`-terminated line without ever holding more than `max` bytes of it.
///
/// `read_until` and `lines()` both grow a `Vec` to whatever the writer sent; this consumes the
/// buffer as it goes and keeps counting after the cap, so a server that writes a gigabyte without a
/// newline costs a counter rather than the rest of the machine's memory.
fn read_line_capped<R: BufRead>(reader: &mut R, max: usize) -> std::io::Result<Option<Line>> {
    let mut kept: Vec<u8> = Vec::new();
    let mut seen = 0usize;
    let mut over = false;
    loop {
        let avail = reader.fill_buf()?;
        if avail.is_empty() {
            if seen == 0 {
                return Ok(None);
            }
            break;
        }
        let newline = avail.iter().position(|b| *b == b'\n');
        let take = newline.unwrap_or(avail.len());
        seen += take;
        if !over {
            if kept.len() + take > max {
                over = true;
                kept.clear();
            } else {
                kept.extend_from_slice(&avail[..take]);
            }
        }
        match newline {
            Some(_) => {
                reader.consume(take + 1);
                break;
            }
            None => reader.consume(take),
        }
    }
    if over {
        return Ok(Some(Line::TooLong(seen)));
    }
    Ok(Some(Line::Text(
        String::from_utf8_lossy(&kept).into_owned(),
    )))
}

/// How long a wait may run before it looks at the cancellation flag again. A tool call is a blocking
/// read on a pipe, so this is the granularity at which a cancelled run stops waiting for one.
const CANCEL_TICK: Duration = Duration::from_millis(100);

/// One MCP server, shared by the tools it offers.
pub struct Server {
    spec: Spec,
    plugin_dir: PathBuf,
    workspace: PathBuf,
    timeout: Duration,
    /// Where a `token_env` variable is looked up when the process environment does not set it —
    /// the `.env` values the config loaded (`#516`). Held here because the token is read at
    /// connect time, which is after the registry that built this server is gone.
    secrets: Secrets,
    next_id: AtomicI64,
    state: Mutex<Option<Conn>>,
    /// What the server answered `initialize` with — `protocolVersion`, and its own name and
    /// version. Kept because `eclipse mcp test` is asked to *prove* a server works, and "it listed
    /// three tools" says nothing about which protocol it speaks (`#352`).
    handshake: Mutex<Option<Value>>,
    stderr: Arc<Mutex<String>>,
}

impl std::fmt::Debug for Server {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("mcp::Server")
            .field("name", &self.spec.name)
            .field("transport", &self.spec.transport.as_str())
            .field("command", &self.spec.command)
            .field("url", &self.spec.url)
            .finish()
    }
}

impl Server {
    /// Start a server and ask it what it can do. Blocking on purpose: this runs while a registry is
    /// being built, outside any turn, and a manifest that names a broken server should say so at
    /// startup rather than at the first tool call.
    pub fn start(
        spec: &Spec,
        plugin_dir: &Path,
        workspace: &Path,
        default_timeout: Duration,
        secrets: &Secrets,
    ) -> Result<(Arc<Self>, Vec<RemoteTool>), String> {
        // The server's own `timeout_secs` wins; `[plugins] mcp_timeout_secs` is the machine-wide
        // default for the ones that do not say. Both are clamped the same way.
        let timeout = match spec.timeout_secs {
            Some(secs) => crate::plugins::clamp_timeout(Some(secs)),
            None => default_timeout,
        };
        let server = Arc::new(Self {
            spec: spec.clone(),
            plugin_dir: plugin_dir.to_path_buf(),
            workspace: workspace.to_path_buf(),
            timeout,
            secrets: secrets.clone(),
            next_id: AtomicI64::new(1),
            state: Mutex::new(None),
            handshake: Mutex::new(None),
            stderr: Arc::new(Mutex::new(String::new())),
        });
        let tools = server.list_tools()?;
        Ok((server, tools))
    }

    pub fn name(&self) -> &str {
        &self.spec.name
    }

    pub fn prefix(&self) -> &str {
        &self.spec.prefix
    }

    /// The `initialize` result, if the handshake got that far.
    pub fn handshake(&self) -> Option<Value> {
        self.handshake
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    /// Remember the handshake for `mcp test`. First answer wins: a server is started once per
    /// process, so nothing legitimately writes a second one.
    fn keep_handshake(&self, result: &Value) {
        let mut slot = self.handshake.lock().unwrap_or_else(|e| e.into_inner());
        if slot.is_none() {
            *slot = Some(result.clone());
        }
    }

    pub fn override_builtin(&self) -> bool {
        self.spec.override_builtin
    }

    /// The policy a remote tool gets: its own override, else the server's.
    pub fn policy_for(&self, remote: &str) -> Policy {
        self.spec
            .policies
            .get(remote)
            .copied()
            .unwrap_or(self.spec.policy)
    }

    /// `tools/list`, following `nextCursor` because a server with more than one page of tools is
    /// not rare (a filesystem server can offer a dozen) and stopping at page one would silently
    /// hide the rest.
    fn list_tools(&self) -> Result<Vec<RemoteTool>, String> {
        let mut out = Vec::new();
        let mut cursor: Option<String> = None;
        for _ in 0..16 {
            let params = match &cursor {
                Some(c) => json!({ "cursor": c }),
                None => json!({}),
            };
            // Listing happens before a run exists: no flag to honour.
            let result = self.request("tools/list", params, &crate::cancel::Cancel::new())?;
            let page: Vec<RemoteTool> =
                serde_json::from_value(result.get("tools").cloned().unwrap_or_else(|| json!([])))
                    .map_err(|e| {
                    format!("`tools/list` answered with tools this build cannot read: {e}")
                })?;
            out.extend(page);
            cursor = result
                .get("nextCursor")
                .and_then(Value::as_str)
                .map(str::to_string)
                .filter(|c| !c.is_empty());
            if cursor.is_none() {
                break;
            }
        }
        Ok(out)
    }

    /// `tools/call`, from a thread that is allowed to block.
    pub fn call_tool(&self, remote: &str, args: &Value) -> Result<String, String> {
        self.call_tool_unless(remote, args, &crate::cancel::Cancel::new())
    }

    /// [`call_tool`](Self::call_tool) with a run's cancellation flag.
    ///
    /// A tool call is not interruptible — it is a blocking read on a pipe — but *waiting* for it is.
    /// When the run is cancelled the answer has nowhere to go, so the wait stops, the connection is
    /// dropped (which kills the server) and the caller gets the reason.
    pub fn call_tool_unless(
        &self,
        remote: &str,
        args: &Value,
        cancel: &crate::cancel::Cancel,
    ) -> Result<String, String> {
        let result = self.request(
            "tools/call",
            json!({ "name": remote, "arguments": args }),
            cancel,
        )?;
        let text = content_text(&result);
        if result
            .get("isError")
            .and_then(Value::as_bool)
            .unwrap_or(false)
        {
            // The server said the *tool* failed. That is a tool error, not a transport error, and
            // the model reads it as one.
            return Err(if text.is_empty() {
                "the tool reported a failure without a message".to_string()
            } else {
                text
            });
        }
        Ok(text)
    }

    fn request(
        &self,
        method: &str,
        params: Value,
        cancel: &crate::cancel::Cancel,
    ) -> Result<Value, String> {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
        self.ensure(&mut guard)?;
        let message = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
        let (outcome, poison) = match guard.as_mut().expect("ensure left a connection") {
            Conn::Pipe(pipe) => self.exchange_pipe(pipe, id, method, &message, cancel),
            // An HTTP exchange leaves nothing half-read, so there is no pipe to poison (`#502`) —
            // but a session the server has forgotten is not reusable either, and that is what the
            // second half of the answer says (`#568`).
            Conn::Http(http) => self.exchange_http(http, id, method, &message, cancel),
        };
        if poison {
            // Dropping the connection kills the process; the answer to this id may still be on
            // the pipe and every later request would read it.
            *guard = None;
        }
        outcome
    }

    /// Write one message to the server's stdin without letting a dead server kill the process.
    ///
    /// The CLI sets `SIGPIPE` to `SIG_DFL` on purpose (so `eclipse … | head` exits quietly instead
    /// of panicking on a closed stdout). The cost is that a write to a pipe whose reader has gone
    /// is a *signal*, not an `EPIPE` error — a server that exits before we finish writing to it
    /// takes the whole agent down with it, silently. That is now the ordinary case, not a corner:
    /// `eclipse mcp list` starts every server it lists, so one broken entry killed the command
    /// that was supposed to report it.
    ///
    /// Blocking the signal with `pthread_sigmask` does **not** fix this: a signal is delivered to
    /// any thread that has it unblocked, and the runtime has reader threads by the time a server is
    /// started. So the disposition is switched to `SIG_IGN` for the duration of the write — which
    /// discards the signal instead of queueing it — and put back afterwards. Ignored signals are
    /// dropped rather than left pending, so nothing is delivered late. The lock is there because
    /// swapping a process-wide disposition twice is not something two writers may interleave.
    fn write_stdin(
        &self,
        stdin: &mut std::process::ChildStdin,
        message: &str,
    ) -> std::io::Result<()> {
        #[cfg(unix)]
        // SAFETY: `signal` with `SIG_IGN`, a previously returned handler, or `SIG_DFL` is sound for
        // any disposition; the lock keeps the swap from interleaving with another writer's.
        unsafe {
            static SIGPIPE_SWAP: std::sync::Mutex<()> = std::sync::Mutex::new(());
            let _guard = SIGPIPE_SWAP.lock().unwrap_or_else(|e| e.into_inner());
            let previous = libc::signal(libc::SIGPIPE, libc::SIG_IGN);
            let result = writeln!(stdin, "{message}").and_then(|_| stdin.flush());
            libc::signal(libc::SIGPIPE, previous);
            result
        }
        #[cfg(not(unix))]
        {
            writeln!(stdin, "{message}").and_then(|_| stdin.flush())
        }
    }

    /// One exchange on a pipe, and whether it poisoned it.
    fn exchange_pipe(
        &self,
        pipe: &mut Pipe,
        id: i64,
        method: &str,
        message: &Value,
        cancel: &crate::cancel::Cancel,
    ) -> (Result<Value, String>, bool) {
        if let Err(e) = self.write_stdin(&mut pipe.stdin, &message.to_string()) {
            return (
                Err(format!(
                    "could not send `{method}`: {e}{}",
                    self.stderr_tail_soon()
                )),
                true,
            );
        }
        let deadline = Instant::now() + self.timeout;
        loop {
            if cancel.is_cancelled() {
                return (
                    Err(format!(
                        "`{method}` was cancelled before the server answered; it has been stopped"
                    )),
                    true,
                );
            }
            let left = deadline
                .saturating_duration_since(Instant::now())
                .min(CANCEL_TICK);
            match pipe.rx.recv_timeout(left) {
                Ok(value) => match answer_to(&value, id, method) {
                    Answer::NotMine => continue,
                    Answer::Unparsable(why) => {
                        return (
                            Err(format!("the server wrote a line that is not JSON: {why}")),
                            true,
                        )
                    }
                    Answer::Value(result) => return (Ok(result), false),
                    Answer::Failed(why) => return (Err(why), false),
                },
                Err(RecvTimeoutError::Timeout) => {
                    // A short tick, so a cancel is noticed while waiting. Only the real deadline is
                    // the server's failure.
                    if Instant::now() < deadline {
                        continue;
                    }
                    return (
                        Err(format!(
                            "the server did not answer `{method}` within {}s; it has been stopped \
                             and will be started again on the next call",
                            self.timeout.as_secs()
                        )),
                        true,
                    );
                }
                Err(RecvTimeoutError::Disconnected) => {
                    return (
                        Err(format!(
                            "the server exited while `{method}` was in flight{}",
                            self.stderr_tail()
                        )),
                        true,
                    )
                }
            }
        }
    }

    /// One exchange over Streamable HTTP (`#502`).
    ///
    /// The message is posted as the whole body; the answer is either a JSON body or an event
    /// stream, and both are parsed here so `request` does not have to care which arrived.
    fn exchange_http(
        &self,
        http: &mut Http,
        id: i64,
        method: &str,
        message: &Value,
        cancel: &crate::cancel::Cancel,
    ) -> (Result<Value, String>, bool) {
        let reply = match self.post(http, message, Some(id), cancel) {
            Ok(reply) => reply,
            Err(message) => return (Err(message), http.expired.load(Ordering::Relaxed)),
        };
        let outcome = match answer_to(&reply.value, id, method) {
            Answer::Value(result) => Ok(result),
            Answer::Failed(why) => Err(why),
            Answer::Unparsable(why) => Err(format!("the server answered `{method}` with {why}")),
            // A server that answers a request with a notification and nothing else has not
            // answered it. Say that rather than looping for an answer that is not coming.
            Answer::NotMine => Err(format!(
                "`{method}` was answered with a message for another id; this build speaks one \
                 request per post"
            )),
        };
        (outcome, http.expired.load(Ordering::Relaxed))
    }

    /// A connection, or a new one: a server that died (crashed, was killed) is replaced here, which
    /// is what makes "crash restarts on next call" true without any supervision thread.
    fn ensure(&self, slot: &mut Option<Conn>) -> Result<(), String> {
        let alive = match slot.as_mut() {
            // A process that exited — crash, kill, `sh -c` that never started the real server — is
            // replaced here, which is what makes "a crash costs one call" true without a supervisor.
            Some(Conn::Pipe(pipe)) => matches!(pipe.child.try_wait(), Ok(None)),
            // An HTTP session has no process to watch: whether it still works is what the next
            // post finds out (`#502`).
            Some(Conn::Http(_)) => true,
            None => false,
        };
        if !alive {
            *slot = None;
        }
        if slot.is_none() {
            *slot = Some(self.connect()?);
        }
        Ok(())
    }

    /// Open the connection the entry asks for — a process, or an HTTP session — and say hello on
    /// it. A connection is only published once it has answered `initialize`.
    fn connect(&self) -> Result<Conn, String> {
        self.spec.validate()?;
        match self.spec.transport {
            Transport::Stdio => Ok(Conn::Pipe(self.start_pipe()?)),
            Transport::Http => Ok(Conn::Http(self.start_http()?)),
        }
    }

    /// The Streamable HTTP handshake (`#502`): `initialize`, keep the session id it hands out, then
    /// `notifications/initialized` — carried *with* that id, because a server that issued one
    /// rejects the next post without it.
    fn start_http(&self) -> Result<Http, String> {
        let url = self
            .spec
            .url
            .as_deref()
            .map(str::trim)
            .filter(|u| !u.is_empty())
            .ok_or("`transport = \"http\"` with no `url` to post to")?
            .to_string();
        let token = self.spec.token(&self.secrets)?;
        let client = reqwest::Client::builder()
            .user_agent(concat!("eclipse/", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(|e| format!("could not build an HTTP client: {e}"))?;
        let mut http = Http {
            client,
            url,
            session: None,
            token,
            expired: Arc::new(AtomicBool::new(false)),
        };
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let init = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": "initialize",
            "params": {
                "protocolVersion": PROTOCOL,
                "capabilities": {},
                "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
            }
        });
        let reply = self.post(&mut http, &init, Some(id), &crate::cancel::Cancel::new())?;
        // Before anything else: a server that handed out a session id wants it on every later
        // post, the notification included.
        if let Some(session) = reply.session {
            http.session = Some(session);
        }
        if let Some(err) = reply.value.get("error") {
            return Err(format!(
                "`initialize` was refused: {}",
                err.get("message")
                    .and_then(Value::as_str)
                    .unwrap_or("no message")
            ));
        }
        match answer_to(&reply.value, id, "initialize") {
            Answer::Value(result) => {
                if result
                    .get("protocolVersion")
                    .and_then(Value::as_str)
                    .is_none()
                {
                    return Err("`initialize` answered without a protocolVersion".into());
                }
                self.keep_handshake(&result);
            }
            Answer::Failed(why) => return Err(why),
            Answer::Unparsable(why) => {
                return Err(format!(
                    "`initialize` was answered with a body this build cannot read: {why}"
                ))
            }
            Answer::NotMine => {
                return Err("`initialize` was answered with a message for another id".into())
            }
        }
        let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
        self.post(&mut http, &ready, None, &crate::cancel::Cancel::new())?;
        Ok(http)
    }

    /// One `POST` carrying `message`, and whatever came back (`#502`).
    ///
    /// The exchange runs on a runtime of its own in a thread of its own. This module is synchronous
    /// by design — a pipe has no other option — so the async client is confined to the one place
    /// that needs it instead of leaking a runtime requirement into every caller. The calling thread
    /// waits on a channel with the same tick the pipe uses, so a cancelled run stops waiting here
    /// exactly as it stops there.
    fn post(
        &self,
        http: &mut Http,
        message: &Value,
        id: Option<i64>,
        cancel: &crate::cancel::Cancel,
    ) -> Result<Reply, String> {
        let exchange = Exchange {
            client: http.client.clone(),
            url: http.url.clone(),
            session: http.session.clone(),
            token: http.token.clone(),
            expired: http.expired.clone(),
        };
        let body = message.clone();
        let timeout = self.timeout;
        let (tx, rx) = mpsc::channel::<Result<Reply, String>>();
        std::thread::spawn(move || {
            let _ = tx.send(over_http(exchange, body, id, timeout));
        });
        // The runtime enforces `timeout` on the request itself; this is the ceiling for a thread
        // that never gets that far, so a hung connect is still a bounded wait.
        let deadline = Instant::now() + timeout + Duration::from_secs(2);
        loop {
            if cancel.is_cancelled() {
                return Err("the request was cancelled before the server answered".to_string());
            }
            let left = deadline
                .saturating_duration_since(Instant::now())
                .min(CANCEL_TICK);
            match rx.recv_timeout(left) {
                Ok(outcome) => return outcome,
                Err(RecvTimeoutError::Timeout) => {
                    if Instant::now() < deadline {
                        continue;
                    }
                    return Err(format!(
                        "the server did not answer within {}s",
                        timeout.as_secs()
                    ));
                }
                Err(RecvTimeoutError::Disconnected) => {
                    return Err("the HTTP exchange ended without an answer".to_string())
                }
            }
        }
    }

    /// Start the process and say hello to it. The handshake lives here rather than in `request`
    /// because `request` holds the state mutex and taking it again from inside `ensure` would
    /// deadlock (std mutexes are not reentrant).
    fn start_pipe(&self) -> Result<Pipe, String> {
        let mut cmd = Command::new(&self.spec.command);
        cmd.args(&self.spec.args)
            .current_dir(self.cwd())
            .env_clear()
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        for key in crate::plugins::INHERITED_ENV {
            if let Ok(v) = std::env::var(key) {
                cmd.env(key, v);
            }
        }
        for key in &self.spec.env {
            if let Ok(v) = std::env::var(key) {
                cmd.env(key, v);
            }
        }
        cmd.env("ECLIPSE_PLUGIN_DIR", &self.plugin_dir)
            .env("ECLIPSE_WORKSPACE", &self.workspace);
        // `#418`: its own process group, so `Conn::drop` can take the whole tree down. Without it a
        // server started through `npx` leaves a grandchild holding the pipe.
        #[cfg(unix)]
        cmd.process_group(0);
        let mut child = cmd
            .spawn()
            .map_err(|e| format!("could not start `{}`: {e}", self.spec.command))?;
        let stdin = child.stdin.take().ok_or("no stdin on the server process")?;
        let stdout = child
            .stdout
            .take()
            .ok_or("no stdout on the server process")?;
        // A server's stderr is its log. Reading it on a thread keeps a chatty server from filling the
        // pipe and blocking on its own writes, and keeps the tail for the error message when
        // something goes wrong.
        if let Some(mut err) = child.stderr.take() {
            let keep = Arc::clone(&self.stderr);
            std::thread::spawn(move || {
                let mut buf = [0u8; 1024];
                loop {
                    match std::io::Read::read(&mut err, &mut buf) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            let text = String::from_utf8_lossy(&buf[..n]).into_owned();
                            let mut slot = keep.lock().unwrap_or_else(|e| e.into_inner());
                            slot.push_str(&text);
                            keep_tail(&mut slot, STDERR_KEEP);
                        }
                    }
                }
            });
        }
        let (tx, rx) = mpsc::sync_channel(LINE_QUEUE);
        std::thread::spawn(move || {
            let mut reader = BufReader::new(stdout);
            loop {
                let line = match read_line_capped(&mut reader, MAX_LINE) {
                    Ok(Some(Line::Text(line))) => line,
                    // A line this build cannot keep is a message the caller never sees; saying so is
                    // better than a request that waits out its timeout for an answer already thrown
                    // away (`#418`).
                    Ok(Some(Line::TooLong(bytes))) => {
                        if tx
                            .send(json!({
                                "eclipse_unparsable": format!(
                                    "a line of {bytes} bytes is over the {MAX_LINE}-byte limit and was dropped"
                                )
                            }))
                            .is_err()
                        {
                            break;
                        }
                        continue;
                    }
                    Ok(None) | Err(_) => break,
                };
                if line.trim().is_empty() {
                    continue;
                }
                // A server that writes a line this build cannot parse is not silent: the caller
                // gets "not JSON" rather than a timeout three minutes later.
                match serde_json::from_str::<Value>(&line) {
                    Ok(value) => {
                        if tx.send(value).is_err() {
                            break;
                        }
                    }
                    Err(e) => {
                        let _ = tx.send(json!({
                            "eclipse_unparsable": format!("{e}: {}", clip(&line, 200))
                        }));
                    }
                }
            }
        });
        let mut pipe = Pipe { child, stdin, rx };
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let init = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": "initialize",
            "params": {
                "protocolVersion": PROTOCOL,
                "capabilities": {},
                "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
            }
        });
        self.write_stdin(&mut pipe.stdin, &init.to_string())
            .map_err(|e| {
                format!(
                    "could not send `initialize`: {e}{}",
                    self.stderr_tail_soon()
                )
            })?;
        let answer = wait_for(&mut pipe, id, self.timeout, &self.stderr)?;
        if let Some(result) = answer.get("result") {
            if result
                .get("protocolVersion")
                .and_then(Value::as_str)
                .is_none()
            {
                return Err("`initialize` answered without a protocolVersion".into());
            }
            self.keep_handshake(result);
        }
        // Required by the protocol once the client is satisfied, and servers do wait for it before
        // answering `tools/list`.
        let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
        self.write_stdin(&mut pipe.stdin, &ready.to_string())
            .map_err(|e| format!("could not finish the handshake: {e}"))?;
        Ok(pipe)
    }

    fn cwd(&self) -> PathBuf {
        match self.spec.cwd {
            crate::plugins::Cwd::Plugin => self.plugin_dir.clone(),
            crate::plugins::Cwd::Workspace => self.workspace.clone(),
        }
    }

    /// [`stderr_tail`](Self::stderr_tail) for a pipe that has just failed: the reader thread may not
    /// have been scheduled yet, and "Broken pipe" alone is a much worse error than the server's own
    /// complaint that follows it a millisecond later. Waits up to 200 ms, and only when the tail is
    /// still empty.
    fn stderr_tail_soon(&self) -> String {
        let mut tail = self.stderr_tail();
        // 200 ms was not always enough for a thread to be *scheduled* on a loaded machine, and the
        // test that asserts this text went red about once a full-suite run. Half a second costs
        // nothing on the happy path — the loop breaks as soon as there is something to say.
        for _ in 0..50 {
            if !tail.is_empty() {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
            tail = self.stderr_tail();
        }
        tail
    }

    fn stderr_tail(&self) -> String {
        let slot = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
        let tail = slot.trim();
        if tail.is_empty() {
            String::new()
        } else {
            format!("; the server said: {}", clip(tail, 600))
        }
    }
}

/// The answer to one POST: the JSON-RPC message, and the session id the server may have issued.
struct Reply {
    value: Value,
    session: Option<String>,
}

/// What an HTTP exchange needs from the connection, cloned out so the exchange can own it: the
/// connection itself is borrowed by the caller and the exchange runs in its own thread.
struct Exchange {
    client: reqwest::Client,
    url: String,
    session: Option<String>,
    token: Option<String>,
    expired: Arc<AtomicBool>,
}

/// The whole HTTP exchange, on a runtime this thread builds and drops (`#502`).
fn over_http(
    exchange: Exchange,
    body: Value,
    id: Option<i64>,
    timeout: Duration,
) -> Result<Reply, String> {
    let Exchange {
        client,
        url,
        session,
        token,
        expired,
    } = exchange;
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| format!("could not start an HTTP runtime: {e}"))?;
    runtime.block_on(async move {
        let mut request = client
            .post(&url)
            .header(
                reqwest::header::ACCEPT,
                "application/json, text/event-stream",
            )
            .timeout(timeout)
            .json(&body);
        if let Some(session) = session.as_deref() {
            request = request.header("mcp-session-id", session);
        }
        if let Some(token) = token.as_deref() {
            request = request.bearer_auth(token);
        }
        let response = request
            .send()
            .await
            .map_err(|e| format!("could not post to {url}: {e:?}"))?;
        let status = response.status();
        let issued = response
            .headers()
            .get("mcp-session-id")
            .and_then(|v| v.to_str().ok())
            .filter(|v| !v.is_empty())
            .map(str::to_string);
        let streamed = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(|v| v.contains("text/event-stream"))
            .unwrap_or(false);
        // A body with no ceiling is the one thing here that can exhaust memory before the timeout
        // fires; stdio already refuses a line this long (`#568`). Read it in chunks and stop.
        let mut response = response;
        let mut text = String::new();
        while let Some(bytes) = response
            .chunk()
            .await
            .map_err(|e| format!("could not read the answer from {url}: {e}"))?
        {
            if text.len() + bytes.len() > MAX_LINE {
                return Err(format!(
                    "the server answered with more than {} MiB: {url}",
                    MAX_LINE / (1024 * 1024)
                ));
            }
            text.push_str(&String::from_utf8_lossy(&bytes));
        }
        let session = issued.or(session);
        if status == reqwest::StatusCode::NOT_FOUND && session.is_some() {
            // Streamable HTTP: `404` is how a server says it has never heard of this session id — it
            // restarted, or the session timed out. Reusing the id fails every call until Eclipse
            // restarts, so the connection is marked for dropping instead (`#568`).
            expired.store(true, Ordering::Relaxed);
        }
        if !status.is_success() {
            // No child process and no stderr to harvest: the status and the body *are* the report.
            return Err(format!(
                "the server answered HTTP {}: {}",
                status.as_u16(),
                if text.trim().is_empty() {
                    "no body".to_string()
                } else {
                    clip(text.trim(), 400)
                }
            ));
        }
        if text.trim().is_empty() {
            // A notification is answered with `202 Accepted` and no body; that is a success.
            return Ok(Reply {
                value: Value::Null,
                session,
            });
        }
        let value = if streamed {
            sse_payload(&text, id)
        } else {
            serde_json::from_str::<Value>(text.trim()).map_err(|e| {
                format!(
                    "the server answered with a body that is not JSON-RPC ({e}): {}",
                    clip(text.trim(), 200)
                )
            })?
        };
        Ok(Reply { value, session })
    })
}

/// The JSON-RPC message inside an event stream.
///
/// Streamable HTTP answers a `POST` with `text/event-stream`: one event per message, its JSON on
/// `data:` lines. This picks the message whose id is `id`, and for a notification — which carries
/// no id — the last message in the stream. An event with no `data:` is a keep-alive or a comment.
fn sse_payload(text: &str, id: Option<i64>) -> Value {
    // A CRLF stream separates events with `\r\n\r\n`, which contains no `\n\n`: every `data:` line
    // fell into one buffer, so a notification followed by the reply became one unparsable blob and
    // the id never matched — "answered with a message for another id" on a perfectly good server
    // (`#567`). The spec allows either line ending, so they are normalised once, here.
    let text = text.replace("\r\n", "\n").replace('\r', "\n");
    let mut last = Value::Null;
    for event in text.split("\n\n") {
        let mut data = String::new();
        for line in event.lines() {
            if let Some(rest) = line.strip_prefix("data:") {
                if !data.is_empty() {
                    data.push('\n');
                }
                data.push_str(rest.trim_start());
            }
        }
        if data.trim().is_empty() {
            continue;
        }
        let Ok(value) = serde_json::from_str::<Value>(data.trim()) else {
            continue;
        };
        if let Some(id) = id {
            if value.get("id").and_then(Value::as_i64) == Some(id) {
                return value;
            }
        }
        last = value;
    }
    last
}

/// What a message from a server is, with respect to the request being waited for.
enum Answer {
    /// Not this request's answer: a notification (`notifications/tools/list_changed`), or the
    /// answer to a message this build has already given up on. On a pipe both arrive at the same
    /// place and the id is the only thing that says which is which.
    NotMine,
    /// A line that could not be parsed as JSON.
    Unparsable(String),
    /// The answer.
    Value(Value),
    /// The server's own error for this request.
    Failed(String),
}

fn answer_to(value: &Value, id: i64, method: &str) -> Answer {
    if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
        return Answer::Unparsable(why.to_string());
    }
    if value.get("id").and_then(Value::as_i64) != Some(id) {
        return Answer::NotMine;
    }
    if let Some(err) = value.get("error") {
        let message = err
            .get("message")
            .and_then(Value::as_str)
            .unwrap_or("no message");
        return Answer::Failed(format!("{method} failed: {message}"));
    }
    Answer::Value(value.get("result").cloned().unwrap_or(Value::Null))
}

/// Wait for the answer to `id` on a connection that is not yet in `state` (the handshake).
fn wait_for(
    pipe: &mut Pipe,
    id: i64,
    timeout: Duration,
    stderr: &Arc<Mutex<String>>,
) -> Result<Value, String> {
    let deadline = Instant::now() + timeout;
    loop {
        let left = deadline.saturating_duration_since(Instant::now());
        match pipe.rx.recv_timeout(left) {
            Ok(value) => {
                if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
                    return Err(format!("the server wrote a line that is not JSON: {why}"));
                }
                if value.get("id").and_then(Value::as_i64) != Some(id) {
                    continue;
                }
                if let Some(err) = value.get("error") {
                    return Err(format!(
                        "`initialize` was refused: {}",
                        err.get("message")
                            .and_then(Value::as_str)
                            .unwrap_or("no message")
                    ));
                }
                return Ok(value);
            }
            Err(RecvTimeoutError::Timeout) => {
                let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
                return Err(format!(
                    "the server did not answer `initialize` within {}s{}",
                    timeout.as_secs(),
                    if tail.trim().is_empty() {
                        String::new()
                    } else {
                        format!("; it said: {}", clip(tail.trim(), 600))
                    }
                ));
            }
            Err(RecvTimeoutError::Disconnected) => {
                let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
                return Err(format!(
                    "the server exited during the handshake{}",
                    if tail.trim().is_empty() {
                        String::new()
                    } else {
                        format!("; it said: {}", clip(tail.trim(), 600))
                    }
                ));
            }
        }
    }
}

/// The text a `tools/call` result carries. Anything that is not text (an image, an embedded
/// resource) is named rather than dropped: silently losing half an answer is worse than saying the
/// dashboard cannot show it.
fn content_text(result: &Value) -> String {
    let Some(items) = result.get("content").and_then(Value::as_array) else {
        // Some servers answer with a bare string or with `structuredContent`; take what is there.
        if let Some(text) = result.get("content").and_then(Value::as_str) {
            return text.to_string();
        }
        if let Some(structured) = result.get("structuredContent") {
            return structured.to_string();
        }
        return String::new();
    };
    let mut parts = Vec::new();
    for item in items {
        let kind = item
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        if kind == "text" {
            if let Some(text) = item.get("text").and_then(Value::as_str) {
                parts.push(text.to_string());
            }
        } else {
            parts.push(format!("[{kind} content from an MCP server is not shown]"));
        }
    }
    parts.join("\n")
}

/// Keep the last `keep` bytes of a log slot, never splitting a character.
///
/// `drain` takes a *byte* range and panics on an index that is not a char boundary. A 1024-byte read
/// frame lands mid-character routinely for non-ASCII log output, so the cut moves forward to the next
/// boundary: the reader thread dying here is not a lost log line, it is stderr nobody drains and a
/// child blocked on a full pipe (`#564`).
fn keep_tail(slot: &mut String, keep: usize) {
    if slot.len() <= keep {
        return;
    }
    let mut cut = slot.len() - keep;
    while !slot.is_char_boundary(cut) {
        cut += 1;
    }
    slot.drain(..cut);
}

fn clip(text: &str, max: usize) -> String {
    if text.chars().count() <= max {
        return text.to_string();
    }
    let head: String = text.chars().take(max).collect();
    format!("{head}…")
}

/// A tool the agent can call, implemented by a remote MCP server.
pub struct McpTool {
    /// The name this build registered (`prefix` + the server's name).
    name: String,
    /// The name the server knows.
    remote: String,
    description: String,
    parameters: Value,
    plugin: String,
    server: Arc<Server>,
}

/// The most a tool name may be. OpenAI-compatible endpoints cap it at 64 characters and reject the
/// whole request past it — the same ceiling the config's tool ids live under.
pub const TOOL_NAME_MAX: usize = 64;

/// What a remote description is cut to. A description is worth a sentence or two of prompt; a
/// server that sends its whole README should not get to charge that to every request.
pub const DESCRIPTION_MAX: usize = 2000;

/// What a remote input schema may serialize to. See `McpTool::new` for what happens past it.
pub const SCHEMA_MAX: usize = 16 * 1024;

/// A remote tool name, made safe to put in a chat request.
///
/// A third-party server names its own tools, and a name is not a private detail: it is copied into
/// the `tools` array of every request, and one name outside `[A-Za-z0-9_-]` makes an
/// OpenAI-compatible endpoint reject the entire request — so the agent is unusable and the error
/// names the model, not the server. Anything outside the alphabet becomes `_`, and the result is
/// truncated to `TOOL_NAME_MAX`; the raw name still goes to the server on the wire.
pub fn sanitize_tool_name(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
                c
            } else {
                '_'
            }
        })
        .collect();
    cleaned.chars().take(TOOL_NAME_MAX).collect()
}

/// Text cut to at most `max` **chars**, with a mark saying it was cut, so a truncated description
/// cannot be mistaken for the whole one.
fn cap_text(text: &str, max: usize) -> String {
    if text.chars().count() <= max {
        return text.to_string();
    }
    let mut out: String = text.chars().take(max).collect();
    out.push_str("… [truncated]");
    out
}

impl McpTool {
    /// The one path a call goes through. The pipe blocks, so it runs on a blocking thread — and the
    /// run's cancellation flag travels with it, because a cancelled run must not sit here for a
    /// minute waiting for an answer nothing will read.
    async fn call_unless(
        &self,
        args: Value,
        cancel: crate::cancel::Cancel,
    ) -> Result<String, ToolError> {
        let server = Arc::clone(&self.server);
        let remote = self.remote.clone();
        let out =
            tokio::task::spawn_blocking(move || server.call_tool_unless(&remote, &args, &cancel))
                .await
                .map_err(|e| ToolError::Failed(format!("the MCP call did not finish: {e}")))?;
        out.map_err(ToolError::Failed)
    }

    pub fn new(server: Arc<Server>, remote: &RemoteTool) -> Self {
        // `#373`: a remote name goes into the `tools` array of every chat request, and an
        // OpenAI-compatible server rejects the *whole request* with a 400 on the first name outside
        // `[A-Za-z0-9_-]` — one third-party server, one advertised `a.b` or `get repo`, and the
        // session is unusable with an error that names no server. Plugin command tools are already
        // held to that alphabet; a server's tools are held to it here, and the raw name is kept for
        // the wire (`remote`), which is the only place it is correct.
        let name = sanitize_tool_name(&format!("{}{}", server.prefix(), remote.name));
        let description = if remote.description.trim().is_empty() {
            format!("`{}` on the `{}` MCP server", remote.name, server.name())
        } else {
            cap_text(&remote.description, DESCRIPTION_MAX)
        };
        let parameters = remote
            .input_schema
            .clone()
            .unwrap_or_else(|| json!({ "type": "object", "properties": {} }));
        // A tool's schema is copied into the prompt verbatim; a server that ships a megabyte of it
        // costs that much of every request in the session. Past the cap the model is told the tool
        // takes an object and the description says so — better than a prompt nobody can afford, and
        // better than a silent downgrade the model has no way to notice.
        let over_cap = serde_json::to_string(&parameters).map_or(0, |s| s.len()) > SCHEMA_MAX;
        let parameters = if over_cap {
            json!({ "type": "object", "properties": {} })
        } else {
            parameters
        };
        let description = if over_cap {
            format!(
                "{description} [its input schema is over {SCHEMA_MAX} bytes and was not included; \
                 the tool takes a JSON object]"
            )
        } else {
            description
        };
        Self {
            name,
            remote: remote.name.clone(),
            description,
            parameters,
            plugin: server.name().to_string(),
            server,
        }
    }
    /// A server's own name, for a message that has to name where a tool came from.
    pub fn server_name(&self) -> &str {
        &self.plugin
    }
}

#[async_trait::async_trait]
impl Tool for McpTool {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn parameters(&self) -> Value {
        self.parameters.clone()
    }

    fn describe_call(&self, args: &Value) -> String {
        // The prompt has to say *which* server this is going to: `read_text_file` is a harmless name
        // on a filesystem server and something else entirely elsewhere.
        format!(
            "{} (mcp: {}) {}",
            self.remote,
            self.plugin,
            clip(&args.to_string(), 200)
        )
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        self.call_unless(args, crate::cancel::Cancel::new()).await
    }

    async fn call_scoped(
        &self,
        args: Value,
        scope: &crate::tools::CallScope<'_>,
    ) -> Result<String, ToolError> {
        // The run's own flag: a cancelled run must not sit waiting for a server that is still
        // thinking, and the answer would have nowhere to go anyway.
        self.call_unless(args, scope.run.cancel.clone()).await
    }
}

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

    /// The default a `[[mcp]]` entry with no `timeout_secs` would get. The tests all state their
    /// own ceiling in the spec, so this only has to be a sane number.
    const DEFAULT_TEST_TIMEOUT: Duration = Duration::from_secs(10);

    /// A server that speaks just enough of the protocol, so the client can be tested without a
    /// network or a real MCP implementation. `sleep` on a call hangs it, which is what a timeout is
    /// for; two pages of tools exercise `nextCursor`.
    const FAKE: &str = r#"#!/usr/bin/env python3
import json, sys, time

def send(obj):
    sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()

for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    msg = json.loads(line)
    mid, method = msg.get("id"), msg.get("method")
    params = msg.get("params") or {}
    if method == "initialize":
        send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
              "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
    elif method == "notifications/initialized":
        pass
    elif method == "tools/list":
        if params.get("cursor"):
            send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
                {"name": "fail_tool", "description": "Always fails"}]}})
        else:
            send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
                {"name": "echo_text", "description": "Echo the text back",
                 "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}}],
                "nextCursor": "page-2"}})
    elif method == "tools/call":
        name, args = params.get("name"), params.get("arguments") or {}
        if name == "echo_text":
            if args.get("sleep"):
                time.sleep(30)
            send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
                {"type": "text", "text": "echo: " + str(args.get("text", ""))}]}})
        elif name == "fail_tool":
            send({"jsonrpc": "2.0", "id": mid, "result": {
                "content": [{"type": "text", "text": "the disk is on fire"}], "isError": True}})
        else:
            send({"jsonrpc": "2.0", "id": mid, "result": {"content": []}})
    elif mid is not None:
        send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no such method"}})
"#;

    /// A Streamable HTTP server, hand-rolled on a socket (`#502`).
    ///
    /// The subject here is the *transport*, not MCP: what a real server does with a message is
    /// already covered by `FAKE`. So this answers from the request line and the body alone, and it
    /// answers in the two shapes the protocol allows — a JSON body for `tools/call`, an event
    /// stream for `tools/list` — so both parsers are exercised by one passing run.
    struct FakeHttp {
        port: u16,
        seen: Arc<Mutex<Vec<(String, String)>>>,
        stop: Arc<std::sync::atomic::AtomicBool>,
        /// Set from the test thread: from then on every request that carries a session id is
        /// answered `404`, which is how a Streamable HTTP server says it has forgotten it (`#568`).
        forgetful: Arc<std::sync::atomic::AtomicBool>,
    }

    impl Drop for FakeHttp {
        fn drop(&mut self) {
            self.stop.store(true, Ordering::SeqCst);
            // Unblock the accept: a connection that is never answered is the thread's exit ticket.
            let _ = std::net::TcpStream::connect(("127.0.0.1", self.port));
        }
    }

    impl FakeHttp {
        /// Make the server forget every session it has issued, the way a restart does (`#568`).
        fn forget_sessions(&self) {
            self.forgetful.store(true, Ordering::SeqCst);
        }

        /// `token`: when set, the server answers 401 unless the request carries it.
        fn start(token: Option<String>, status: Option<u16>) -> Self {
            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a port");
            let port = listener.local_addr().unwrap().port();
            let seen = Arc::new(Mutex::new(Vec::new()));
            let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let forgetful = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let (log, flag) = (Arc::clone(&seen), Arc::clone(&stop));
            let forget = Arc::clone(&forgetful);
            std::thread::spawn(move || {
                for stream in listener.incoming() {
                    if flag.load(Ordering::SeqCst) {
                        break;
                    }
                    let Ok(mut stream) = stream else { continue };
                    let (head, body) = read_http(&mut stream);
                    log.lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .push((head.clone(), body.clone()));
                    let reply = answer_http(&head, &body, token.as_deref(), status, &forget);
                    let _ = std::io::Write::write_all(&mut stream, reply.as_bytes());
                    let _ = std::io::Write::flush(&mut stream);
                }
            });
            FakeHttp {
                port,
                seen,
                stop,
                forgetful,
            }
        }

        fn url(&self, path: &str) -> String {
            format!("http://127.0.0.1:{}{path}", self.port)
        }

        fn requests(&self) -> Vec<(String, String)> {
            self.seen.lock().unwrap_or_else(|e| e.into_inner()).clone()
        }
    }

    /// Read one request: the head, and `Content-Length` bytes of body.
    fn read_http(stream: &mut std::net::TcpStream) -> (String, String) {
        use std::io::Read;
        let mut head = Vec::new();
        let mut byte = [0u8; 1];
        while head.len() < 64 * 1024 {
            match stream.read(&mut byte) {
                Ok(0) | Err(_) => {
                    return (String::from_utf8_lossy(&head).into_owned(), String::new())
                }
                Ok(_) => {
                    head.push(byte[0]);
                    if head.ends_with(b"\r\n\r\n") {
                        break;
                    }
                }
            }
        }
        let head = String::from_utf8_lossy(&head).into_owned();
        let length = head
            .lines()
            .find_map(|line| {
                let (name, value) = line.split_once(':')?;
                name.eq_ignore_ascii_case("content-length")
                    .then(|| value.trim().parse::<usize>().ok())
                    .flatten()
            })
            .unwrap_or(0);
        let mut body = vec![0u8; length];
        let mut got = 0;
        while got < length {
            match stream.read(&mut body[got..]) {
                Ok(0) | Err(_) => break,
                Ok(n) => got += n,
            }
        }
        body.truncate(got);
        (head, String::from_utf8_lossy(&body).into_owned())
    }

    fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> {
        head.lines().find_map(|line| {
            let (key, value) = line.split_once(':')?;
            key.eq_ignore_ascii_case(name).then(|| value.trim())
        })
    }

    fn answer_http(
        head: &str,
        body: &str,
        token: Option<&str>,
        status: Option<u16>,
        forgetful: &std::sync::atomic::AtomicBool,
    ) -> String {
        let message: Value = serde_json::from_str(body).unwrap_or(Value::Null);
        let id = message.get("id").cloned().unwrap_or(Value::Null);
        let method = message.get("method").and_then(Value::as_str).unwrap_or("");
        if let Some(token) = token {
            let sent = header(head, "authorization").unwrap_or("<>");
            if sent != format!("Bearer {token}") {
                return http_reply(
                    401,
                    "application/json",
                    &json!({ "error": "unauthorized" }).to_string(),
                    "",
                );
            }
        }
        if let Some(status) = status {
            return http_reply(status, "application/json", "", "");
        }
        // A server that has restarted knows no sessions: everything but a fresh `initialize` is
        // answered `404` (`#568`).
        if forgetful.load(Ordering::SeqCst) && method != "initialize" {
            return http_reply(404, "application/json", "", "");
        }
        // The session id is the whole point of the handshake: everything after `initialize` must
        // carry it back.
        if method != "initialize" && header(head, "mcp-session-id").is_none() {
            return http_reply(400, "application/json", "", "");
        }
        match method {
            "initialize" => {
                let extra = "mcp-session-id: test-session\r\n";
                http_reply(
                    200,
                    "application/json",
                    &json!({ "jsonrpc": "2.0", "id": id, "result": {
                        "protocolVersion": "2024-11-05",
                        "capabilities": { "tools": {} },
                        "serverInfo": { "name": "fake-http", "version": "0" } } })
                    .to_string(),
                    extra,
                )
            }
            // A notification is answered with an accepted-and-empty body.
            "notifications/initialized" => http_reply(202, "text/plain", "", ""),
            "tools/list" => {
                let page = message
                    .get("params")
                    .and_then(|p| p.get("cursor"))
                    .and_then(Value::as_str)
                    .map(str::to_string);
                let result = match page.as_deref() {
                    Some("page-2") => json!({ "tools": [
                        { "name": "fail_tool", "description": "Always fails" }] }),
                    _ => json!({ "tools": [
                        { "name": "echo_text", "description": "Echo the text back",
                          "inputSchema": { "type": "object",
                            "properties": { "text": { "type": "string" } } } }],
                        "nextCursor": "page-2" }),
                };
                // An event stream, with a keep-alive comment first: a parser that treats every
                // line as a message would answer with null here.
                let event = format!(
                    ": keep-alive\n\ndata: {}\n\n",
                    json!({ "jsonrpc": "2.0", "id": id, "result": result })
                );
                http_reply(200, "text/event-stream", &event, "")
            }
            "tools/call" => {
                let name = message
                    .get("params")
                    .and_then(|p| p.get("name"))
                    .and_then(Value::as_str)
                    .unwrap_or("");
                let text = message
                    .get("params")
                    .and_then(|p| p.get("arguments"))
                    .and_then(|a| a.get("text"))
                    .and_then(Value::as_str)
                    .unwrap_or("");
                let result = if name == "fail_tool" {
                    json!({ "content": [{ "type": "text", "text": "the disk is on fire" }],
                            "isError": true })
                } else {
                    json!({ "content": [{ "type": "text", "text": format!("echo: {text}") }] })
                };
                http_reply(
                    200,
                    "application/json",
                    &json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string(),
                    "",
                )
            }
            _ => http_reply(
                200,
                "application/json",
                &json!({ "jsonrpc": "2.0", "id": id,
                        "error": { "code": -32601, "message": "no such method" } })
                .to_string(),
                "",
            ),
        }
    }

    fn http_reply(status: u16, kind: &str, body: &str, extra: &str) -> String {
        format!(
            "HTTP/1.1 {status} OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
            body.len()
        )
    }

    /// An HTTP entry with the fields the transport needs, and nothing else.
    fn http_spec(url: &str) -> Spec {
        Spec {
            name: "ha".into(),
            transport: Transport::Http,
            command: String::new(),
            args: Vec::new(),
            env: Vec::new(),
            cwd: crate::plugins::Cwd::Workspace,
            url: Some(url.to_string()),
            token_env: None,
            timeout_secs: Some(10),
            policy: Policy::Allow,
            policies: BTreeMap::new(),
            prefix: String::new(),
            override_builtin: false,
            disabled: false,
        }
    }

    /// A server that dies before saying anything: the failure has to arrive as an error with the
    /// reason, not as a hang.
    const DIES: &str = r#"#!/usr/bin/env python3
import sys
sys.stderr.write("could not open the database: /nope\n")
sys.exit(3)
"#;

    fn have_python() -> bool {
        std::process::Command::new("python3")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    fn script(dir: &Path, name: &str, body: &str) -> PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, body).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        path
    }

    fn spec(script: &Path, timeout_secs: u64) -> Spec {
        Spec {
            name: "fake".into(),
            transport: Transport::Stdio,
            command: "python3".into(),
            args: vec![script.to_string_lossy().into_owned()],
            url: None,
            token_env: None,
            env: Vec::new(),
            cwd: crate::plugins::Cwd::Plugin,
            timeout_secs: Some(timeout_secs),
            policy: Policy::Ask,
            policies: Default::default(),
            prefix: String::new(),
            override_builtin: false,
            disabled: false,
        }
    }

    /// `#373`: a remote server names its own tools, and that name is copied into the `tools` array of
    /// every chat request. An OpenAI-compatible endpoint rejects the *whole request* on the first name
    /// outside `[A-Za-z0-9_-]`, so one third-party server advertising `get repo` left the agent
    /// unusable for the session with an error naming the model rather than the server.
    #[test]
    fn a_remote_tool_name_is_made_safe_for_a_request() {
        // The alphabet is the one plugin command tools are already held to.
        assert_eq!(sanitize_tool_name("get repo"), "get_repo");
        assert_eq!(sanitize_tool_name("a.b"), "a_b");
        assert_eq!(sanitize_tool_name("日本"), "__");
        assert_eq!(sanitize_tool_name("read_file"), "read_file");
        // Long names are cut, not rejected: a 64-character ceiling is what the endpoint enforces.
        let long = "x".repeat(200);
        assert_eq!(sanitize_tool_name(&long).chars().count(), TOOL_NAME_MAX);
        assert_eq!(
            sanitize_tool_name(&format!("{}_tail", "y".repeat(63)))
                .chars()
                .count(),
            TOOL_NAME_MAX
        );

        // A description and a schema are copied into the prompt too.
        let long_desc = "d".repeat(DESCRIPTION_MAX * 2);
        let capped = cap_text(&long_desc, DESCRIPTION_MAX);
        assert!(capped.starts_with(&"d".repeat(DESCRIPTION_MAX)));
        assert!(capped.ends_with("[truncated]"), "{capped}");
        assert_eq!(cap_text("short", DESCRIPTION_MAX), "short");
    }

    /// The name the endpoint sees is safe; the name the *server* is asked for is the one it
    /// published — those are two different strings and both have to be right.
    #[test]
    fn the_wire_keeps_the_name_the_server_published() {
        if !have_python() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = script(dir.path(), "fake.py", FAKE);
        let (server, _tools) = Server::start(
            &spec(&path, 10),
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the fake server starts");
        let remote = RemoteTool {
            name: "get repo".into(),
            description: "Read a repository".into(),
            input_schema: None,
        };
        let tool = McpTool::new(Arc::clone(&server), &remote);
        assert_eq!(tool.name(), "get_repo");
        assert_eq!(
            tool.remote, "get repo",
            "the server is asked for the name it published, not the sanitised one"
        );
    }

    /// `#418`: `BufReader::lines()` grew a `Vec` to whatever the writer sent, so a server that wrote
    /// a gigabyte without a newline cost a gigabyte before any cap was consulted. The reader keeps
    /// at most `MAX_LINE` bytes and counts the rest.
    #[test]
    fn a_line_over_the_cap_is_counted_and_dropped_not_buffered() {
        // A line that never ends, 4× the cap.
        let big = vec![b'x'; MAX_LINE * 4];
        let mut reader = BufReader::new(&big[..]);
        match read_line_capped(&mut reader, MAX_LINE).unwrap() {
            Some(Line::TooLong(bytes)) => assert_eq!(bytes, MAX_LINE * 4),
            Some(Line::Text(t)) => panic!("kept {} bytes of it", t.len()),
            None => panic!("nothing read at all"),
        }
        // And an ordinary line still arrives whole, with the newline consumed.
        let mut reader = BufReader::new(&b"{\"a\":1}\n{\"b\":2}\n"[..]);
        match read_line_capped(&mut reader, MAX_LINE).unwrap() {
            Some(Line::Text(text)) => assert_eq!(text, "{\"a\":1}"),
            other => panic!("{:?}", other.is_some()),
        }
        match read_line_capped(&mut reader, MAX_LINE).unwrap() {
            Some(Line::Text(text)) => assert_eq!(text, "{\"b\":2}"),
            _ => panic!("the second line did not survive"),
        }
        assert!(read_line_capped(&mut reader, MAX_LINE).unwrap().is_none());
    }

    /// `#418`: killing only the direct child left the real server running when it was started
    /// through `npx`/`sh -c` — the grandchild held the stdout pipe, so the reader thread stayed
    /// blocked on it for the life of the process. The server is in its own process group now and
    /// the drop takes the tree with it.
    #[cfg(unix)]
    #[test]
    fn dropping_a_connection_kills_the_grandchild_holding_the_pipe() {
        if !have_python() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let fake = script(dir.path(), "fake.py", FAKE);
        let pid_file = dir.path().join("grandchild.pid");
        let wrapper = format!(
            "#!/bin/sh\nsleep 300 &\necho $! > {}\nexec python3 {}\n",
            pid_file.display(),
            fake.display()
        );
        let path = script(dir.path(), "wrapper.sh", &wrapper);
        let mut spec = spec(&fake, 10);
        spec.command = "sh".into();
        spec.args = vec![path.to_string_lossy().into_owned()];
        let (server, tools) = Server::start(
            &spec,
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the wrapped server still speaks the protocol");
        assert_eq!(tools.len(), 2);
        let pid: u32 = std::fs::read_to_string(&pid_file)
            .expect("the wrapper recorded its child")
            .trim()
            .parse()
            .expect("a pid");
        assert!(pid_alive(pid), "the grandchild is running");

        drop(server);

        // The group kill is synchronous inside `Drop`, but a pid can linger as a zombie if it was
        // not reaped by its own parent; `pid_alive` treats a zombie as gone. What this asserts is
        // that the tree is gone — not that it went in the same second. The window used to be one
        // second, which failed about once in ten whole-suite runs on a loaded runner (`#432`) while
        // never failing alone: a pid is reaped when its own parent dies, and under contention that
        // bookkeeping is not what the scheduler is spending its time on.
        let mut waited = Duration::ZERO;
        while pid_alive(pid) && waited < Duration::from_secs(10) {
            std::thread::sleep(Duration::from_millis(20));
            waited += Duration::from_millis(20);
        }
        assert!(
            !pid_alive(pid),
            "the grandchild outlived the connection: still alive after {waited:?}"
        );
    }

    #[cfg(unix)]
    fn pid_alive(pid: u32) -> bool {
        let Ok(pid) = libc::pid_t::try_from(pid) else {
            return false;
        };
        // SAFETY: signal 0 asks the kernel whether the pid exists.
        let rc = unsafe { libc::kill(pid, 0) };
        if rc != 0 {
            return false;
        }
        // A zombie still answers signal 0; read its state and call it gone.
        match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
            Ok(stat) => match stat.rsplit_once(')') {
                Some((_, rest)) => !rest.trim_start().starts_with('Z'),
                None => true,
            },
            Err(_) => false,
        }
    }

    #[test]
    fn a_server_is_listed_across_pages_and_its_tools_can_be_called() {
        if !have_python() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = script(dir.path(), "fake.py", FAKE);
        let (server, tools) = Server::start(
            &spec(&path, 10),
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the fake server starts");
        // Both pages: stopping at the first would have hidden `fail_tool` entirely.
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
        assert_eq!(names, ["echo_text", "fail_tool"]);
        let echo = tools.iter().find(|t| t.name == "echo_text").unwrap();
        assert_eq!(echo.description, "Echo the text back");
        assert_eq!(echo.input_schema.as_ref().unwrap()["type"], "object");

        // One connection for both calls: the second answer must not be read from the first's pipe.
        let out = server
            .call_tool("echo_text", &json!({"text": "one"}))
            .unwrap();
        assert_eq!(out, "echo: one");
        let out = server
            .call_tool("echo_text", &json!({"text": "two"}))
            .unwrap();
        assert_eq!(out, "echo: two");

        // A tool that reports failure is an error the model reads, with the server's own words.
        let err = server.call_tool("fail_tool", &json!({})).unwrap_err();
        assert_eq!(err, "the disk is on fire");
    }

    /// `#502`: the transport itself — list across two pages over an event stream, call over a JSON
    /// body, and the session id carried back on every post after `initialize`.
    #[test]
    fn an_http_entry_lists_across_pages_calls_a_tool_and_carries_the_session_id() {
        let fake = FakeHttp::start(None, None);
        let dir = tempfile::tempdir().unwrap();
        let (server, tools) = Server::start(
            &http_spec(&fake.url("/api/mcp")),
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the HTTP server handshakes");
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
        assert_eq!(names, ["echo_text", "fail_tool"], "both pages arrived");
        assert_eq!(
            tools[0].input_schema.as_ref().unwrap()["type"],
            "object",
            "the schema survives the event-stream framing"
        );

        assert_eq!(
            server
                .call_tool("echo_text", &json!({ "text": "ha" }))
                .unwrap(),
            "echo: ha"
        );
        // A tool that reports failure is an error the model reads, with the server's own words —
        // the same as on stdio, because that decision is above the transport.
        assert_eq!(
            server.call_tool("fail_tool", &json!({})).unwrap_err(),
            "the disk is on fire"
        );

        let requests = fake.requests();
        assert_eq!(requests.len(), 6, "initialize, ready, two pages, two calls");
        // Every post after the handshake carries the id the server issued, or the fake answers
        // 400 — which is why the calls above would have failed rather than passed.
        for (head, _) in requests.iter().skip(1) {
            assert_eq!(
                header(head, "mcp-session-id"),
                Some("test-session"),
                "{head}"
            );
        }
        assert_eq!(
            header(&requests[0].0, "accept"),
            Some("application/json, text/event-stream"),
            "the client has to say it can read both, or a server may answer neither"
        );
        assert!(
            requests[0].1.contains("\"initialize\""),
            "{}",
            requests[0].1
        );
        // Page two is a `cursor` in the request: the client has to send back what it was given.
        assert!(
            requests[3].1.contains("\"cursor\""),
            "the second page is asked for by cursor: {}",
            requests[3].1
        );
    }

    /// A server that does not accept us says so with its status, not with a timeout.
    #[test]
    fn a_401_is_reported_as_a_status_and_not_as_a_timeout() {
        let fake = FakeHttp::start(Some("s3cret".into()), None);
        let dir = tempfile::tempdir().unwrap();
        // A name built at runtime, so this stays a test detail rather than a variable the build
        // is documented to read (`every_environment_variable_the_build_reads_is_classified`).
        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_SET");
        let mut spec = http_spec(&fake.url("/api/mcp"));
        spec.token_env = Some(key.clone());
        std::env::set_var(&key, "wrong");
        let err = Server::start(
            &spec,
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect_err("401 is not a handshake");
        assert!(err.contains("401"), "the status is the report: {err}");
        assert!(!err.contains("did not answer"), "{err}");

        // The right token gets through — the same entry, one variable changed.
        std::env::set_var(&key, "s3cret");
        Server::start(
            &spec,
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the right token handshakes");
        std::env::remove_var(&key);
    }

    /// `#516`: a token in `.env` is a token. The config parses that file into `Dotenv.values` and
    /// never touches the process environment, so `token_env` used to be the one credential that
    /// could not see a secret stored where eclipse says secrets live. The assertion is on what
    /// went over the wire, not on a log.
    #[test]
    fn a_token_stored_only_in_dotenv_connects_and_is_what_the_client_sends() {
        let fake = FakeHttp::start(Some("from-file".into()), None);
        let dir = tempfile::tempdir().unwrap();
        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_DOTENV");
        std::env::remove_var(&key);
        let mut spec = http_spec(&fake.url("/api/mcp"));
        spec.token_env = Some(key.clone());
        let mut secrets = Secrets::new();
        secrets.insert(key, "from-file".to_string());

        Server::start(
            &spec,
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &secrets,
        )
        .expect("a token kept in `.env` is a token this build can send");

        let sent = fake
            .requests()
            .into_iter()
            .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
            .expect("the handshake carries an Authorization header");
        assert_eq!(sent, "Bearer from-file", "the value from `.env`, verbatim");
    }

    /// The other half of the order: the process environment wins, so one run can override one
    /// file without editing it.
    #[test]
    fn the_environment_wins_over_dotenv_for_a_token_variable() {
        let fake = FakeHttp::start(Some("from-env".into()), None);
        let dir = tempfile::tempdir().unwrap();
        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_BOTH");
        let mut spec = http_spec(&fake.url("/api/mcp"));
        spec.token_env = Some(key.clone());
        let mut secrets = Secrets::new();
        secrets.insert(key.clone(), "from-file".to_string());
        std::env::set_var(&key, "from-env");

        let started = Server::start(
            &spec,
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &secrets,
        );
        std::env::remove_var(&key);
        started.expect("the environment's value is the one used");

        let sent = fake
            .requests()
            .into_iter()
            .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
            .expect("the handshake carries an Authorization header");
        assert_eq!(
            sent, "Bearer from-env",
            "the environment wins over the file"
        );
    }

    /// An empty value is absent, as it is in `Dotenv::load` — and the refusal names the variable
    /// without printing any other secret that happens to be resolved.
    #[test]
    fn an_empty_dotenv_token_is_absent_and_the_refusal_prints_no_secret() {
        let fake = FakeHttp::start(Some("s3cret".into()), None);
        let dir = tempfile::tempdir().unwrap();
        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_EMPTY");
        std::env::remove_var(&key);
        let mut spec = http_spec(&fake.url("/api/mcp"));
        spec.token_env = Some(key.clone());
        let mut secrets = Secrets::new();
        secrets.insert(key.clone(), String::new());
        secrets.insert(format!("{key}_NEIGHBOUR"), "s3cret".to_string());

        let err = Server::start(
            &spec,
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &secrets,
        )
        .expect_err("an empty value is not a token");
        assert!(err.contains(&key), "{err}");
        assert!(
            err.contains("never reads a token from the manifest"),
            "{err}"
        );
        assert!(
            !err.contains("s3cret"),
            "a refusal is not a place for a value: {err}"
        );
    }

    /// A variable the environment does not set is an error naming it: the alternative is a 401
    /// that reads like the server's fault.
    #[test]
    fn a_token_variable_that_is_not_set_is_named_in_the_error() {
        let fake = FakeHttp::start(Some("s3cret".into()), None);
        let dir = tempfile::tempdir().unwrap();
        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_UNSET");
        let mut spec = http_spec(&fake.url("/api/mcp"));
        spec.token_env = Some(key.clone());
        std::env::remove_var(&key);
        let err = Server::start(
            &spec,
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect_err("no token, no connection");
        assert!(err.contains(&key), "{err}");
        assert!(
            err.contains("never reads a token from the manifest"),
            "{err}"
        );
    }

    /// The one place a `[[mcp]]` entry is checked, both ways round.
    #[test]
    fn a_manifest_that_mixes_transports_is_refused_naming_both() {
        // Default is stdio, so every manifest written before `#502` still means what it meant.
        let old: Spec = toml::from_str(
            "name = \"fs\"\ncommand = \"mcp-server-filesystem\"\nargs = [\"/tmp\"]\n",
        )
        .expect("an entry with no transport is a stdio entry");
        assert_eq!(old.transport, Transport::Stdio);
        assert!(old.validate().is_ok());

        let mut both = http_spec("http://127.0.0.1:1/api/mcp");
        both.command = "mcp-server".into();
        let why = both.validate().unwrap_err();
        assert!(why.contains("command"), "{why}");
        assert!(why.contains("url"), "{why}");
        assert!(why.contains("stdio") && why.contains("http"), "{why}");

        let mut no_url = http_spec("http://127.0.0.1:1/api/mcp");
        no_url.url = None;
        assert!(no_url.validate().unwrap_err().contains("no `url`"));

        let mut no_command = old.clone();
        no_command.command = String::new();
        assert!(no_command
            .validate()
            .unwrap_err()
            .contains("no `command` given"));

        // A stdio entry with a url is a mix too, and says which half to drop.
        let mut stray = old.clone();
        stray.url = Some("http://127.0.0.1:1/api/mcp".into());
        let why = stray.validate().unwrap_err();
        assert!(why.contains("command"), "{why}");
        assert!(why.contains("http"), "{why}");

        // A scheme this client cannot speak is refused before anything is posted.
        let mut bad = http_spec("127.0.0.1:1/api/mcp");
        bad.transport = Transport::Http;
        assert!(bad.validate().unwrap_err().contains("not an http://"));
    }

    /// `#564`: `drain` panics on a byte index that is not a char boundary, and a 1024-byte read frame
    /// lands mid-character as soon as the log is not ASCII. The thread that panics here is the one
    /// draining stderr: it dies, the pipe fills, and the server blocks forever.
    #[test]
    fn a_stderr_tail_is_cut_on_a_character_boundary() {
        // `len - STDERR_KEEP` lands on the second byte of `ě`, which is exactly the panic.
        let mut slot = format!("0123456789ě{}", "x".repeat(STDERR_KEEP - 1));
        let full = slot.len();
        assert_eq!(full - STDERR_KEEP, 11, "the cut lands mid-character");
        keep_tail(&mut slot, STDERR_KEEP);
        assert!(slot.len() <= STDERR_KEEP, "{}", slot.len());
        assert!(slot.ends_with('x'), "the tail is kept: {}", &slot[..4]);
    }

    /// `#567`: a CRLF stream separates events with `\r\n\r\n`, which contains no `\n\n`. Every
    /// `data:` line used to land in one buffer, so a notification ahead of the reply made one
    /// unparsable blob and a good server was reported as "answered with a message for another id".
    #[test]
    fn a_crlf_event_stream_with_a_notification_ahead_of_the_reply_is_split() {
        let text = "event: message\r\n\
                    data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}\r\n\r\n\
                    event: message\r\n\
                    data: {\"jsonrpc\":\"2.0\",\"id\":9,\"result\":{\"ok\":true}}\r\n\r\n";
        let value = sse_payload(text, Some(9));
        assert_eq!(
            value["id"], 9,
            "the reply was found behind the notification"
        );
        assert_eq!(value["result"]["ok"], true);
    }

    /// `#568`: `404` is how a Streamable HTTP server says it does not know the session id it was
    /// sent — a restart, an expired session. The id went back on every later call, so every tool
    /// failed until Eclipse restarted. The connection is dropped now, and the next call handshakes.
    #[test]
    fn a_404_on_the_session_makes_the_next_call_handshake_again() {
        let fake = FakeHttp::start(None, None);
        let dir = tempfile::tempdir().unwrap();
        let (server, _tools) = Server::start(
            &http_spec(&fake.url("/api/mcp")),
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the handshake itself carries no session");

        fake.forget_sessions();
        let first = server.call_tool("echo_text", &json!({ "text": "ha" }));
        assert!(first.is_err(), "the server has forgotten the session");
        assert!(
            first.unwrap_err().to_string().contains("404"),
            "the status is the report"
        );

        let before = fake.seen.lock().unwrap().len();
        let _ = server.call_tool("echo_text", &json!({ "text": "ha" }));
        let seen = fake.seen.lock().unwrap();
        let after: Vec<&String> = seen[before..].iter().map(|(_, body)| body).collect();
        assert!(
            after.iter().any(|b| b.contains("\"initialize\"")),
            "the dead session was reused instead of replaced: {after:?}"
        );
    }

    /// The event-stream parser: a keep-alive, a comment, and a message split over two `data:` lines
    /// with CRLF endings — the shapes a real server puts on the wire.
    #[test]
    fn an_event_stream_is_read_as_json_rpc() {
        let text = ": keep-alive\r\n\r\n\
                    data: {\"jsonrpc\":\"2.0\",\"id\":7,\r\n\
                    data: \"result\":{\"ok\":true}}\r\n\r\n";
        let value = sse_payload(text, Some(7));
        assert_eq!(value["id"], 7);
        assert_eq!(value["result"]["ok"], true);

        // A message for another id is not the answer to this one, and null is not an answer at all.
        assert_eq!(sse_payload(text, Some(8))["id"], 7);
        assert_eq!(sse_payload(": nothing\r\n\r\n", Some(1)), Value::Null);
        // No id asked for — a notification's answer — means the last message wins.
        assert_eq!(sse_payload(text, None)["id"], 7);
    }

    #[test]
    fn a_hanging_server_times_out_and_the_next_call_starts_a_fresh_one() {
        if !have_python() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = script(dir.path(), "fake.py", FAKE);
        let (server, _tools) = Server::start(
            &spec(&path, 1),
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the fake server starts");

        let started = std::time::Instant::now();
        let err = server
            .call_tool("echo_text", &json!({"text": "x", "sleep": true}))
            .unwrap_err();
        assert!(
            err.contains("did not answer") && err.contains("1s"),
            "the timeout names itself: {err}"
        );
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "a hung call returns at the timeout, not when the server wakes up"
        );

        // The poisoned connection was killed, so this is a new process talking to the same server.
        let out = server
            .call_tool("echo_text", &json!({"text": "after"}))
            .unwrap();
        assert_eq!(out, "echo: after");
    }

    #[test]
    fn a_server_that_dies_is_an_error_with_its_own_stderr() {
        if !have_python() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = script(dir.path(), "dies.py", DIES);
        let err = Server::start(
            &spec(&path, 5),
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect_err("a server that exits during the handshake cannot be used");
        assert!(
            err.contains("could not open the database"),
            "the server's own complaint is the error, not a timeout: {err}"
        );
    }

    #[test]
    fn a_policy_override_can_allow_one_tool_and_leave_the_rest_asking() {
        let dir = tempfile::tempdir().unwrap();
        let mut s = spec(Path::new("/bin/true"), 5);
        s.policies.insert("read_text_file".into(), Policy::Allow);
        // No server is started here: the policy is manifest data, and asking for it should not
        // need a process.
        let (server, _) = (
            Arc::new(Server {
                spec: s.clone(),
                plugin_dir: dir.path().to_path_buf(),
                workspace: dir.path().to_path_buf(),
                timeout: Duration::from_secs(5),
                secrets: Secrets::new(),
                next_id: AtomicI64::new(1),
                state: Mutex::new(None),
                handshake: Mutex::new(None),
                stderr: Arc::new(Mutex::new(String::new())),
            }),
            (),
        );
        assert_eq!(server.policy_for("read_text_file"), Policy::Allow);
        assert_eq!(server.policy_for("write_file"), Policy::Ask);
    }

    #[test]
    fn a_cancelled_run_stops_waiting_for_a_server() {
        // The fake hangs a call for 30 s. A cancelled run cannot interrupt a blocking read, but it
        // must stop *waiting*: the answer has nowhere to go, and the next call starts a fresh server
        // anyway.
        if !have_python() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = script(dir.path(), "fake.py", FAKE);
        let (server, _tools) = Server::start(
            &spec(&path, 60),
            dir.path(),
            dir.path(),
            DEFAULT_TEST_TIMEOUT,
            &Secrets::new(),
        )
        .expect("the fake server starts");
        let cancel = crate::cancel::Cancel::new();
        let flag = cancel.clone();
        let canceller = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(150));
            flag.cancel();
        });
        let started = std::time::Instant::now();
        let err = server
            .call_tool_unless("echo_text", &json!({"text": "x", "sleep": true}), &cancel)
            .unwrap_err();
        canceller.join().unwrap();
        assert!(err.contains("cancelled"), "the reason is the cancel: {err}");
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "the wait ended at the cancel, not at the 60 s timeout: {:.2}s",
            started.elapsed().as_secs_f32()
        );
        // A server stopped for a cancel is a server stopped: the next call starts another one.
        let out = server
            .call_tool("echo_text", &json!({"text": "after"}))
            .unwrap();
        assert_eq!(out, "echo: after");
    }

    #[test]
    fn a_result_that_is_not_text_says_so_instead_of_disappearing() {
        let text = content_text(&json!({"content": [
            {"type": "text", "text": "a"},
            {"type": "image", "data": "…"},
            {"type": "text", "text": "b"}
        ]}));
        assert_eq!(
            text,
            "a\n[image content from an MCP server is not shown]\nb"
        );
    }
}