mcp-execution-cli 0.9.0

CLI for MCP progressive loading code generation
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
//! Common utilities shared across CLI commands.
//!
//! Provides shared functionality for building server configurations from CLI arguments
//! and loading MCP server definitions from `~/.claude/mcp.json`.

use anyhow::{Context, Result};
use mcp_execution_core::{
    Error as CoreError, REDACTED_PLACEHOLDER, RedactedItems, RedactedMapValues, RedactedUrl,
    ServerConfig, ServerConfigBuilder, ServerId, sanitize_path_for_error,
};
use mcp_execution_skill::MAX_SERVER_ID_LENGTH;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tracing::{debug, warn};
use url::Url;

/// Fallback slug used when a URL sanitizes down to nothing (e.g. no host).
const FALLBACK_SERVER_ID_SLUG: &str = "http-server";

/// MCP configuration file structure (`~/.claude/mcp.json`).
///
/// The `mcp_servers` field defaults to an empty map so that an absent file or
/// a file containing only `{}` does not produce a deserialization error.
///
/// # Examples
///
/// ```
/// use mcp_execution_cli::commands::common::McpConfig;
/// use std::collections::HashMap;
///
/// let config = McpConfig {
///     mcp_servers: HashMap::new(),
/// };
///
/// assert!(config.mcp_servers.is_empty());
/// ```
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpConfig {
    /// Map of server name → server configuration entry.
    #[serde(default)]
    pub mcp_servers: HashMap<String, McpServerEntry>,
}

/// Canonical in-crate representation of an MCP server's transport.
///
/// This is the single source of truth for "stdio vs http vs sse", shared by
/// both the `mcp.json` config path ([`McpServerEntry`]) and the CLI-flag path
/// ([`TransportArgs`] converts into this via `TryFrom`).
///
/// # Examples
///
/// ```
/// use mcp_execution_cli::commands::common::McpTransport;
/// use std::collections::HashMap;
///
/// let transport = McpTransport::Http {
///     url: "https://api.example.com/mcp".to_string(),
///     headers: HashMap::new(),
/// };
/// assert!(matches!(transport, McpTransport::Http { .. }));
/// ```
///
/// Debug output redacts header/env values (keeping keys), `args` wholesale,
/// and URL userinfo/query strings, mirroring `mcp_execution_core::ServerConfig`:
///
/// ```
/// use mcp_execution_cli::commands::common::McpTransport;
/// use std::collections::HashMap;
///
/// let transport = McpTransport::Http {
///     url: "https://api.example.com/mcp".to_string(),
///     headers: HashMap::from([("Authorization".to_string(), "Bearer sk-secret".to_string())]),
/// };
///
/// let debug_output = format!("{transport:?}");
/// assert!(debug_output.contains("Authorization"));
/// assert!(!debug_output.contains("sk-secret"));
/// ```
#[derive(Clone)]
pub enum McpTransport {
    /// Stdio transport: spawn a subprocess and speak MCP over stdin/stdout.
    Stdio {
        /// Command to execute (binary name or absolute path).
        command: String,
        /// Arguments to pass to the command.
        args: Vec<String>,
        /// Environment variables for the server process.
        env: HashMap<String, String>,
        /// Working directory for the server process.
        cwd: Option<PathBuf>,
    },
    /// Streamable HTTP transport.
    Http {
        /// Server endpoint URL.
        url: String,
        /// HTTP headers sent with every request (e.g. `Authorization`).
        headers: HashMap<String, String>,
    },
    /// Server-Sent Events transport.
    Sse {
        /// Server endpoint URL.
        url: String,
        /// HTTP headers sent with every request (e.g. `Authorization`).
        headers: HashMap<String, String>,
    },
}

impl fmt::Debug for McpTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stdio {
                command,
                args,
                env,
                cwd,
            } => f
                .debug_struct("Stdio")
                .field("command", &sanitize_path_for_error(Path::new(command)))
                .field("args", &RedactedItems(args))
                .field("env", &RedactedMapValues(env))
                .field("cwd", &cwd.as_deref().map(sanitize_path_for_error))
                .finish(),
            Self::Http { url, headers } => f
                .debug_struct("Http")
                .field("url", &RedactedUrl(url))
                .field("headers", &RedactedMapValues(headers))
                .finish(),
            Self::Sse { url, headers } => f
                .debug_struct("Sse")
                .field("url", &RedactedUrl(url))
                .field("headers", &RedactedMapValues(headers))
                .finish(),
        }
    }
}

/// Individual MCP server configuration entry from `mcp.json`.
///
/// # Examples
///
/// ```
/// use mcp_execution_cli::commands::common::McpServerEntry;
/// use std::collections::HashMap;
///
/// let entry = McpServerEntry {
///     transport: mcp_execution_cli::commands::common::McpTransport::Http {
///         url: "https://api.example.com".to_string(),
///         headers: HashMap::new(),
///     },
///     connect_timeout_secs: Some(30),
///     discover_timeout_secs: Some(30),
/// };
///
/// assert_eq!(entry.connect_timeout_secs, Some(30));
/// ```
#[derive(Debug, Clone)]
pub struct McpServerEntry {
    /// The server's transport and its transport-specific settings.
    pub transport: McpTransport,
    /// Connection (handshake) timeout in seconds, overriding the 30-second
    /// default when set. JSON key: `connectTimeoutSecs`.
    pub connect_timeout_secs: Option<u64>,
    /// Tool discovery timeout in seconds, overriding the 30-second default
    /// when set. JSON key: `discoverTimeoutSecs`.
    pub discover_timeout_secs: Option<u64>,
}

/// Discriminant for the optional `"type"` field in an `mcp.json` server entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
enum TransportTag {
    Stdio,
    Http,
    Sse,
}

impl TransportTag {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Stdio => "stdio",
            Self::Http => "http",
            Self::Sse => "sse",
        }
    }
}

/// Flat, all-optional serde landing zone for a raw `mcp.json` server entry.
///
/// Every field is optional so that stdio, http, and sse shapes can share one
/// deserialization pass; [`McpServerEntry`]'s manual `Deserialize` converts
/// this via `TryFrom` and raises precise, field-naming errors for
/// cross-field violations that a derived `Deserialize` can't express (e.g.
/// "http entries must not set `command`"). Unknown keys land in `extra`
/// rather than hard-failing, since `~/.claude/mcp.json` is shared with other
/// MCP clients that store keys this project doesn't model (`disabled`,
/// `alwaysAllow`, ...).
///
/// This is a raw landing zone for the same `mcp.json` data [`McpTransport`]
/// carries, so its hand-written [`Debug`] impl applies the identical
/// redaction: `command`/`cwd` sanitized, `args` redacted wholesale, `url`
/// stripped of userinfo/query, `env`/`headers` values redacted (keys kept),
/// and `extra` values redacted (keys kept) since they are arbitrary JSON
/// this project has not validated.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", rename = "McpServerEntry")]
struct RawMcpServerEntry {
    #[serde(rename = "type")]
    transport_type: Option<TransportTag>,
    command: Option<String>,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    env: HashMap<String, String>,
    cwd: Option<String>,
    url: Option<String>,
    #[serde(default)]
    headers: HashMap<String, String>,
    connect_timeout_secs: Option<u64>,
    discover_timeout_secs: Option<u64>,
    #[serde(flatten)]
    extra: HashMap<String, serde_json::Value>,
}

/// Debug-formats an `extra`-style unknown-fields map with keys visible and
/// every value replaced by [`REDACTED_PLACEHOLDER`].
///
/// `extra` holds arbitrary JSON from a shared `mcp.json` this project
/// doesn't validate — treated as secret-shaped for the same reason
/// [`RedactedMapValues`] treats `env`/`headers` values that way.
struct RedactedExtra<'a>(&'a HashMap<String, serde_json::Value>);

impl fmt::Debug for RedactedExtra<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map()
            .entries(self.0.keys().map(|key| (key, REDACTED_PLACEHOLDER)))
            .finish()
    }
}

impl fmt::Debug for RawMcpServerEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawMcpServerEntry")
            .field("transport_type", &self.transport_type)
            .field(
                "command",
                &self
                    .command
                    .as_deref()
                    .map(|command| sanitize_path_for_error(Path::new(command))),
            )
            .field("args", &RedactedItems(&self.args))
            .field("env", &RedactedMapValues(&self.env))
            .field(
                "cwd",
                &self
                    .cwd
                    .as_deref()
                    .map(|cwd| sanitize_path_for_error(Path::new(cwd))),
            )
            .field("url", &self.url.as_deref().map(RedactedUrl))
            .field("headers", &RedactedMapValues(&self.headers))
            .field("connect_timeout_secs", &self.connect_timeout_secs)
            .field("discover_timeout_secs", &self.discover_timeout_secs)
            .field("extra", &RedactedExtra(&self.extra))
            .finish()
    }
}

/// Resolves the `url`/`command` pair for an http-like (`http` or `sse`)
/// transport tag, rejecting a `command` field and requiring `url`.
fn http_like_transport(
    tag_name: &str,
    command: Option<&str>,
    url: Option<String>,
    headers: HashMap<String, String>,
) -> Result<(String, HashMap<String, String>), String> {
    if command.is_some() {
        return Err(format!("{tag_name} server entry must not set \"command\""));
    }
    let url = url.ok_or_else(|| format!("{tag_name} server entry requires \"url\""))?;
    Ok((url, headers))
}

impl TryFrom<RawMcpServerEntry> for McpServerEntry {
    type Error = String;

    fn try_from(raw: RawMcpServerEntry) -> Result<Self, Self::Error> {
        if !raw.extra.is_empty() {
            let mut keys: Vec<&str> = raw.extra.keys().map(String::as_str).collect();
            keys.sort_unstable();
            warn!(
                "mcp.json server entry has unrecognized field(s), ignoring: {}",
                keys.join(", ")
            );
        }

        let tag = match raw.transport_type {
            Some(tag) => tag,
            None if raw.command.is_some() => TransportTag::Stdio,
            None if raw.url.is_some() => TransportTag::Http,
            None => {
                return Err(
                    "server entry must set either \"command\" (stdio) or \"type\" and \"url\" \
                     (http/sse)"
                        .to_string(),
                );
            }
        };

        let transport = match tag {
            TransportTag::Stdio => {
                if raw.url.is_some() {
                    return Err("stdio server entry must not set \"url\"".to_string());
                }
                let command = raw
                    .command
                    .ok_or_else(|| "stdio server entry requires \"command\"".to_string())?;
                McpTransport::Stdio {
                    command,
                    args: raw.args,
                    env: raw.env,
                    cwd: raw.cwd.map(PathBuf::from),
                }
            }
            TransportTag::Http => {
                let (url, headers) = http_like_transport(
                    tag.as_str(),
                    raw.command.as_deref(),
                    raw.url,
                    raw.headers,
                )?;
                McpTransport::Http { url, headers }
            }
            TransportTag::Sse => {
                let (url, headers) = http_like_transport(
                    tag.as_str(),
                    raw.command.as_deref(),
                    raw.url,
                    raw.headers,
                )?;
                McpTransport::Sse { url, headers }
            }
        };

        Ok(Self {
            transport,
            connect_timeout_secs: raw.connect_timeout_secs,
            discover_timeout_secs: raw.discover_timeout_secs,
        })
    }
}

impl<'de> Deserialize<'de> for McpServerEntry {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = RawMcpServerEntry::deserialize(deserializer)?;
        raw.try_into().map_err(serde::de::Error::custom)
    }
}

/// Loads MCP configuration from the given path.
///
/// This is the primary, testable entry point. [`load_mcp_config`] is a thin
/// wrapper that resolves the default `~/.claude/mcp.json` location.
///
/// # Errors
///
/// Returns an error if the file cannot be read or the JSON is malformed.
fn load_mcp_config_from(path: &Path) -> Result<McpConfig> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read MCP config from {}", path.display()))?;

    serde_json::from_str(&content).context("failed to parse MCP config JSON")
}

/// Loads MCP configuration from `~/.claude/mcp.json`.
///
/// Delegates to [`load_mcp_config_from`] after resolving the default path.
///
/// # Errors
///
/// Returns an error if the home directory cannot be determined, the file
/// cannot be read, or the JSON is malformed.
fn load_mcp_config() -> Result<McpConfig> {
    let home = dirs::home_dir().context("failed to get home directory")?;
    load_mcp_config_from(&home.join(".claude").join("mcp.json"))
}

/// Lists all servers defined in the given `mcp.json` file.
///
/// Returns an empty list when the file does not exist — the primary testable
/// entry point for the "fresh machine" code path (no config file yet).
///
/// # Errors
///
/// Returns an error if the file exists but cannot be read or parsed.
fn list_mcp_servers_from(path: &Path) -> Result<Vec<(String, McpServerEntry)>> {
    if !path.exists() {
        return Ok(Vec::new());
    }
    let config = load_mcp_config_from(path)?;
    Ok(config.mcp_servers.into_iter().collect())
}

/// Lists all servers defined in `~/.claude/mcp.json`.
///
/// Returns an empty list when the config file does not exist so that
/// `server list` shows a clear empty result rather than hard-failing.
///
/// Delegates to [`list_mcp_servers_from`] after resolving the default path.
///
/// Callers may print an entry's `transport` field directly:
/// [`McpTransport`]'s `Debug` impl redacts `headers`/`env` values (keeping
/// keys), so doing so can never leak a secret read from `mcp.json`.
///
/// # Errors
///
/// Returns an error if the home directory cannot be determined, or the config
/// file exists but cannot be read or parsed.
pub(crate) fn list_mcp_servers() -> Result<Vec<(String, McpServerEntry)>> {
    let home = dirs::home_dir().context("failed to get home directory")?;
    list_mcp_servers_from(&home.join(".claude").join("mcp.json"))
}

/// Retrieves a named server from `~/.claude/mcp.json`.
///
/// # Arguments
///
/// * `name` - Server name as defined under `mcpServers` in `mcp.json`
///
/// # Returns
///
/// A tuple of `(ServerId, ServerConfig, McpServerEntry)`:
/// - [`ServerId`] — typed server identifier
/// - [`ServerConfig`] — ready-to-use connection config for `Introspector`
/// - [`McpServerEntry`] — raw entry for display purposes
///
/// # Errors
///
/// Returns an error if the config file is missing, malformed, the named
/// server is not present, or the entry fails [`build_core_config`]'s
/// security validation. Callers that must distinguish "entry absent" from
/// "entry present but invalid" (e.g. to route the latter through a
/// format-aware error path instead of a raw `Err`) should call
/// [`get_mcp_server_entry`] and [`build_core_config`] separately instead.
///
/// Deliberately does *not* validate `name` against
/// [`validate_server_id`](mcp_execution_skill::validate_server_id): this
/// function is shared by `introspect` and `server list`/`server show`, which
/// have no need for `name` to be a filesystem-safe slug — only `generate`
/// turns it into a directory name, so that check lives at `generate`'s own
/// sink (`resolve_server_dir_name`) instead. Enforcing the stricter
/// `[a-z0-9-]` charset here would hard-fail `introspect --from-config` for
/// entirely legitimate `mcp.json` keys that aren't already in that charset
/// (e.g. `claude_ai_Gmail`). [`ServerId::new`]'s own baseline invariant
/// (non-empty, no `..`/path separator) still applies unconditionally, since
/// it's now enforced at construction rather than being an opt-in check.
pub(crate) fn get_mcp_server(name: &str) -> Result<(ServerId, ServerConfig, McpServerEntry)> {
    let (server_id, entry) = get_mcp_server_entry(name)?;
    let server_config = build_core_config(&entry)?;
    Ok((server_id, server_config, entry))
}

/// Looks up a named server's raw [`McpServerEntry`] in `~/.claude/mcp.json`, without running
/// `build_core_config`'s security validation.
///
/// Split out from `get_mcp_server` so callers whose own error handling depends on knowing
/// whether the entry is present at all — regardless of whether it would later pass validation —
/// can perform that check first. `server info`/`server validate` need this: previously, calling
/// `get_mcp_server` made an entry present but failing URL-scheme (or other) validation
/// indistinguishable from an entry that does not exist at all, since both surfaced through the
/// same `with_context` "not found" wrapping.
///
/// # Errors
///
/// Returns an error if the config file is missing or malformed, or the named server is not
/// present.
pub(crate) fn get_mcp_server_entry(name: &str) -> Result<(ServerId, McpServerEntry)> {
    let config = load_mcp_config()?;

    let entry = config
        .mcp_servers
        .get(name)
        .with_context(|| {
            format!(
                "server '{name}' not found in ~/.claude/mcp.json\n\
                 Hint: ensure the server is defined in ~/.claude/mcp.json under \"mcpServers\""
            )
        })?
        .clone();

    let server_id = ServerId::new(name).with_context(|| {
        format!("server '{name}' in ~/.claude/mcp.json is not a valid server id")
    })?;
    Ok((server_id, entry))
}

/// Loads server configuration from `~/.claude/mcp.json` by server name.
///
/// Convenience wrapper around the crate-internal server lookup that drops
/// the raw entry.
///
/// # Arguments
///
/// * `name` - Server name from `mcp.json` (e.g., `"github"`)
///
/// # Errors
///
/// Returns an error if the config file is missing, malformed, or the server
/// name is not present.
pub(crate) fn load_server_from_config(name: &str) -> Result<(ServerId, ServerConfig)> {
    let (id, config, _) = get_mcp_server(name)?;
    Ok((id, config))
}

/// Applies transport-specific settings onto a fresh [`ServerConfig`] builder.
///
/// The single place where [`ServerConfig::builder()`] is invoked; both the
/// `mcp.json` path ([`build_core_config`]) and the CLI-flag path
/// ([`build_server_config`]) funnel through this.
fn builder_for_transport(transport: McpTransport) -> ServerConfigBuilder {
    match transport {
        McpTransport::Stdio {
            command,
            args,
            env,
            cwd,
        } => {
            let mut builder = ServerConfig::builder().command(command);
            if !args.is_empty() {
                builder = builder.args(args);
            }
            for (key, value) in env {
                builder = builder.env(key, value);
            }
            if let Some(dir) = cwd {
                builder = builder.cwd(dir);
            }
            builder
        }
        McpTransport::Http { url, headers } => {
            let mut builder = ServerConfig::builder().http_transport(url);
            for (key, value) in headers {
                builder = builder.header(key, value);
            }
            builder
        }
        McpTransport::Sse { url, headers } => {
            let mut builder = ServerConfig::builder().sse_transport(url);
            for (key, value) in headers {
                builder = builder.header(key, value);
            }
            builder
        }
    }
}

/// Builds a core [`ServerConfig`] from an [`McpServerEntry`].
///
/// `pub(crate)` rather than private: `commands::server`'s `list_servers` also
/// needs it, to build the same `(ServerId, ServerConfig)` pair
/// [`get_mcp_server`] builds internally, without re-reading `mcp.json` for
/// every entry it already has in hand.
///
/// # Errors
///
/// Returns an error if the entry fails [`ServerConfigBuilder::build`]'s
/// security validation (e.g. a shell metacharacter or forbidden environment
/// variable in a hand-edited `mcp.json`).
pub(crate) fn build_core_config(entry: &McpServerEntry) -> Result<ServerConfig> {
    let mut builder = builder_for_transport(entry.transport.clone());

    if let Some(secs) = entry.connect_timeout_secs {
        builder = builder.connect_timeout(Duration::from_secs(secs));
    }

    if let Some(secs) = entry.discover_timeout_secs {
        builder = builder.discover_timeout(Duration::from_secs(secs));
    }

    Ok(builder.build()?)
}

/// Parses a single `KEY=VALUE` CLI argument (used for `--env` and `--header`).
///
/// Security: `s` routinely carries secrets (tokens, API keys) in the value
/// portion, so it must never be echoed into an error message verbatim —
/// mirrors the discipline in `mcp_execution_core::command::validate_header_value_string`.
/// Every error here is a `CoreError::InvalidArgument` (rather than a bare
/// anyhow string) so it classifies as `ExitCode::INVALID_INPUT` downstream
/// in `runner::classify_exit_code`.
fn parse_key_value(s: &str, kind: &str) -> Result<(String, String)> {
    // No `=` at all: the whole string could itself be the secret with no
    // discernible key, so it is never echoed, not even its length (which
    // would narrow the secret's type/format for free in CI logs).
    let Some((key, value)) = s.split_once('=') else {
        return Err(CoreError::InvalidArgument(format!(
            "invalid {kind} format: no '=' separator found (expected KEY=VALUE)"
        ))
        .into());
    };
    if key.is_empty() {
        return Err(CoreError::InvalidArgument(format!(
            "invalid {kind} format: key cannot be empty (expected KEY=VALUE)"
        ))
        .into());
    }
    // A real header/env key never legitimately contains whitespace, `:`, or
    // control characters. Their presence is the signature of the `=` having
    // matched somewhere inside the value instead of acting as the separator
    // — e.g. a header written `Name: Value` by mistake, where the value
    // happens to contain `=` (base64 padding, a JWT). Reject without echoing
    // `key`, since in that scenario it *is* the secret.
    if key
        .chars()
        .any(|c| c.is_whitespace() || c == ':' || c.is_control())
    {
        return Err(CoreError::InvalidArgument(format!(
            "invalid {kind} format: text before '=' contains characters that are never valid \
             in a key, suggesting '=' matched inside a value rather than as the separator; \
             refusing to echo it since it may contain a secret (expected KEY=VALUE)"
        ))
        .into());
    }
    Ok((key.to_string(), value.to_string()))
}

/// CLI-flag mirror of [`McpTransport`], holding the raw, unvalidated
/// `Option`/`Vec<String>` values clap hands back.
///
/// Every variant is a legal state by construction — there is no all-`None`
/// or "both http and sse" shape to represent, unlike the flat flag surface
/// this type is built from. In the real CLI path, values come from
/// [`TryFrom<ServerFlags> for ServerSource`](crate::cli::ServerFlags), the
/// single place "exactly one transport selected" is enforced (backed by
/// clap's `server_source` argument group at parse time); since this type and
/// its fields are `pub`, a direct caller can also construct one by hand
/// (e.g. as a library), which is exactly why every variant already being
/// well-formed matters. `TryFrom<TransportArgs> for McpTransport` does the
/// `KEY=VALUE` parsing for environment variables and headers.
///
/// # Examples
///
/// ```
/// use mcp_execution_cli::commands::common::TransportArgs;
///
/// let transport = TransportArgs::Stdio {
///     command: "github-mcp-server".to_string(),
///     args: vec!["stdio".to_string()],
///     env: vec![],
///     cwd: None,
/// };
/// assert!(matches!(transport, TransportArgs::Stdio { .. }));
/// ```
///
/// Debug output redacts `env`/`headers` entries wholesale, not just a value
/// half — these are raw, unparsed `KEY=VALUE` strings, and per
/// `parse_key_value`'s own doc comment the whole string may be the secret
/// with no discernible key:
///
/// ```
/// use mcp_execution_cli::commands::common::TransportArgs;
///
/// let transport = TransportArgs::Http {
///     url: "https://api.example.com/mcp".to_string(),
///     headers: vec!["Authorization=Bearer sk-secret".to_string()],
/// };
///
/// let debug_output = format!("{transport:?}");
/// assert!(!debug_output.contains("sk-secret"));
/// assert!(!debug_output.contains("Authorization"));
/// assert!(debug_output.contains("<redacted>"));
/// ```
#[derive(Clone)]
pub enum TransportArgs {
    /// Stdio transport (default): raw CLI flags.
    Stdio {
        /// Command to execute (binary name or path).
        command: String,
        /// Arguments to pass to the command.
        args: Vec<String>,
        /// Environment variables in `KEY=VALUE` format.
        env: Vec<String>,
        /// Working directory for the server process.
        cwd: Option<String>,
    },
    /// HTTP transport: raw CLI flags.
    Http {
        /// Server endpoint URL.
        url: String,
        /// HTTP headers in `KEY=VALUE` format.
        headers: Vec<String>,
    },
    /// SSE transport: raw CLI flags.
    Sse {
        /// Server endpoint URL.
        url: String,
        /// HTTP headers in `KEY=VALUE` format.
        headers: Vec<String>,
    },
}

impl fmt::Debug for TransportArgs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stdio {
                command,
                args,
                env,
                cwd,
            } => f
                .debug_struct("Stdio")
                .field("command", &sanitize_path_for_error(Path::new(command)))
                .field("args", &RedactedItems(args))
                .field("env", &RedactedItems(env))
                .field(
                    "cwd",
                    &cwd.as_deref()
                        .map(|cwd| sanitize_path_for_error(Path::new(cwd))),
                )
                .finish(),
            Self::Http { url, headers } => f
                .debug_struct("Http")
                .field("url", &RedactedUrl(url))
                .field("headers", &RedactedItems(headers))
                .finish(),
            Self::Sse { url, headers } => f
                .debug_struct("Sse")
                .field("url", &RedactedUrl(url))
                .field("headers", &RedactedItems(headers))
                .finish(),
        }
    }
}

impl TryFrom<TransportArgs> for McpTransport {
    type Error = anyhow::Error;

    fn try_from(args: TransportArgs) -> Result<Self> {
        match args {
            TransportArgs::Stdio {
                command,
                args,
                env,
                cwd,
            } => {
                let env = env
                    .iter()
                    .map(|s| parse_key_value(s, "environment variable"))
                    .collect::<Result<HashMap<_, _>>>()?;
                Ok(Self::Stdio {
                    command,
                    args,
                    env,
                    cwd: cwd.map(PathBuf::from),
                })
            }
            TransportArgs::Http { url, headers } => {
                let headers = headers
                    .iter()
                    .map(|s| parse_key_value(s, "header"))
                    .collect::<Result<HashMap<_, _>>>()?;
                Ok(Self::Http { url, headers })
            }
            TransportArgs::Sse { url, headers } => {
                let headers = headers
                    .iter()
                    .map(|s| parse_key_value(s, "header"))
                    .collect::<Result<HashMap<_, _>>>()?;
                Ok(Self::Sse { url, headers })
            }
        }
    }
}

/// Builds `ServerConfig` from CLI transport arguments.
///
/// # Arguments
///
/// * `transport` - The selected transport and its raw CLI flags, from a
///   [`ServerSource::Flags`] arm.
/// * `connect_timeout_secs` - Connection (handshake) timeout override, in
///   seconds. Same semantics as `mcp.json`'s `connectTimeoutSecs`: must be
///   greater than zero and at most 600 seconds, enforced by
///   [`ServerConfigBuilder::build`](mcp_execution_core::ServerConfigBuilder::build)
///   at construction time.
/// * `discover_timeout_secs` - Tool discovery timeout override, in seconds.
///   Same semantics as `mcp.json`'s `discoverTimeoutSecs`.
///
/// # Errors
///
/// Returns an error if environment variables or headers are not in
/// `KEY=VALUE` format, or if the resulting [`ServerConfig`] fails security
/// validation (shell metacharacters, forbidden environment variables,
/// invalid URL scheme, unsafe headers, or out-of-bounds timeouts).
pub(crate) fn build_server_config(
    transport: TransportArgs,
    connect_timeout_secs: Option<u64>,
    discover_timeout_secs: Option<u64>,
) -> Result<(ServerId, ServerConfig)> {
    let server_id = match &transport {
        TransportArgs::Stdio { command, .. } => derive_server_id_from_path_or_name(command),
        TransportArgs::Http { url, .. } | TransportArgs::Sse { url, .. } => {
            derive_server_id_from_url(url)
        }
    };

    let mut builder = builder_for_transport(McpTransport::try_from(transport)?);

    if let Some(secs) = connect_timeout_secs {
        builder = builder.connect_timeout(Duration::from_secs(secs));
    }

    if let Some(secs) = discover_timeout_secs {
        builder = builder.discover_timeout(Duration::from_secs(secs));
    }

    Ok((server_id, builder.build()?))
}

/// Fully-resolved "how do I reach this server" selection for `introspect` and
/// `generate`.
///
/// The output of [`TryFrom<ServerFlags> for
/// ServerSource`](crate::cli::ServerFlags), converted from clap's parsed
/// argv once the `server_source` argument group has already guaranteed
/// exactly one selector was set. Unlike the former `RawServerArgs` landing
/// zone, every value of this type is a legal state: `--from-config` and the
/// timeout overrides are folded into the same enum because they belong to
/// the same exclusivity group (a `from_config` selection can never carry a
/// meaningless `connect_timeout_secs`/`discover_timeout_secs` override, since
/// those live on the `Flags` arm only).
///
/// # Examples
///
/// ```
/// use mcp_execution_cli::commands::common::{ServerSource, TransportArgs};
///
/// let source = ServerSource::Flags {
///     transport: TransportArgs::Stdio {
///         command: "github-mcp-server".to_string(),
///         args: vec!["stdio".to_string()],
///         env: vec![],
///         cwd: None,
///     },
///     connect_timeout_secs: None,
///     discover_timeout_secs: None,
/// };
///
/// assert!(matches!(source, ServerSource::Flags { .. }));
/// ```
///
/// Debug output redacts via [`TransportArgs`]'s own redacting `Debug` impl:
///
/// ```
/// use mcp_execution_cli::commands::common::{ServerSource, TransportArgs};
///
/// let source = ServerSource::Flags {
///     transport: TransportArgs::Http {
///         url: "https://api.example.com/mcp".to_string(),
///         headers: vec!["Authorization=Bearer sk-secret".to_string()],
///     },
///     connect_timeout_secs: None,
///     discover_timeout_secs: None,
/// };
///
/// let debug_output = format!("{source:?}");
/// assert!(!debug_output.contains("sk-secret"));
/// ```
#[derive(Debug, Clone)]
pub enum ServerSource {
    /// Load server configuration from `~/.claude/mcp.json` by name.
    Config {
        /// Server name as defined under `mcpServers` in `mcp.json`.
        name: String,
    },
    /// Build server configuration directly from CLI transport flags.
    Flags {
        /// Selected transport and its raw CLI flags.
        transport: TransportArgs,
        /// Connection (handshake) timeout override, in seconds.
        connect_timeout_secs: Option<u64>,
        /// Tool discovery timeout override, in seconds.
        discover_timeout_secs: Option<u64>,
    },
}

/// Resolves a server's [`ServerId`] and [`ServerConfig`] from an
/// already-validated [`ServerSource`], either loading `~/.claude/mcp.json`
/// (`ServerSource::Config`) or building directly from CLI transport flags
/// (`ServerSource::Flags`).
///
/// The single place `generate` and `introspect` share for this "config file
/// vs. CLI flags" branch, since both commands accept the identical flag
/// surface.
///
/// # Errors
///
/// Returns an error if `source` is `Config` and the named server is missing
/// from the config file or the file is malformed, or if `source` is `Flags`
/// and the resulting [`ServerConfig`] fails security validation.
pub(crate) fn resolve_server_config(source: ServerSource) -> Result<(ServerId, ServerConfig)> {
    match source {
        ServerSource::Config { name } => {
            debug!("Loading server configuration from ~/.claude/mcp.json: {name}");
            load_server_from_config(&name)
        }
        ServerSource::Flags {
            transport,
            connect_timeout_secs,
            discover_timeout_secs,
        } => build_server_config(transport, connect_timeout_secs, discover_timeout_secs),
    }
}

/// Lowercases `input`, collapses every run of characters outside
/// `[a-z0-9-]` to a single `-`, and trims leading/trailing `-`, producing a
/// filesystem- and `validate_server_id`-safe [`ServerId`] slug.
///
/// Shared by [`derive_server_id_from_url`] (applied to a URL's host+path) and
/// [`derive_server_id_from_path_or_name`] (applied directly to a stdio
/// command or `--name` override). Since path separators (`/`, `\`) and `.`
/// are outside the whitelist, they can never survive into the slug — a
/// leading `/` or a `..` segment is dropped entirely rather than preserved,
/// which is what makes this safe to use directly on untrusted filesystem-path-shaped
/// input. Falls back to [`FALLBACK_SERVER_ID_SLUG`] if the result would
/// otherwise be empty, and truncates to `MAX_SERVER_ID_LENGTH`.
fn slugify(input: &str) -> ServerId {
    let mut slug = String::with_capacity(input.len());
    for ch in input.chars() {
        let lower = ch.to_ascii_lowercase();
        if lower.is_ascii_lowercase() || lower.is_ascii_digit() {
            slug.push(lower);
        } else if slug.chars().next_back().is_some_and(|last| last != '-') {
            slug.push('-');
        }
    }

    let slug = slug.trim_matches('-');
    let slug = &slug[..slug.len().min(MAX_SERVER_ID_LENGTH)];
    let slug = slug.trim_end_matches('-');

    // The whitelist loop above only ever produces `[a-z0-9-]` characters (or the constant
    // fallback), so the result is always non-empty and free of `..`/path separators — always a
    // valid `ServerId` per `ServerId::new`'s invariant.
    ServerId::new(if slug.is_empty() {
        FALLBACK_SERVER_ID_SLUG
    } else {
        slug
    })
    .expect("slugify only ever produces a valid path-segment ServerId")
}

/// Derives a filesystem- and `validate_server_id`-safe [`ServerId`] slug from
/// an Http/Sse transport URL.
///
/// Using the raw URL as the id (the previous behavior) is unsafe once Http/Sse
/// configs can actually reach `generate`: the id flows into a directory name
/// under `~/.claude/servers/{id}/` and into generated `tool.ts` literals, so a
/// raw URL there breaks `mcp_execution_skill::validate_server_id`'s
/// lowercase/digit/hyphen requirement, can smuggle `..` path segments through
/// `PathBuf::join`, and — if the URL carries `user:token@host` userinfo —
/// leaks the credential into a directory name and generated source.
///
/// Only `host` and `path` are used (never `userinfo`, so credentials are
/// structurally excluded) before delegating to [`slugify`].
fn derive_server_id_from_url(url: &str) -> ServerId {
    // On parse failure, fall through to the empty-slug case below rather than
    // sanitizing the raw string: a URL that failed to parse is about to be
    // rejected by `validate_url_scheme`/the connection attempt anyway, and
    // preserving any part of it here would defeat the credential-exclusion
    // guarantee above for inputs like `https://user:pass@evil.com:99999/x`
    // (a mistyped port is a realistic `Url::parse` failure, not just an
    // adversarial one).
    let host_and_path = Url::parse(url)
        .ok()
        .map(|parsed| format!("{}{}", parsed.host_str().unwrap_or_default(), parsed.path()))
        .unwrap_or_default();

    slugify(&host_and_path)
}

/// Derives a filesystem- and `validate_server_id`-safe [`ServerId`] slug from
/// a stdio transport command or a `--name` override.
///
/// `command`/`name` are attacker-influenced (a CLI argument, or free text an
/// operator might paste from a shared script) and — unlike an Http/Sse URL —
/// commonly *are* legitimate filesystem paths (e.g. `./bin/my-server` or
/// `/usr/local/bin/mcp-server`). Constructing `ServerId` directly from them
/// (the previous behavior) is unsafe because the id flows unmodified into a
/// directory name under `~/.claude/servers/{id}/`
/// (`base_dir.join(&server_dir_name)`): a leading `/` makes `PathBuf::join`
/// discard `base_dir` entirely, and `..` segments walk back out of it.
/// Delegates to [`slugify`], which strips path separators and `..` by
/// construction.
pub(crate) fn derive_server_id_from_path_or_name(raw: &str) -> ServerId {
    slugify(raw)
}

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

    /// Creates a temporary mcp.json file for testing.
    fn create_test_config(content: &str) -> tempfile::NamedTempFile {
        let mut file = tempfile::NamedTempFile::new().unwrap();
        file.write_all(content.as_bytes()).unwrap();
        file.flush().unwrap();
        file
    }

    fn stdio_transport(
        command: &str,
        args: Vec<&str>,
        env: Vec<&str>,
        cwd: Option<&str>,
    ) -> TransportArgs {
        TransportArgs::Stdio {
            command: command.to_string(),
            args: args.into_iter().map(String::from).collect(),
            env: env.into_iter().map(String::from).collect(),
            cwd: cwd.map(String::from),
        }
    }

    fn http_transport(url: &str, headers: Vec<&str>) -> TransportArgs {
        TransportArgs::Http {
            url: url.to_string(),
            headers: headers.into_iter().map(String::from).collect(),
        }
    }

    fn sse_transport(url: &str, headers: Vec<&str>) -> TransportArgs {
        TransportArgs::Sse {
            url: url.to_string(),
            headers: headers.into_iter().map(String::from).collect(),
        }
    }

    #[test]
    fn test_load_mcp_config_from_valid() {
        let json = r#"{"mcpServers": {"github": {"command": "node", "args": ["server.js"]}}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        assert_eq!(config.mcp_servers.len(), 1);
        assert!(config.mcp_servers.contains_key("github"));
    }

    #[test]
    fn test_load_mcp_config_from_empty_servers() {
        // mcp_servers defaults to empty map when key is absent
        let json = r"{}";
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        assert!(config.mcp_servers.is_empty());
    }

    #[test]
    fn test_load_mcp_config_from_minimal_server() {
        // Server with only command (args and env should default), no "type" key
        let json = r#"{"mcpServers": {"minimal": {"command": "python"}}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        let entry = &config.mcp_servers["minimal"];
        match &entry.transport {
            McpTransport::Stdio {
                command, args, env, ..
            } => {
                assert_eq!(command, "python");
                assert!(args.is_empty());
                assert!(env.is_empty());
            }
            other => panic!("expected Stdio transport, got {other:?}"),
        }
    }

    #[test]
    fn test_load_mcp_config_from_multiple_servers() {
        let json = r#"{
            "mcpServers": {
                "server1": {"command": "node", "args": ["s1.js"]},
                "server2": {"command": "python", "args": ["s2.py"]}
            }
        }"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        assert_eq!(config.mcp_servers.len(), 2);
        assert!(config.mcp_servers.contains_key("server1"));
        assert!(config.mcp_servers.contains_key("server2"));
    }

    #[test]
    fn test_load_mcp_config_from_not_found() {
        let result = load_mcp_config_from(Path::new("/nonexistent/path/mcp.json"));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("failed to read"));
    }

    #[test]
    fn test_load_mcp_config_from_malformed_json() {
        let file = create_test_config("not valid json");
        let result = load_mcp_config_from(file.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("parse MCP config"));
    }

    // ── mixed stdio/http/sse configs (#210) ──

    #[test]
    fn test_load_mcp_config_mixed_stdio_http_sse() {
        let json = r#"{
            "mcpServers": {
                "local": {"command": "node", "args": ["server.js"]},
                "remote-http": {"type": "http", "url": "https://api.example.com/mcp", "headers": {"Authorization": "Bearer x"}},
                "remote-sse": {"type": "sse", "url": "https://example.com/sse"}
            }
        }"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        assert_eq!(config.mcp_servers.len(), 3);

        assert!(matches!(
            config.mcp_servers["local"].transport,
            McpTransport::Stdio { .. }
        ));
        assert!(matches!(
            config.mcp_servers["remote-http"].transport,
            McpTransport::Http { .. }
        ));
        assert!(matches!(
            config.mcp_servers["remote-sse"].transport,
            McpTransport::Sse { .. }
        ));
    }

    #[test]
    fn test_load_mcp_config_http_entry_type_absent_but_url_present() {
        // "type" is optional: a bare `url` key alone resolves to Http.
        let json = r#"{"mcpServers": {"remote": {"url": "https://api.example.com/mcp"}}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        assert!(matches!(
            config.mcp_servers["remote"].transport,
            McpTransport::Http { .. }
        ));
    }

    #[test]
    fn test_load_mcp_config_http_entry_missing_url_errors_naming_url() {
        let json = r#"{"mcpServers": {"remote": {"type": "http"}}}"#;
        let file = create_test_config(json);

        let result = load_mcp_config_from(file.path());
        assert!(result.is_err());
        // anyhow's `Display` only prints the outermost context; the field
        // name lives in the wrapped serde_json error, so inspect the chain.
        assert!(format!("{:#}", result.unwrap_err()).contains("url"));
    }

    #[test]
    fn test_load_mcp_config_entry_with_neither_command_nor_type_errors() {
        let json = r#"{"mcpServers": {"broken": {}}}"#;
        let file = create_test_config(json);

        let result = load_mcp_config_from(file.path());
        assert!(result.is_err());
        let msg = format!("{:#}", result.unwrap_err());
        assert!(msg.contains("command"));
        assert!(msg.contains("url"));
    }

    #[test]
    fn test_load_mcp_config_http_entry_with_command_errors() {
        let json = r#"{"mcpServers": {"bad": {"type": "http", "url": "https://x.com", "command": "node"}}}"#;
        let file = create_test_config(json);

        let result = load_mcp_config_from(file.path());
        assert!(result.is_err());
        assert!(format!("{:#}", result.unwrap_err()).contains("command"));
    }

    #[test]
    fn test_load_mcp_config_stdio_entry_with_url_errors() {
        let json = r#"{"mcpServers": {"bad": {"command": "node", "url": "https://x.com"}}}"#;
        let file = create_test_config(json);

        let result = load_mcp_config_from(file.path());
        assert!(result.is_err());
        assert!(format!("{:#}", result.unwrap_err()).contains("url"));
    }

    #[test]
    fn test_load_mcp_config_unknown_field_still_parses() {
        // Unrecognized keys (owned by other MCP clients sharing the file,
        // e.g. Claude Code's "disabled") must warn, not fail the whole file.
        let json = r#"{"mcpServers": {"github": {"command": "node", "disabled": false, "description": "x"}}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        assert!(matches!(
            config.mcp_servers["github"].transport,
            McpTransport::Stdio { .. }
        ));
    }

    #[test]
    fn test_build_server_config_stdio() {
        let (id, config) = build_server_config(
            stdio_transport(
                "github-mcp-server",
                vec!["stdio"],
                vec!["TOKEN=abc123"],
                None,
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(id.as_str(), "github-mcp-server");
        assert_eq!(config.command(), Some("github-mcp-server"));
        assert_eq!(config.args(), &["stdio"]);
        assert_eq!(config.env().get("TOKEN"), Some(&"abc123".to_string()));
    }

    #[test]
    fn test_build_server_config_docker() {
        let (id, config) = build_server_config(
            stdio_transport(
                "docker",
                vec!["run", "-i", "--rm", "ghcr.io/github/github-mcp-server"],
                vec!["GITHUB_PERSONAL_ACCESS_TOKEN=ghp_xxx"],
                None,
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(id.as_str(), "docker");
        assert_eq!(config.command(), Some("docker"));
        assert_eq!(
            config.args(),
            &["run", "-i", "--rm", "ghcr.io/github/github-mcp-server"]
        );
        assert_eq!(
            config.env().get("GITHUB_PERSONAL_ACCESS_TOKEN"),
            Some(&"ghp_xxx".to_string())
        );
    }

    #[test]
    fn test_build_server_config_http() {
        let (id, config) = build_server_config(
            http_transport(
                "https://api.githubcopilot.com/mcp/",
                vec!["Authorization=Bearer token123"],
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(id.as_str(), "api-githubcopilot-com-mcp");
        assert_eq!(config.url(), Some("https://api.githubcopilot.com/mcp/"));
        assert_eq!(
            config.headers().get("Authorization"),
            Some(&"Bearer token123".to_string())
        );
    }

    #[test]
    fn test_build_server_config_sse() {
        let (id, config) = build_server_config(
            sse_transport("https://example.com/sse", vec!["X-API-Key=secret"]),
            None,
            None,
        )
        .unwrap();

        assert_eq!(id.as_str(), "example-com-sse");
        assert_eq!(config.url(), Some("https://example.com/sse"));
        assert_eq!(
            config.headers().get("X-API-Key"),
            Some(&"secret".to_string())
        );
    }

    #[test]
    fn test_build_server_config_with_cwd() {
        let (_, config) = build_server_config(
            stdio_transport("server", vec![], vec![], Some("/tmp/workdir")),
            None,
            None,
        )
        .unwrap();

        assert_eq!(config.cwd(), Some(PathBuf::from("/tmp/workdir")).as_ref());
    }

    #[test]
    fn test_build_server_config_invalid_env() {
        // Regression test for #190: a malformed `--env` value with no `=` is
        // itself indistinguishable from a raw secret and must never be
        // echoed — checked against the `{:?}` chain, since that's what
        // `runner::execute_command` actually prints to stderr.
        let secret = "ghp_verySECRETtoken1234567890abcdef";
        let result = build_server_config(
            stdio_transport("server", vec![], vec![secret], None),
            None,
            None,
        );

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(format!("{err:?}").contains("expected KEY=VALUE"));
        assert!(
            !format!("{err:?}").contains(secret),
            "error chain leaked the raw secret: {err:?}"
        );
    }

    #[test]
    fn test_build_server_config_invalid_header() {
        // Regression test for #190: same guarantee for `--header` values,
        // which routinely carry bearer tokens / API keys.
        let secret = "Bearer sk-live-supersecretvalue1234567890";
        let result = build_server_config(
            http_transport("https://example.com", vec![secret]),
            None,
            None,
        );

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(format!("{err:?}").contains("expected KEY=VALUE"));
        assert!(
            !format!("{err:?}").contains(secret),
            "error chain leaked the raw secret: {err:?}"
        );
    }

    #[test]
    fn test_mcp_transport_debug_redacts_headers_http() {
        // Regression test for #229: `McpTransport::Http`/`Sse` carry real
        // bearer tokens read from `~/.claude/mcp.json`; the plain derived
        // `Debug` used to echo them verbatim. Asserting on the bare
        // `sk-...` substring (not just the exact original string) catches
        // an impl that truncates instead of replacing the value.
        let secret_body = "sk-verySECRETtoken1234567890";
        let secret = format!("Bearer {secret_body}");
        let transport = McpTransport::Http {
            url: "https://api.example.com/mcp".to_string(),
            headers: HashMap::from([("Authorization".to_string(), secret.clone())]),
        };

        let debug_output = format!("{transport:?}");
        assert!(debug_output.contains("Authorization"));
        assert!(debug_output.contains("<redacted>"));
        assert!(!debug_output.contains(&secret));
        assert!(!debug_output.contains(secret_body));
    }

    #[test]
    fn test_mcp_transport_debug_redacts_headers_sse() {
        // Regression test for #229/M1: the `Sse` arm is copy-pasted from
        // `Http` and had no dedicated coverage.
        let secret_body = "sk-verySECRETtoken1234567890";
        let secret = format!("Bearer {secret_body}");
        let transport = McpTransport::Sse {
            url: "https://api.example.com/sse".to_string(),
            headers: HashMap::from([("Authorization".to_string(), secret.clone())]),
        };

        let debug_output = format!("{transport:?}");
        assert!(debug_output.contains("Authorization"));
        assert!(debug_output.contains("<redacted>"));
        assert!(!debug_output.contains(&secret));
        assert!(!debug_output.contains(secret_body));
    }

    #[test]
    fn test_mcp_transport_debug_redacts_env() {
        let secret_body = "ghp_verySECRETtoken1234567890abcdef";
        let transport = McpTransport::Stdio {
            command: "node".to_string(),
            args: vec![],
            env: HashMap::from([("GITHUB_TOKEN".to_string(), secret_body.to_string())]),
            cwd: None,
        };

        let debug_output = format!("{transport:?}");
        assert!(debug_output.contains("GITHUB_TOKEN"));
        assert!(debug_output.contains("<redacted>"));
        assert!(!debug_output.contains(secret_body));
    }

    #[test]
    fn test_mcp_server_entry_debug_redacts_via_transport() {
        // `McpServerEntry` derives `Debug`, so it must inherit the
        // redaction through `McpTransport`'s custom impl rather than
        // needing its own.
        let secret_body = "sk-verySECRETtoken1234567890";
        let secret = format!("Bearer {secret_body}");
        let entry = McpServerEntry {
            transport: McpTransport::Http {
                url: "https://api.example.com/mcp".to_string(),
                headers: HashMap::from([("Authorization".to_string(), secret.clone())]),
            },
            connect_timeout_secs: None,
            discover_timeout_secs: None,
        };

        let debug_output = format!("{entry:?}");
        assert!(debug_output.contains("Authorization"));
        assert!(!debug_output.contains(&secret));
        assert!(!debug_output.contains(secret_body));
    }

    #[test]
    fn test_server_source_debug_redacts_via_transport() {
        // `ServerSource` derives `Debug`, so it must inherit the redaction
        // through `TransportArgs`'s custom impl rather than needing its own —
        // same pattern as `McpServerEntry` inheriting from `McpTransport`.
        let secret_body = "sk-verySECRETtoken1234567890";
        let secret = format!("Bearer {secret_body}");
        let source = ServerSource::Flags {
            transport: TransportArgs::Http {
                url: "https://api.example.com/mcp".to_string(),
                headers: vec![format!("Authorization={secret}")],
            },
            connect_timeout_secs: None,
            discover_timeout_secs: None,
        };

        let debug_output = format!("{source:?}");
        assert!(!debug_output.contains(&secret));
        assert!(!debug_output.contains(secret_body));
        assert!(debug_output.contains("<redacted>"));
    }

    #[test]
    fn test_transport_args_debug_redacts_headers_and_env() {
        // Regression test for #229/S1: `TransportArgs` is the CLI-flag
        // mirror of `McpTransport` and holds raw, unparsed `KEY=VALUE`
        // strings; its derived `Debug` used to echo them verbatim.
        let secret_body = "sk-verySECRETtoken1234567890";
        let header_entry = format!("Authorization=Bearer {secret_body}");
        let http = TransportArgs::Http {
            url: "https://api.example.com/mcp".to_string(),
            headers: vec![header_entry.clone()],
        };
        let http_debug = format!("{http:?}");
        assert!(!http_debug.contains(&header_entry));
        assert!(!http_debug.contains(secret_body));
        assert!(!http_debug.contains("Authorization"));
        assert!(http_debug.contains("<redacted>"));

        let sse = TransportArgs::Sse {
            url: "https://api.example.com/sse".to_string(),
            headers: vec![header_entry.clone()],
        };
        let sse_debug = format!("{sse:?}");
        assert!(!sse_debug.contains(&header_entry));
        assert!(!sse_debug.contains(secret_body));

        let env_entry = format!("GITHUB_TOKEN={secret_body}");
        let stdio = TransportArgs::Stdio {
            command: "node".to_string(),
            args: vec![],
            env: vec![env_entry.clone()],
            cwd: None,
        };
        let stdio_debug = format!("{stdio:?}");
        assert!(!stdio_debug.contains(&env_entry));
        assert!(!stdio_debug.contains(secret_body));
        assert!(!stdio_debug.contains("GITHUB_TOKEN"));
        assert!(stdio_debug.contains("<redacted>"));
    }

    #[test]
    fn test_mcp_transport_debug_redacts_args() {
        let secret = "sk-live-secret";
        let transport = McpTransport::Stdio {
            command: "node".to_string(),
            args: vec!["--api-key".to_string(), secret.to_string()],
            env: HashMap::new(),
            cwd: None,
        };

        let debug_output = format!("{transport:?}");
        assert!(!debug_output.contains(secret));
    }

    #[test]
    fn test_mcp_transport_debug_redacts_url_userinfo_and_query() {
        let secret = "hunter2";
        let http = McpTransport::Http {
            url: format!("https://user:{secret}@api.example.com/mcp?token={secret}"),
            headers: HashMap::new(),
        };
        let http_debug = format!("{http:?}");
        assert!(!http_debug.contains(secret));
        assert!(http_debug.contains("api.example.com/mcp"));

        let sse = McpTransport::Sse {
            url: format!("https://user:{secret}@api.example.com/sse?token={secret}"),
            headers: HashMap::new(),
        };
        let sse_debug = format!("{sse:?}");
        assert!(!sse_debug.contains(secret));
        assert!(sse_debug.contains("api.example.com/sse"));
    }

    #[test]
    fn test_transport_args_debug_redacts_args() {
        let secret = "sk-live-secret";
        let stdio = TransportArgs::Stdio {
            command: "node".to_string(),
            args: vec!["--api-key".to_string(), secret.to_string()],
            env: vec![],
            cwd: None,
        };

        let debug_output = format!("{stdio:?}");
        assert!(!debug_output.contains(secret));
    }

    #[test]
    fn test_transport_args_debug_redacts_url_userinfo_and_query() {
        let secret = "hunter2";
        let http = TransportArgs::Http {
            url: format!("https://user:{secret}@api.example.com/mcp?token={secret}"),
            headers: vec![],
        };
        let http_debug = format!("{http:?}");
        assert!(!http_debug.contains(secret));
        assert!(http_debug.contains("api.example.com/mcp"));
    }

    #[test]
    fn test_raw_mcp_server_entry_debug_redacts_secret_shaped_fields() {
        let secret = "sk-live-secret";
        let entry = RawMcpServerEntry {
            transport_type: Some(TransportTag::Stdio),
            command: Some("node".to_string()),
            args: vec!["--api-key".to_string(), secret.to_string()],
            env: HashMap::from([("GITHUB_TOKEN".to_string(), secret.to_string())]),
            cwd: None,
            url: None,
            headers: HashMap::new(),
            connect_timeout_secs: None,
            discover_timeout_secs: None,
            extra: HashMap::from([(
                "someUnknownSecret".to_string(),
                serde_json::Value::String(secret.to_string()),
            )]),
        };

        let debug_output = format!("{entry:?}");
        assert!(!debug_output.contains(secret));
        // Keys stay visible for debugging.
        assert!(debug_output.contains("GITHUB_TOKEN"));
        assert!(debug_output.contains("someUnknownSecret"));
        assert!(debug_output.contains("node"));
    }

    #[test]
    fn test_build_server_config_header_name_value_typo_does_not_leak_secret() {
        // Regression test for #190/S1: a header written with the conventional
        // `Name: Value` syntax (colon) instead of `Name=Value`, where the
        // value contains `=` (e.g. base64 padding), previously put the whole
        // secret into the "key" slot. That key then reached
        // `mcp_execution_core::command::validate_header_name_string`, whose
        // error message assumes header names are never secret and echoes
        // them verbatim — leaking the credential one function downstream of
        // the original fix.
        let secret = "c2VjcmV0dG9rZW4=";
        let header = format!("Authorization: Bearer {secret}");
        let result = build_server_config(
            http_transport("https://example.com", vec![&header]),
            None,
            None,
        );

        let err = result.unwrap_err();
        assert!(
            !format!("{err:?}").contains(secret),
            "error chain leaked the raw secret: {err:?}"
        );
        assert!(
            !format!("{err:?}").contains(&header),
            "error chain leaked the raw header argument: {err:?}"
        );
    }

    #[test]
    fn test_build_server_config_invalid_env_classifies_as_invalid_argument() {
        // Regression test for #195/S3: malformed `--env`/`--header` values are
        // the most common invalid-input path for `introspect`/`generate`. The
        // error must carry a `CoreError::InvalidArgument` so
        // `runner::classify_exit_code` maps it to `ExitCode::INVALID_INPUT`
        // instead of silently falling through to the generic `ExitCode::ERROR`.
        let result = build_server_config(
            stdio_transport("server", vec![], vec!["INVALID_FORMAT"], None),
            None,
            None,
        );

        let err = result.unwrap_err();
        assert!(matches!(
            err.downcast_ref::<CoreError>(),
            Some(CoreError::InvalidArgument(_))
        ));
    }

    #[test]
    fn test_build_server_config_multiple_env_vars() {
        let (_, config) = build_server_config(
            stdio_transport(
                "server",
                vec![],
                vec!["TOKEN=abc123", "API_KEY=secret456", "DEBUG=true"],
                None,
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(config.env().get("TOKEN"), Some(&"abc123".to_string()));
        assert_eq!(config.env().get("API_KEY"), Some(&"secret456".to_string()));
        assert_eq!(config.env().get("DEBUG"), Some(&"true".to_string()));
        assert_eq!(config.env().len(), 3);
    }

    #[test]
    fn test_build_server_config_env_with_special_chars() {
        // Test environment variable values containing equals signs
        let (_, config) = build_server_config(
            stdio_transport(
                "server",
                vec![],
                vec![
                    "TOKEN=abc=def=123",
                    "URL=https://example.com?key=value",
                    "ENCODED=a=b=c=d",
                ],
                None,
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(config.env().get("TOKEN"), Some(&"abc=def=123".to_string()));
        assert_eq!(
            config.env().get("URL"),
            Some(&"https://example.com?key=value".to_string())
        );
        assert_eq!(config.env().get("ENCODED"), Some(&"a=b=c=d".to_string()));
    }

    #[test]
    fn test_build_server_config_empty_args_stdio() {
        let (id, config) = build_server_config(
            stdio_transport("simple-server", vec![], vec![], None),
            None,
            None,
        )
        .unwrap();

        assert_eq!(id.as_str(), "simple-server");
        assert_eq!(config.command(), Some("simple-server"));
        assert!(config.args().is_empty());
        assert!(config.env().is_empty());
    }

    #[test]
    fn test_build_server_config_http_multiple_headers() {
        let (_, config) = build_server_config(
            http_transport(
                "https://api.example.com",
                vec![
                    "Authorization=Bearer token123",
                    "X-API-Key=secret",
                    "Content-Type=application/json",
                ],
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(
            config.headers().get("Authorization"),
            Some(&"Bearer token123".to_string())
        );
        assert_eq!(
            config.headers().get("X-API-Key"),
            Some(&"secret".to_string())
        );
        assert_eq!(
            config.headers().get("Content-Type"),
            Some(&"application/json".to_string())
        );
        assert_eq!(config.headers().len(), 3);
    }

    #[test]
    fn test_build_server_config_header_with_special_chars() {
        // Test header values containing equals signs
        let (_, config) = build_server_config(
            http_transport(
                "https://api.example.com",
                vec!["X-Custom=value=with=equals", "X-Query=a=b&c=d"],
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(
            config.headers().get("X-Custom"),
            Some(&"value=with=equals".to_string())
        );
        assert_eq!(
            config.headers().get("X-Query"),
            Some(&"a=b&c=d".to_string())
        );
    }

    #[test]
    fn test_build_server_config_sse_with_headers() {
        let (id, config) = build_server_config(
            sse_transport(
                "https://sse.example.com/events",
                vec!["Authorization=Bearer xyz"],
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(id.as_str(), "sse-example-com-events");
        assert_eq!(config.url(), Some("https://sse.example.com/events"));
        assert_eq!(
            config.headers().get("Authorization"),
            Some(&"Bearer xyz".to_string())
        );
    }

    #[test]
    fn test_build_server_config_empty_value_in_env() {
        // Test environment variable with empty value after equals
        let (_, config) = build_server_config(
            stdio_transport("server", vec![], vec!["EMPTY="], None),
            None,
            None,
        )
        .unwrap();

        assert_eq!(config.env().get("EMPTY"), Some(&String::new()));
    }

    #[test]
    fn test_build_server_config_empty_value_in_header() {
        // Test header with empty value after equals
        let (_, config) = build_server_config(
            http_transport("https://example.com", vec!["X-Empty="]),
            None,
            None,
        )
        .unwrap();

        assert_eq!(config.headers().get("X-Empty"), Some(&String::new()));
    }

    #[test]
    fn test_build_server_config_complex_docker_scenario() {
        let (id, config) = build_server_config(
            stdio_transport(
                "docker",
                vec!["run", "-i", "--rm", "--network=host", "my-image:latest"],
                vec!["API_TOKEN=secret123", "LOG_LEVEL=debug"],
                Some("/app/workdir"),
            ),
            None,
            None,
        )
        .unwrap();

        assert_eq!(id.as_str(), "docker");
        assert_eq!(config.command(), Some("docker"));
        assert_eq!(
            config.args(),
            &["run", "-i", "--rm", "--network=host", "my-image:latest"]
        );
        assert_eq!(
            config.env().get("API_TOKEN"),
            Some(&"secret123".to_string())
        );
        assert_eq!(config.env().get("LOG_LEVEL"), Some(&"debug".to_string()));
        assert_eq!(config.cwd(), Some(PathBuf::from("/app/workdir")).as_ref());
    }

    #[test]
    fn test_build_server_config_empty_key_in_env() {
        // Regression test for #190: the pre-fix message echoed the raw `s`
        // (e.g. "=secretvalue"), leaking the value even though the key was
        // reported empty.
        let secret = "topsecretvalue";
        let env_arg = format!("={secret}");
        let result = build_server_config(
            stdio_transport("server", vec![], vec![&env_arg], None),
            None,
            None,
        );

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(format!("{err:?}").contains("key cannot be empty"));
        assert!(
            !format!("{err:?}").contains(secret),
            "error chain leaked the raw secret: {err:?}"
        );
    }

    #[test]
    fn test_build_server_config_empty_key_in_header() {
        let secret = "topsecretheadervalue";
        let header_arg = format!("={secret}");
        let result = build_server_config(
            http_transport("https://example.com", vec![&header_arg]),
            None,
            None,
        );

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(format!("{err:?}").contains("key cannot be empty"));
        assert!(
            !format!("{err:?}").contains(secret),
            "error chain leaked the raw secret: {err:?}"
        );
    }

    #[test]
    fn test_build_server_config_timeout_override_reaches_core_validation() {
        // The manual CLI-flag path must fail identically to the mcp.json path:
        // both end up calling the same `ServerConfigBuilder::build`, so a zero
        // override must trip the same `connect_timeout` ValidationError — now
        // surfaced directly by `build_server_config` itself, since
        // `ServerConfig` can no longer be constructed unvalidated (#177).
        let result = build_server_config(
            stdio_transport("docker", vec![], vec![], None),
            Some(0),
            None,
        );

        let err = result.unwrap_err();
        let core_err = err.downcast::<mcp_execution_core::Error>().unwrap();
        if let mcp_execution_core::Error::ValidationError { field, reason } = core_err {
            assert_eq!(field, "connect_timeout");
            assert!(reason.contains("greater than zero"));
        } else {
            panic!("expected ValidationError for connect_timeout");
        }
    }

    #[test]
    fn test_build_server_config_timeout_overrides() {
        let (_, config) = build_server_config(
            stdio_transport("server", vec![], vec![], None),
            Some(5),
            Some(90),
        )
        .unwrap();

        assert_eq!(config.connect_timeout(), Duration::from_secs(5));
        assert_eq!(config.discover_timeout(), Duration::from_secs(90));
    }

    #[test]
    fn test_build_server_config_default_timeouts_without_overrides() {
        let (_, config) =
            build_server_config(stdio_transport("server", vec![], vec![], None), None, None)
                .unwrap();

        assert_eq!(config.connect_timeout(), Duration::from_secs(30));
        assert_eq!(config.discover_timeout(), Duration::from_secs(30));
    }

    #[test]
    fn test_load_server_from_config_not_found() {
        // Should fail because either config doesn't exist or server not in it
        let result = load_server_from_config("nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_load_mcp_config_no_file() {
        // Should fail gracefully when config file doesn't exist
        let result = load_mcp_config_from(Path::new("/nonexistent/mcp.json"));

        if let Err(error) = result {
            let error = error.to_string();
            assert!(
                error.contains("failed to read MCP config")
                    || error.contains("failed to get home directory"),
                "Expected config read error or home dir error, got: {error}"
            );
        }
    }

    #[test]
    fn test_list_mcp_servers_from_missing_file_returns_empty() {
        // GAP-1: the primary UX fix for #81 — missing config → empty list, not error.
        let result = list_mcp_servers_from(Path::new("/nonexistent/path/mcp.json"));
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_list_mcp_servers_from_valid_file() {
        let json = r#"{"mcpServers": {"github": {"command": "node"}}}"#;
        let file = create_test_config(json);

        let servers = list_mcp_servers_from(file.path()).unwrap();
        assert_eq!(servers.len(), 1);
        assert_eq!(servers[0].0, "github");
        assert!(matches!(
            servers[0].1.transport,
            McpTransport::Stdio { ref command, .. } if command == "node"
        ));
    }

    #[test]
    fn test_list_mcp_servers_from_empty_servers_key() {
        let json = r#"{"mcpServers": {}}"#;
        let file = create_test_config(json);

        let servers = list_mcp_servers_from(file.path()).unwrap();
        assert!(servers.is_empty());
    }

    #[test]
    fn test_load_mcp_config_without_timeout_keys_uses_defaults() {
        let json = r#"{"mcpServers": {"github": {"command": "node"}}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        let entry = &config.mcp_servers["github"];
        assert_eq!(entry.connect_timeout_secs, None);
        assert_eq!(entry.discover_timeout_secs, None);

        let server_config = build_core_config(entry).unwrap();
        assert_eq!(server_config.connect_timeout(), Duration::from_secs(30));
        assert_eq!(server_config.discover_timeout(), Duration::from_secs(30));
    }

    #[test]
    fn test_load_mcp_config_with_timeout_keys_reaches_server_config() {
        let json = r#"{"mcpServers": {"github": {
            "command": "node",
            "connectTimeoutSecs": 5,
            "discoverTimeoutSecs": 90
        }}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        let entry = &config.mcp_servers["github"];
        assert_eq!(entry.connect_timeout_secs, Some(5));
        assert_eq!(entry.discover_timeout_secs, Some(90));

        let server_config = build_core_config(entry).unwrap();
        assert_eq!(server_config.connect_timeout(), Duration::from_secs(5));
        assert_eq!(server_config.discover_timeout(), Duration::from_secs(90));
    }

    #[test]
    fn test_build_core_config_http_entry_reaches_server_config() {
        // The mcp.json -> ServerConfig path (what #210 is literally about),
        // as opposed to the CLI-flag path already covered by
        // `test_build_server_config_http`.
        let json = r#"{"mcpServers": {"remote": {"type": "http", "url": "https://api.example.com/mcp", "headers": {"Authorization": "Bearer x"}}}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        let entry = &config.mcp_servers["remote"];

        let server_config = build_core_config(entry).unwrap();
        assert_eq!(server_config.url(), Some("https://api.example.com/mcp"));
        assert_eq!(
            server_config.headers().get("Authorization"),
            Some(&"Bearer x".to_string())
        );
    }

    #[test]
    fn test_build_core_config_stdio_cwd_reaches_server_config() {
        let json = r#"{"mcpServers": {"local": {"command": "node", "cwd": "/tmp/workdir"}}}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        let entry = &config.mcp_servers["local"];

        let server_config = build_core_config(entry).unwrap();
        assert_eq!(server_config.cwd(), Some(&PathBuf::from("/tmp/workdir")));
    }

    #[test]
    fn test_load_mcp_config_serde_default_on_missing_mcp_servers() {
        // When mcp.json has no mcpServers key, should deserialize to empty map
        let json = r#"{"someOtherKey": "value"}"#;
        let file = create_test_config(json);

        let config = load_mcp_config_from(file.path()).unwrap();
        assert!(
            config.mcp_servers.is_empty(),
            "missing mcpServers key must produce empty map, not error"
        );
    }

    // ── derive_server_id_from_url (review S1: raw-URL server ids are unsafe) ──

    #[test]
    fn test_derive_server_id_from_url_basic() {
        assert_eq!(
            derive_server_id_from_url("https://api.githubcopilot.com/mcp/").as_str(),
            "api-githubcopilot-com-mcp"
        );
        assert_eq!(
            derive_server_id_from_url("https://example.com/sse").as_str(),
            "example-com-sse"
        );
    }

    #[test]
    fn test_derive_server_id_from_url_strips_credentials() {
        // Userinfo (credentials) must never end up in the derived id: it flows
        // into a directory name and generated tool.ts source.
        let id = derive_server_id_from_url("https://user:sekrit-token@api.example.com/mcp");
        assert!(!id.as_str().contains("sekrit"));
        assert!(!id.as_str().contains("user"));
        assert_eq!(id.as_str(), "api-example-com-mcp");
    }

    #[test]
    fn test_derive_server_id_from_url_rejects_path_traversal_chars() {
        // `..` segments must not survive into the id (which is later joined
        // into a filesystem path via PathBuf::join).
        let id = derive_server_id_from_url("https://api.example.com/../../etc/passwd");
        assert!(!id.as_str().contains(".."));
        assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
    }

    #[test]
    fn test_derive_server_id_from_url_join_never_escapes_base_dir() {
        // Literal reproduction of how `generate.rs` uses the id: joined onto
        // a base directory. Since the sanitized slug can only ever contain
        // `[a-z0-9-]`, `PathBuf::join` can never interpret a component of it
        // as `..` or an absolute-path override, regardless of what path
        // segments were present in the original URL.
        let base_dir = PathBuf::from("/home/user/.claude/servers");
        let malicious_urls = [
            "https://api.example.com/../../../../etc/passwd",
            "https://api.example.com/..%2f..%2fescape",
            "https://api.example.com/./././escape",
        ];

        for url in malicious_urls {
            let id = derive_server_id_from_url(url);
            let joined = base_dir.join(id.as_str());
            assert!(
                joined.starts_with(&base_dir),
                "joining derived id {:?} (from {url:?}) onto {base_dir:?} escaped it: {joined:?}",
                id.as_str()
            );
        }
    }

    #[test]
    fn test_derive_server_id_from_url_normalizes_case() {
        assert_eq!(
            derive_server_id_from_url("https://API.Example.COM/MCP").as_str(),
            "api-example-com-mcp"
        );
    }

    #[test]
    fn test_derive_server_id_from_url_truncates_to_length_limit() {
        let long_path = "a".repeat(200);
        let id = derive_server_id_from_url(&format!("https://example.com/{long_path}"));
        assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
    }

    #[test]
    fn test_derive_server_id_from_url_falls_back_when_empty() {
        // `Url::parse` accepts "..." as a (degenerate but valid) host, so
        // this genuinely exercises the "parsed OK, but sanitizes to nothing"
        // path, not the parse-failure path covered by the test below.
        let id = derive_server_id_from_url("https://...");
        assert_eq!(id.as_str(), FALLBACK_SERVER_ID_SLUG);
        assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
    }

    #[test]
    fn test_derive_server_id_from_url_falls_back_on_unparseable_url() {
        // On a `Url::parse` failure the raw input is discarded entirely
        // (never sanitized-and-reused) — every unparseable URL maps to the
        // same fixed fallback slug, regardless of its content.
        for unparseable in ["not a url at all", "", "://", "!!!"] {
            let id = derive_server_id_from_url(unparseable);
            assert_eq!(
                id.as_str(),
                FALLBACK_SERVER_ID_SLUG,
                "input {unparseable:?} should fall back to the default slug"
            );
        }
    }

    /// Regression test for the credential leak the second review round found:
    /// a URL with a mistyped port (a realistic user typo, not an attack) is a
    /// `Url::parse` failure. Before the fix, the fallback sanitized the raw
    /// string instead of discarding it, so `user`/`pass` survived into the id
    /// — which is logged via `info!("Introspecting server: {}", ..)` before
    /// `validate_server_config` ever gets a chance to reject the URL.
    #[test]
    fn test_derive_server_id_from_url_unparseable_credential_bearing_url_leaks_nothing() {
        let id = derive_server_id_from_url("https://user:pass@evil.com:99999/x");
        assert_eq!(id.as_str(), FALLBACK_SERVER_ID_SLUG);
        assert!(!id.as_str().contains("user"));
        assert!(!id.as_str().contains("pass"));
        assert!(!id.as_str().contains("evil"));
    }

    #[test]
    fn test_derive_server_id_from_url_always_passes_validate_server_id() {
        let urls = [
            "https://api.githubcopilot.com/mcp/",
            "https://example.com/sse",
            "https://user:token@host.example.com/mcp?query=1#frag",
            "https://HOST.EXAMPLE.COM/Path/With/Mixed_Case",
            "https://127.0.0.1:8443/mcp",
            "https://example.com/../../escape",
            "https://",
            "not-a-url",
        ];
        for url in urls {
            let id = derive_server_id_from_url(url);
            assert!(
                mcp_execution_skill::validate_server_id(id.as_str()).is_ok(),
                "derived id {:?} from url {url:?} must satisfy validate_server_id",
                id.as_str()
            );
        }
    }

    #[test]
    fn test_build_server_config_http_id_passes_validate_server_id() {
        let (id, _config) = build_server_config(
            http_transport("https://user:token@api.example.com/mcp/../secret", vec![]),
            None,
            None,
        )
        .unwrap();

        assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
        assert!(!id.as_str().contains("token"));
    }

    // ── derive_server_id_from_path_or_name / issue #311 (stdio command and
    // `--name` override are also joined onto a filesystem base directory and
    // must be sanitized the same way `derive_server_id_from_url` already is) ──

    #[test]
    fn test_derive_server_id_from_path_or_name_rejects_parent_traversal() {
        let id = derive_server_id_from_path_or_name("../../../../etc/passwd");
        assert!(!id.as_str().contains(".."));
        assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
    }

    #[test]
    fn test_derive_server_id_from_path_or_name_rejects_absolute_path() {
        let id = derive_server_id_from_path_or_name("/etc/cron.d/evil");
        assert!(!id.as_str().starts_with('/'));
        assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
    }

    #[test]
    fn test_derive_server_id_from_path_or_name_join_never_escapes_base_dir() {
        // Literal reproduction of how `generate.rs` uses the id: joined onto
        // a base directory via `PathBuf::join`, which discards the base
        // entirely if the joined component is absolute. Since the sanitized
        // slug can only ever contain `[a-z0-9-]`, that can never happen.
        let base_dir = PathBuf::from("/home/user/.claude/servers");
        let malicious_inputs = [
            "../../../../etc/passwd",
            "/etc/cron.d/evil",
            "/../../escape",
            "..",
            "./../escape",
        ];

        for input in malicious_inputs {
            let id = derive_server_id_from_path_or_name(input);
            let joined = base_dir.join(id.as_str());
            assert!(
                joined.starts_with(&base_dir),
                "joining derived id {:?} (from {input:?}) onto {base_dir:?} escaped it: {joined:?}",
                id.as_str()
            );
        }
    }

    #[test]
    fn test_derive_server_id_from_path_or_name_preserves_ordinary_commands() {
        // Ordinary stdio commands (already lowercase alnum-hyphen) must be
        // unaffected by sanitization.
        assert_eq!(
            derive_server_id_from_path_or_name("github-mcp-server").as_str(),
            "github-mcp-server"
        );
        assert_eq!(
            derive_server_id_from_path_or_name("docker").as_str(),
            "docker"
        );
    }

    #[test]
    fn test_derive_server_id_from_path_or_name_strips_path_components() {
        // A legitimate absolute/relative binary path still produces a safe,
        // single-segment id rather than being rejected outright.
        let id = derive_server_id_from_path_or_name("/usr/local/bin/mcp-server");
        assert_eq!(id.as_str(), "usr-local-bin-mcp-server");
        assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
    }

    #[test]
    fn test_build_server_config_stdio_traversal_command_never_escapes_base_dir() {
        // Regression test for #311: a stdio `command` used to flow straight
        // into `ServerId::new` unsanitized, then into a directory name under
        // `~/.claude/servers/{id}/`. Covers both a relative command
        // containing `..` (skips `ServerConfigBuilder`'s absolute-path
        // existence check entirely) and a legitimate absolute path (which
        // must exist to pass that check, so `/bin/sh` is used) — both are
        // realistic stdio `command` shapes.
        let base_dir = PathBuf::from("/home/user/.claude/servers");
        for command in ["../../../../etc/passwd", "/bin/sh"] {
            let (id, _config) =
                build_server_config(stdio_transport(command, vec![], vec![], None), None, None)
                    .unwrap();

            assert!(mcp_execution_skill::validate_server_id(id.as_str()).is_ok());
            let joined = base_dir.join(id.as_str());
            assert!(
                joined.starts_with(&base_dir),
                "joining derived id {:?} (from command {command:?}) escaped {base_dir:?}: {joined:?}",
                id.as_str()
            );
        }
    }

    /// Serializes tests in this module that mutate the `HOME` env var so
    /// they cannot race each other when run in the same process (relevant
    /// under plain `cargo test`, which runs a crate's tests in one process;
    /// the mandated `cargo nextest run` isolates every test in its own
    /// process, so this lock is a safety net for the unmandated runner, not
    /// a requirement of the mandated one). A separate static from
    /// `server.rs`'s own `HOME_ENV_LOCK` — the two don't cross-serialize —
    /// which is fine precisely because `cargo nextest run` never runs them
    /// concurrently in a shared process to begin with.
    #[cfg(unix)]
    static HOME_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Regression test for #276: `list_mcp_servers` and `get_mcp_server`
    /// (both downgraded to `pub(crate)`, losing their `# Examples` doctest)
    /// were previously only exercised via their `_from`/error-path siblings.
    /// This exercises the 0-arg wrappers' actual success path — resolving
    /// `~/.claude/mcp.json` via `dirs::home_dir()` and returning a populated,
    /// looked-up entry — which no other test in this crate covered.
    ///
    /// Unix-only, mirroring `server.rs`'s own `HOME`-override tests: on
    /// Windows, `dirs::home_dir()` resolves via the `SHGetKnownFolderPath`
    /// Win32 API, which reads the real OS user profile and ignores
    /// environment variables entirely, so no `HOME` override can redirect it.
    #[cfg(unix)]
    #[test]
    fn test_list_and_get_mcp_server_success_via_default_path() {
        let _guard = HOME_ENV_LOCK.lock().unwrap();

        let temp = tempfile::TempDir::new().unwrap();
        let claude_dir = temp.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::write(
            claude_dir.join("mcp.json"),
            r#"{"mcpServers": {"github": {"command": "node", "args": ["server.js"]}}}"#,
        )
        .unwrap();

        let original_home = std::env::var_os("HOME");
        // SAFETY: guarded by `HOME_ENV_LOCK`; no other test in this process
        // reads or writes `HOME` while the guard is held.
        unsafe {
            std::env::set_var("HOME", temp.path());
        }

        let list_result = list_mcp_servers();
        let get_result = get_mcp_server("github");

        // SAFETY: see above.
        unsafe {
            match &original_home {
                Some(home) => std::env::set_var("HOME", home),
                None => std::env::remove_var("HOME"),
            }
        }

        let servers = list_result.expect("list_mcp_servers must resolve the default path");
        assert_eq!(servers.len(), 1);
        assert_eq!(servers[0].0, "github");

        let (id, _config, entry) =
            get_result.expect("get_mcp_server must find the configured server");
        assert_eq!(id.as_str(), "github");
        assert!(matches!(
            entry.transport,
            McpTransport::Stdio { ref command, .. } if command == "node"
        ));
    }

    /// Regression test for #311 review S4: `get_mcp_server` must accept a
    /// legitimate `mcp.json` key that isn't already `[a-z0-9-]` (mixed case,
    /// underscores) — it is shared by `introspect`/`server`, which have no
    /// need for the id to be a filesystem-safe slug. Only `generate`'s own
    /// sink (`resolve_server_dir_name` in `generate.rs`) enforces that
    /// constraint, since only `generate` turns the id into a directory name.
    #[cfg(unix)]
    #[test]
    fn test_get_mcp_server_accepts_non_slug_shaped_config_key() {
        let _guard = HOME_ENV_LOCK.lock().unwrap();

        let temp = tempfile::TempDir::new().unwrap();
        let claude_dir = temp.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::write(
            claude_dir.join("mcp.json"),
            r#"{"mcpServers": {"claude_ai_Gmail": {"command": "node", "args": ["server.js"]}}}"#,
        )
        .unwrap();

        let original_home = std::env::var_os("HOME");
        // SAFETY: guarded by `HOME_ENV_LOCK`; no other test in this process
        // reads or writes `HOME` while the guard is held.
        unsafe {
            std::env::set_var("HOME", temp.path());
        }

        let get_result = get_mcp_server("claude_ai_Gmail");

        // SAFETY: see above.
        unsafe {
            match &original_home {
                Some(home) => std::env::set_var("HOME", home),
                None => std::env::remove_var("HOME"),
            }
        }

        let (id, _config, _entry) =
            get_result.expect("get_mcp_server must not reject a non-slug-shaped mcp.json key");
        assert_eq!(id.as_str(), "claude_ai_Gmail");
    }

    /// Regression test for #305/#304: an entry present in `mcp.json` but whose `url` fails
    /// `build_core_config`'s scheme validation must still be found by `get_mcp_server_entry` —
    /// distinct from `get_mcp_server`, which eagerly runs that validation and previously made
    /// this case indistinguishable from a genuinely absent entry to its callers.
    #[cfg(unix)]
    #[test]
    fn test_get_mcp_server_entry_finds_entry_that_fails_config_validation() {
        let _guard = HOME_ENV_LOCK.lock().unwrap();

        let temp = tempfile::TempDir::new().unwrap();
        let claude_dir = temp.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::write(
            claude_dir.join("mcp.json"),
            r#"{"mcpServers": {"badscheme": {"type": "http", "url": "not-a-url"}}}"#,
        )
        .unwrap();

        let original_home = std::env::var_os("HOME");
        // SAFETY: guarded by `HOME_ENV_LOCK`; no other test in this process
        // reads or writes `HOME` while the guard is held.
        unsafe {
            std::env::set_var("HOME", temp.path());
        }

        let entry_result = get_mcp_server_entry("badscheme");

        // SAFETY: see above.
        unsafe {
            match &original_home {
                Some(home) => std::env::set_var("HOME", home),
                None => std::env::remove_var("HOME"),
            }
        }

        let (id, entry) = entry_result.expect(
            "get_mcp_server_entry must find the entry even though its url fails validation",
        );
        assert_eq!(id.as_str(), "badscheme");
        let config_err = build_core_config(&entry).expect_err(
            "the entry's url is expected to fail build_core_config's scheme validation",
        );
        // Regression coverage for #304: `validate_command` interpolates this error's `Display`
        // into its "invalid configuration" message. It must describe the actual validation
        // failure, not read like the unrelated "not found" message reserved for a genuinely
        // absent entry.
        let message = config_err.to_string();
        assert!(
            !message.to_lowercase().contains("not found"),
            "build_core_config's error must not read like a not-found message, got: {message}"
        );
    }
}