mcp-execution-core 0.9.0

Core types, traits, and error handling for MCP execution
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
//! MCP server configuration with command, arguments, and environment.
//!
//! This module provides type-safe server configuration for launching MCP servers
//! with security validation of commands, arguments, and environment variables.
//!
//! # Transport Types
//!
//! Supports two transport types:
//! - Stdio: Subprocess communication via stdin/stdout (default)
//! - HTTP: Communication via HTTP/HTTPS API
//!
//! # Security
//!
//! The configuration enforces:
//! - Command validation (absolute path or binary name)
//! - Argument sanitization (no shell metacharacters)
//! - Environment variable validation (block dangerous names)
//! - Forbidden characters: `;`, `|`, `&`, `>`, `<`, `` ` ``, `$`, `(`, `)`, `\n`, `\r`
//! - Forbidden env vars: dynamic-linker (`LD_PRELOAD`, `LD_LIBRARY_PATH`,
//!   `LD_AUDIT`, `DYLD_*`), `PATH`, and interpreter hijack vectors
//!   (`NODE_OPTIONS`, `PYTHONPATH`, `PYTHONSTARTUP`, `RUBYOPT`, `PERL5OPT`,
//!   `JAVA_TOOL_OPTIONS`) — see `command::FORBIDDEN_ENV_NAMES` for the full
//!   list and its documented threat model
//!
//! # Examples
//!
//! ```
//! use mcp_execution_core::ServerConfig;
//! use std::collections::HashMap;
//!
//! // Simple configuration with just command
//! let config = ServerConfig::builder()
//!     .command("docker".to_string())
//!     .build().unwrap();
//!
//! // Full configuration with args and env
//! let config = ServerConfig::builder()
//!     .command("mcp-server".to_string())
//!     .arg("--port".to_string())
//!     .arg("8080".to_string())
//!     .env("LOG_LEVEL".to_string(), "debug".to_string())
//!     .build().unwrap();
//!
//! // HTTP transport configuration
//! let config = ServerConfig::builder()
//!     .http_transport("https://api.example.com/mcp".to_string())
//!     .header("Authorization".to_string(), "Bearer token".to_string())
//!     .build().unwrap();
//! ```

use crate::path::sanitize_path_for_error;
use crate::redact::{RedactedItems, RedactedMapValues, RedactedUrl};
use serde::de::Error as _;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::time::Duration;

/// Default timeout for establishing an MCP server connection (handshake).
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

/// Default timeout for the `list_all_tools` discovery call after connecting.
const DEFAULT_DISCOVER_TIMEOUT: Duration = Duration::from_secs(30);

const fn default_connect_timeout() -> Duration {
    DEFAULT_CONNECT_TIMEOUT
}

const fn default_discover_timeout() -> Duration {
    DEFAULT_DISCOVER_TIMEOUT
}

/// Shared empty map returned by [`ServerConfig::env`]/[`ServerConfig::headers`] for the
/// transport that doesn't carry that field (e.g. `headers()` for a `Stdio` config), so those
/// accessors can keep returning a plain `&HashMap` instead of an `Option`.
static EMPTY_MAP: LazyLock<HashMap<String, String>> = LazyLock::new(HashMap::new);

/// Transport-specific configuration for connecting to an MCP server.
///
/// Each variant carries exactly the fields meaningful for that transport, so a config with
/// stdio's `command`/`args`/`env`/`cwd` set alongside http/sse's `url`/`headers` — or a
/// `Stdio` variant missing `command`, or an `Http`/`Sse` variant missing `url` — cannot be
/// constructed at all; the combination is unrepresentable rather than merely unvalidated
/// (issue #313). [`ServerConfig::builder`] is the normal way to construct one; a bare
/// `Transport` value is mostly useful for matching on [`ServerConfig::transport`].
///
/// # Examples
///
/// ```
/// use mcp_execution_core::{ServerConfig, Transport};
///
/// let config = ServerConfig::builder()
///     .command("docker".to_string())
///     .build()
///     .unwrap();
///
/// assert!(matches!(config.transport(), Transport::Stdio { .. }));
/// ```
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "transport", rename_all = "lowercase")]
pub enum Transport {
    /// Stdio transport: subprocess communication via stdin/stdout.
    Stdio {
        /// Command to execute (binary name or absolute path).
        ///
        /// Can be either:
        /// - Binary name (e.g., "docker", "python") - resolved via PATH
        /// - Absolute path (e.g., "/usr/local/bin/mcp-server")
        command: String,

        /// Arguments to pass to command.
        ///
        /// Each argument is passed separately to avoid shell interpretation.
        /// Do not include the command itself in arguments.
        #[serde(default)]
        args: Vec<String>,

        /// Environment variables to set for the subprocess.
        ///
        /// These are added to (or override) the parent process environment.
        /// Security validation blocks dangerous variables like `LD_PRELOAD`.
        /// Values routinely hold secrets (e.g. `GITHUB_PERSONAL_ACCESS_TOKEN`); see
        /// the redaction note on [`ServerConfig`]'s own doc comment.
        #[serde(default)]
        env: HashMap<String, String>,

        /// Working directory for the subprocess (optional).
        ///
        /// If `None`, inherits the parent process working directory.
        #[serde(default)]
        cwd: Option<PathBuf>,
    },
    /// HTTP transport: communication via HTTP/HTTPS API.
    Http {
        /// URL for HTTP transport.
        ///
        /// Example: `https://api.example.com/mcp`
        ///
        /// This crate does not apply SSRF allowlisting to this URL — it is
        /// treated like a `curl` target, appropriate for a local CLI tool.
        /// Embedders that expose this config in a multi-tenant or server context
        /// should apply their own URL allowlisting before connecting.
        url: String,

        /// HTTP headers for HTTP transport.
        ///
        /// Common headers include:
        /// - `Authorization`: Authentication token
        /// - `Content-Type`: Request content type
        ///
        /// Values routinely hold secrets (e.g. a bearer token); see the redaction
        /// note on [`ServerConfig`]'s own doc comment.
        #[serde(default)]
        headers: HashMap<String, String>,
    },
    /// SSE transport: Server-Sent Events for streaming communication.
    Sse {
        /// URL for SSE transport.
        ///
        /// Same shape and SSRF caveat as [`Transport::Http`]'s `url`.
        url: String,

        /// HTTP headers for SSE transport.
        ///
        /// Same shape and redaction guarantee as [`Transport::Http`]'s `headers`.
        #[serde(default)]
        headers: HashMap<String, String>,
    },
}

impl fmt::Debug for Transport {
    /// Redacts the same fields, the same way, as [`ServerConfig`]'s own hand-written impl —
    /// see the "Security" section on that type's doc comment for the full rationale. Kept as a
    /// standalone impl (rather than `ServerConfig` delegating to it) so each type's `Debug`
    /// output stays exactly what it was already documented and tested to be.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::Transport;
    /// use std::collections::HashMap;
    ///
    /// let transport = Transport::Http {
    ///     url: "https://user:sk-secret@api.example.com/mcp?token=sk-secret".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("api.example.com/mcp"));
    /// assert!(!debug_output.contains("sk-secret"));
    /// ```
    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(),
        }
    }
}

/// MCP server configuration with command, arguments, and environment.
///
/// Represents the configuration needed to communicate with an MCP server,
/// supporting both stdio (subprocess) and HTTP transports.
///
/// # Transport Types
///
/// - **Stdio**: Launches a subprocess and communicates via stdin/stdout
/// - **HTTP**: Connects to an HTTP/HTTPS API endpoint
///
/// # Security
///
/// Both fields are private and the type's [`Deserialize`] impl is hand-written (see below), so
/// a `ServerConfig` cannot be obtained — via [`ServerConfigBuilder::build`], a struct literal,
/// or `serde_json::from_str` — without having passed [`validate_server_config`]. This closes
/// the gap that existed when every field was `pub` and `Deserialize` was derived: a
/// hand-edited `mcp.json` or a directly-constructed struct literal could previously skip
/// validation entirely.
///
/// `headers`, `env`, `args`, and `url` routinely carry secrets (e.g. an
/// `Authorization: Bearer <token>` header, a `GITHUB_PERSONAL_ACCESS_TOKEN`
/// environment variable, an `--api-key sk-...`-style argument, or a
/// `?token=`-style query string), so this type's [`Debug`] implementation is
/// hand-written to redact them (this guarantee is `Debug`-only — see
/// "Serialization Hazard" below for `Serialize`, which does not redact
/// anything):
///
/// - `headers`/`env`: keys stay visible, values are replaced — a legitimately
///   configured key (a chosen header or env var name, e.g. `"Authorization"`)
///   is not itself a secret and remains useful for debugging. This mirrors
///   the discipline already applied to header values in `command.rs`'s
///   `validate_header_value_string`, which never echoes a header value into
///   an error message.
/// - `args`: every entry is replaced wholesale (via [`crate::RedactedItems`])
///   since an argument has no key/value split to preserve half of.
/// - `url`: userinfo credentials and any query string are stripped (via
///   [`crate::RedactedUrl`]); scheme, host, and path stay readable.
/// - `command`/`cwd`: passed through [`crate::sanitize_path_for_error`] —
///   not a secret, but an absolute path leaks the OS username, and the
///   program name itself (`docker`, `npx`) is worth keeping readable for
///   telling server entries apart in a log.
///
/// This is a narrower guarantee than `command.rs`'s header-*name* validation
/// errors, which redact the name too: those fire on input that has not yet
/// been confirmed well-formed (e.g. a `Name=Value` CLI argument mis-split on
/// the wrong separator can leave a secret value sitting in the name
/// position), so any name reaching that error path must be treated as
/// secret-shaped. Once [`validate_server_config`] has accepted a config,
/// its `headers`/`env` keys are the caller's own identifiers rather than
/// unvalidated split output, so trusting them for `Debug` output is not in
/// tension with distrusting an unvalidated name in an error message.
///
/// [`ServerConfigBuilder`] carries the same [`Debug`] treatment for
/// consistency, but that guarantee does not extend to it: the builder is
/// populated *before* [`validate_server_config`] runs, so a caller that
/// feeds it unvalidated input (e.g. a mis-split CLI argument) can still end
/// up with a secret-shaped key in `format!("{builder:?}")`. Keys are shown
/// there deliberately regardless — redacting them would defeat the point of
/// a debug impl for a type whose purpose is to be inspected before
/// `build()`.
///
/// ## Serialization Hazard
///
/// `Serialize` is a separate code path from [`Debug`] and is deliberately
/// left unredacted: whatever consumes the serialized form must still be able
/// to round-trip real values, so `serde_json::to_string(&config)` (or any
/// other `Serialize`-driven output) emits every field, including secrets, in
/// full. **The `Debug`-redaction guarantee documented above does not extend
/// to `Serialize` in any way** — do not assume "this type redacts secrets"
/// covers both.
///
/// Consequently, a serialized `ServerConfig` must never be logged or printed
/// directly. It exists for whatever trusted persistence an embedder builds
/// on top of this crate (a caller-owned config store, for instance) — not
/// for a specific path this crate implements itself; as of this writing no
/// non-test code in this workspace serializes a `ServerConfig` and then
/// logs or prints the result.
///
/// ```
/// use mcp_execution_core::ServerConfig;
///
/// let config = ServerConfig::builder()
///     .command("docker".to_string())
///     .env(
///         "GITHUB_PERSONAL_ACCESS_TOKEN".to_string(),
///         "ghp_supersecretvalue".to_string(),
///     )
///     .build()
///     .unwrap();
///
/// // Unlike `Debug`, `Serialize` does not redact anything.
/// let json = serde_json::to_string(&config).unwrap();
/// assert!(json.contains("ghp_supersecretvalue"));
/// ```
///
/// # Examples
///
/// ```
/// use mcp_execution_core::ServerConfig;
///
/// // Stdio transport
/// let config = ServerConfig::builder()
///     .command("docker".to_string())
///     .arg("run".to_string())
///     .arg("mcp-server".to_string())
///     .build().unwrap();
///
/// assert_eq!(config.command(), Some("docker"));
/// assert_eq!(config.args().len(), 2);
///
/// // HTTP transport
/// let config = ServerConfig::builder()
///     .http_transport("https://api.example.com/mcp".to_string())
///     .header("Authorization".to_string(), "Bearer token".to_string())
///     .build().unwrap();
/// ```
///
/// Debug output redacts header/env values but keeps keys:
///
/// ```
/// use mcp_execution_core::ServerConfig;
///
/// let config = ServerConfig::builder()
///     .http_transport("https://api.example.com/mcp".to_string())
///     .header("Authorization".to_string(), "Bearer sk-secret-value".to_string())
///     .build();
///
/// let debug_output = format!("{config:?}");
/// assert!(debug_output.contains("Authorization"));
/// assert!(!debug_output.contains("sk-secret-value"));
/// ```
///
/// Debug output redacts `args` wholesale and strips URL userinfo/query,
/// while keeping `command` and the URL host/path readable:
///
/// ```
/// use mcp_execution_core::ServerConfig;
///
/// let config = ServerConfig::builder()
///     .command("docker".to_string())
///     .arg("--api-key".to_string())
///     .arg("sk-secret-arg".to_string())
///     .build();
///
/// let debug_output = format!("{config:?}");
/// assert!(debug_output.contains("docker"));
/// assert!(!debug_output.contains("sk-secret-arg"));
///
/// let config = ServerConfig::builder()
///     .http_transport("https://user:sk-secret@api.example.com/mcp?token=sk-secret".to_string())
///     .build();
///
/// let debug_output = format!("{config:?}");
/// assert!(debug_output.contains("api.example.com/mcp"));
/// assert!(!debug_output.contains("sk-secret"));
/// ```
///
/// [`validate_server_config`]: fn.validate_server_config.html
#[derive(Clone, Serialize, PartialEq, Eq)]
pub struct ServerConfig {
    /// Transport-specific fields (command/args/env/cwd, or url/headers).
    #[serde(flatten)]
    transport: Transport,

    /// Timeout for establishing a connection to the server (handshake).
    ///
    /// Bounds how long `Introspector::discover_server` waits for the initial
    /// rmcp `serve` handshake before giving up. Defaults to 30 seconds.
    #[serde(default = "default_connect_timeout")]
    connect_timeout: Duration,

    /// Timeout for the tool discovery call after a connection is established.
    ///
    /// Bounds how long `Introspector::discover_server` waits for
    /// `list_all_tools` to respond. Defaults to 30 seconds.
    #[serde(default = "default_discover_timeout")]
    discover_timeout: Duration,
}

impl<'de> Deserialize<'de> for ServerConfig {
    /// Deserializes into a private shadow shape and then runs
    /// `validate_server_config` before returning, so a hand-edited `mcp.json` (or any other
    /// JSON source) can never produce an unvalidated `ServerConfig` — see the "Security"
    /// section on [`ServerConfig`]'s own doc comment.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Raw {
            #[serde(flatten)]
            transport: Transport,
            #[serde(default = "default_connect_timeout")]
            connect_timeout: Duration,
            #[serde(default = "default_discover_timeout")]
            discover_timeout: Duration,
        }

        let raw = Raw::deserialize(deserializer)?;
        let config = Self {
            transport: raw.transport,
            connect_timeout: raw.connect_timeout,
            discover_timeout: raw.discover_timeout,
        };
        crate::validate_server_config(&config).map_err(D::Error::custom)?;
        Ok(config)
    }
}

impl fmt::Debug for ServerConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("ServerConfig");
        match &self.transport {
            Transport::Stdio {
                command,
                args,
                env,
                cwd,
            } => {
                s.field("transport", &"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));
            }
            Transport::Http { url, headers } => {
                s.field("transport", &"http")
                    .field("url", &RedactedUrl(url))
                    .field("headers", &RedactedMapValues(headers));
            }
            Transport::Sse { url, headers } => {
                s.field("transport", &"sse")
                    .field("url", &RedactedUrl(url))
                    .field("headers", &RedactedMapValues(headers));
            }
        }
        s.field("connect_timeout", &self.connect_timeout)
            .field("discover_timeout", &self.discover_timeout)
            .finish()
    }
}

impl ServerConfig {
    /// Creates a new builder for `ServerConfig`.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn builder() -> ServerConfigBuilder {
        ServerConfigBuilder::default()
    }

    /// Returns the transport-specific configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::{ServerConfig, Transport};
    ///
    /// let config = ServerConfig::builder()
    ///     .command("test".to_string())
    ///     .build().unwrap();
    ///
    /// assert!(matches!(config.transport(), Transport::Stdio { .. }));
    /// ```
    #[must_use]
    pub const fn transport(&self) -> &Transport {
        &self.transport
    }

    /// Returns the command as a string slice, or `None` for a config that isn't
    /// [`Transport::Stdio`].
    ///
    /// Mirrors [`Self::url`], which is `None` for [`Transport::Stdio`] and `Some` for the
    /// other two variants — `command` only ever exists for `Stdio`, so absence is
    /// represented the same way rather than as an empty string a caller would have to
    /// remember to check for.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("test-server".to_string())
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.command(), Some("test-server"));
    ///
    /// let config = ServerConfig::builder()
    ///     .http_transport("https://api.example.com/mcp".to_string())
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.command(), None);
    /// ```
    #[must_use]
    pub fn command(&self) -> Option<&str> {
        match &self.transport {
            Transport::Stdio { command, .. } => Some(command),
            Transport::Http { .. } | Transport::Sse { .. } => None,
        }
    }

    /// Returns a slice of arguments, or an empty slice for a config that isn't
    /// [`Transport::Stdio`].
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("server".to_string())
    ///     .args(vec!["--port".to_string(), "8080".to_string()])
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.args(), &["--port", "8080"]);
    /// ```
    #[must_use]
    pub fn args(&self) -> &[String] {
        match &self.transport {
            Transport::Stdio { args, .. } => args,
            Transport::Http { .. } | Transport::Sse { .. } => &[],
        }
    }

    /// Returns a reference to the environment variables map, or an empty map for a config
    /// that isn't [`Transport::Stdio`].
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("server".to_string())
    ///     .env("VAR_NAME".to_string(), "var_value".to_string())
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.env().get("VAR_NAME"), Some(&"var_value".to_string()));
    /// ```
    #[must_use]
    pub fn env(&self) -> &HashMap<String, String> {
        match &self.transport {
            Transport::Stdio { env, .. } => env,
            Transport::Http { .. } | Transport::Sse { .. } => &EMPTY_MAP,
        }
    }

    /// Returns the working directory, if set. Always `None` for a config that isn't
    /// [`Transport::Stdio`].
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("server".to_string())
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.cwd(), None);
    /// ```
    #[must_use]
    pub const fn cwd(&self) -> Option<&PathBuf> {
        match &self.transport {
            Transport::Stdio { cwd, .. } => cwd.as_ref(),
            Transport::Http { .. } | Transport::Sse { .. } => None,
        }
    }

    /// Returns the URL for HTTP/SSE transport, if set. Always `None` for
    /// [`Transport::Stdio`].
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("server".to_string())
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.url(), None);
    /// ```
    #[must_use]
    pub fn url(&self) -> Option<&str> {
        match &self.transport {
            Transport::Stdio { .. } => None,
            Transport::Http { url, .. } | Transport::Sse { url, .. } => Some(url),
        }
    }

    /// Returns a reference to the HTTP headers map, or an empty map for
    /// [`Transport::Stdio`].
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::collections::HashMap;
    ///
    /// let mut headers_map = HashMap::new();
    /// headers_map.insert("Authorization".to_string(), "Bearer token".to_string());
    ///
    /// let config = ServerConfig::builder()
    ///     .http_transport("https://api.example.com/mcp".to_string())
    ///     .headers(headers_map)
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.headers().get("Authorization"), Some(&"Bearer token".to_string()));
    /// ```
    #[must_use]
    pub fn headers(&self) -> &HashMap<String, String> {
        match &self.transport {
            Transport::Stdio { .. } => &EMPTY_MAP,
            Transport::Http { headers, .. } | Transport::Sse { headers, .. } => headers,
        }
    }

    /// Returns the connection (handshake) timeout.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::time::Duration;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.connect_timeout(), Duration::from_secs(30));
    /// ```
    #[must_use]
    pub const fn connect_timeout(&self) -> Duration {
        self.connect_timeout
    }

    /// Returns the tool discovery timeout.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::time::Duration;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.discover_timeout(), Duration::from_secs(30));
    /// ```
    #[must_use]
    pub const fn discover_timeout(&self) -> Duration {
        self.discover_timeout
    }
}

/// Which transport [`ServerConfigBuilder::build`] should assemble.
///
/// Internal to the builder only: unlike the public [`Transport`] enum (the assembled config's
/// actual representation), this carries no data — the builder still accumulates
/// `command`/`args`/`env`/`cwd`/`url`/`headers` as flat, independently-settable fields before
/// `build()` decides, based on this discriminant, which of them become the final
/// [`Transport`] variant's payload.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum TransportKind {
    /// Stdio transport: subprocess communication via stdin/stdout.
    #[default]
    Stdio,
    /// HTTP transport: communication via HTTP/HTTPS API.
    Http,
    /// SSE transport: Server-Sent Events for streaming communication.
    Sse,
}

/// Builder for constructing `ServerConfig` instances.
///
/// Provides a fluent API for building server configurations with
/// optional arguments, environment variables, and HTTP settings.
///
/// # Examples
///
/// ```
/// use mcp_execution_core::ServerConfig;
///
/// // Stdio transport
/// let config = ServerConfig::builder()
///     .command("mcp-server".to_string())
///     .arg("--verbose".to_string())
///     .env("DEBUG".to_string(), "1".to_string())
///     .build().unwrap();
///
/// // HTTP transport
/// let config = ServerConfig::builder()
///     .http_transport("https://api.example.com/mcp".to_string())
///     .header("Authorization".to_string(), "Bearer token".to_string())
///     .build().unwrap();
/// ```
///
/// Like [`ServerConfig`] itself, this builder accumulates `env`/`headers`
/// before secrets they may carry are known to be well-formed, so its
/// [`Debug`] impl redacts values the same way — see the redaction note on
/// [`ServerConfig`]'s doc comment.
#[derive(Clone)]
pub struct ServerConfigBuilder {
    transport: TransportKind,
    command: Option<String>,
    args: Vec<String>,
    env: HashMap<String, String>,
    cwd: Option<PathBuf>,
    url: Option<String>,
    headers: HashMap<String, String>,
    connect_timeout: Duration,
    discover_timeout: Duration,
}

impl fmt::Debug for ServerConfigBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ServerConfigBuilder")
            .field("transport", &self.transport)
            .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(sanitize_path_for_error))
            .field("url", &self.url.as_deref().map(RedactedUrl))
            .field("headers", &RedactedMapValues(&self.headers))
            .field("connect_timeout", &self.connect_timeout)
            .field("discover_timeout", &self.discover_timeout)
            .finish()
    }
}

impl Default for ServerConfigBuilder {
    fn default() -> Self {
        Self {
            transport: TransportKind::default(),
            command: None,
            args: Vec::new(),
            env: HashMap::new(),
            cwd: None,
            url: None,
            headers: HashMap::new(),
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            discover_timeout: DEFAULT_DISCOVER_TIMEOUT,
        }
    }
}

impl ServerConfigBuilder {
    /// Sets the command to execute.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn command(mut self, command: String) -> Self {
        self.command = Some(command);
        self
    }

    /// Adds a single argument.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .arg("run".to_string())
    ///     .arg("--rm".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn arg(mut self, arg: String) -> Self {
        self.args.push(arg);
        self
    }

    /// Sets all arguments at once, replacing any previously added.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .args(vec!["run".to_string(), "--rm".to_string()])
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn args(mut self, args: Vec<String>) -> Self {
        self.args = args;
        self
    }

    /// Adds a single environment variable.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("mcp-server".to_string())
    ///     .env("LOG_LEVEL".to_string(), "debug".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn env(mut self, key: String, value: String) -> Self {
        self.env.insert(key, value);
        self
    }

    /// Sets all environment variables at once, replacing any previously added.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::collections::HashMap;
    ///
    /// let mut env_map = HashMap::new();
    /// env_map.insert("DEBUG".to_string(), "1".to_string());
    ///
    /// let config = ServerConfig::builder()
    ///     .command("mcp-server".to_string())
    ///     .environment(env_map)
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn environment(mut self, env: HashMap<String, String>) -> Self {
        self.env = env;
        self
    }

    /// Sets the working directory for the subprocess.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::path::PathBuf;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("mcp-server".to_string())
    ///     .cwd(PathBuf::from("/tmp"))
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn cwd(mut self, cwd: PathBuf) -> Self {
        self.cwd = Some(cwd);
        self
    }

    /// Configures HTTP transport with the given URL.
    ///
    /// This sets the transport type to HTTP and configures the endpoint URL.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .http_transport("https://api.example.com/mcp".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn http_transport(mut self, url: String) -> Self {
        self.transport = TransportKind::Http;
        self.url = Some(url);
        self
    }

    /// Configures SSE transport with the given URL.
    ///
    /// This sets the transport type to SSE (Server-Sent Events) and configures the endpoint URL.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .sse_transport("https://api.example.com/sse".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn sse_transport(mut self, url: String) -> Self {
        self.transport = TransportKind::Sse;
        self.url = Some(url);
        self
    }

    /// Sets the URL for HTTP transport.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .http_transport("https://api.example.com/mcp".to_string())
    ///     .url("https://api.example.com/mcp/v2".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn url(mut self, url: String) -> Self {
        self.url = Some(url);
        self
    }

    /// Adds a single HTTP header.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .http_transport("https://api.example.com/mcp".to_string())
    ///     .header("Authorization".to_string(), "Bearer token".to_string())
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn header(mut self, key: String, value: String) -> Self {
        self.headers.insert(key, value);
        self
    }

    /// Sets all HTTP headers at once, replacing any previously added.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::collections::HashMap;
    ///
    /// let mut headers = HashMap::new();
    /// headers.insert("Authorization".to_string(), "Bearer token".to_string());
    ///
    /// let config = ServerConfig::builder()
    ///     .http_transport("https://api.example.com/mcp".to_string())
    ///     .headers(headers)
    ///     .build().unwrap();
    /// ```
    #[must_use]
    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
        self.headers = headers;
        self
    }

    /// Sets the connection (handshake) timeout, overriding the 30-second default.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::time::Duration;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .connect_timeout(Duration::from_secs(5))
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.connect_timeout(), Duration::from_secs(5));
    /// ```
    #[must_use]
    pub const fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Sets the tool discovery timeout, overriding the 30-second default.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    /// use std::time::Duration;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .discover_timeout(Duration::from_secs(5))
    ///     .build().unwrap();
    ///
    /// assert_eq!(config.discover_timeout(), Duration::from_secs(5));
    /// ```
    #[must_use]
    pub const fn discover_timeout(mut self, timeout: Duration) -> Self {
        self.discover_timeout = timeout;
        self
    }

    /// Builds and validates the `ServerConfig`.
    ///
    /// This is the only way to obtain a [`ServerConfig`] through the builder: beyond the
    /// structural checks (command/url presence), it also runs the full security validation
    /// performed by [`validate_server_config`] — shell metacharacters, forbidden environment
    /// variables, URL scheme, and header safety — before returning. A `ServerConfig` built
    /// through this method therefore cannot exist without having passed security
    /// validation. Unlike before #313, this is now also a type-level guarantee: every other
    /// way to obtain a `ServerConfig` (a struct literal, `serde_json::from_str`) is closed —
    /// see [`ServerConfig`]'s own "Security" section.
    ///
    /// # Errors
    ///
    /// Returns `Error::ValidationError` if:
    /// - Command is not set (or is empty) for stdio transport
    /// - URL is not set for HTTP/SSE transport
    ///
    /// Returns `Error::SecurityViolation` or `Error::ValidationError` for any
    /// reason documented on [`validate_server_config`] (forbidden shell
    /// metacharacters, forbidden environment variables, invalid URL scheme,
    /// unsafe headers, out-of-bounds timeouts, etc.).
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::ServerConfig;
    ///
    /// let config = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .build()
    ///     .unwrap();
    ///
    /// // Rejected at construction time — no separate validation step needed.
    /// let err = ServerConfig::builder()
    ///     .command("docker".to_string())
    ///     .arg("run; rm -rf /".to_string())
    ///     .build()
    ///     .unwrap_err();
    /// assert!(err.is_security_error());
    /// ```
    ///
    /// [`validate_server_config`]: fn.validate_server_config.html
    pub fn build(self) -> crate::Result<ServerConfig> {
        let config = self.build_structural()?;
        crate::validate_server_config(&config)?;
        Ok(config)
    }

    /// Checks structural completeness (command/url presence) and assembles
    /// the `ServerConfig`, without running security validation.
    ///
    /// Kept private and separate from [`Self::build`] so the two concerns —
    /// "is this config structurally complete" and "is this config safe to
    /// spawn" — stay independently testable, while the public API only ever
    /// hands out a fully validated [`ServerConfig`].
    fn build_structural(self) -> crate::Result<ServerConfig> {
        let transport = match self.transport {
            TransportKind::Stdio => {
                let command = self.command.ok_or_else(|| crate::Error::ValidationError {
                    field: "command".to_string(),
                    reason: "command is required for stdio transport".to_string(),
                })?;

                if command.trim().is_empty() {
                    return Err(crate::Error::ValidationError {
                        field: "command".to_string(),
                        reason: "command cannot be empty for stdio transport".to_string(),
                    });
                }

                Transport::Stdio {
                    command,
                    args: self.args,
                    env: self.env,
                    cwd: self.cwd,
                }
            }
            TransportKind::Http => {
                let url = self.url.ok_or_else(|| crate::Error::ValidationError {
                    field: "url".to_string(),
                    reason: "url is required for HTTP transport".to_string(),
                })?;

                Transport::Http {
                    url,
                    headers: self.headers,
                }
            }
            TransportKind::Sse => {
                let url = self.url.ok_or_else(|| crate::Error::ValidationError {
                    field: "url".to_string(),
                    reason: "url is required for SSE transport".to_string(),
                })?;

                Transport::Sse {
                    url,
                    headers: self.headers,
                }
            }
        };

        Ok(ServerConfig {
            transport,
            connect_timeout: self.connect_timeout,
            discover_timeout: self.discover_timeout,
        })
    }
}

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

    #[test]
    fn test_server_config_builder_minimal() {
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .build()
            .unwrap();

        assert_eq!(config.command(), Some("docker"));
        assert!(config.args().is_empty());
        assert!(config.env().is_empty());
        assert!(config.cwd().is_none());
    }

    #[test]
    fn test_server_config_builder_with_args() {
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .arg("run".to_string())
            .arg("--rm".to_string())
            .arg("mcp-server".to_string())
            .build()
            .unwrap();

        assert_eq!(config.command(), Some("docker"));
        assert_eq!(config.args(), vec!["run", "--rm", "mcp-server"]);
    }

    #[test]
    fn test_server_config_builder_with_args_vec() {
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .args(vec!["run".to_string(), "--rm".to_string()])
            .build()
            .unwrap();

        assert_eq!(config.args(), vec!["run", "--rm"]);
    }

    #[test]
    fn test_server_config_builder_with_env() {
        let config = ServerConfig::builder()
            .command("mcp-server".to_string())
            .env("LOG_LEVEL".to_string(), "debug".to_string())
            .env("DEBUG".to_string(), "1".to_string())
            .build()
            .unwrap();

        assert_eq!(config.env().len(), 2);
        assert_eq!(config.env().get("LOG_LEVEL"), Some(&"debug".to_string()));
        assert_eq!(config.env().get("DEBUG"), Some(&"1".to_string()));
    }

    #[test]
    fn test_server_config_builder_with_environment_map() {
        let mut env_map = HashMap::new();
        env_map.insert("VAR1".to_string(), "value1".to_string());
        env_map.insert("VAR2".to_string(), "value2".to_string());

        let config = ServerConfig::builder()
            .command("mcp-server".to_string())
            .environment(env_map)
            .build()
            .unwrap();

        assert_eq!(config.env().len(), 2);
    }

    #[test]
    fn test_server_config_builder_with_cwd() {
        let config = ServerConfig::builder()
            .command("mcp-server".to_string())
            .cwd(PathBuf::from("/tmp"))
            .build()
            .unwrap();

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

    #[test]
    fn test_server_config_builder_full() {
        let mut env_map = HashMap::new();
        env_map.insert("LOG_LEVEL".to_string(), "debug".to_string());

        let config = ServerConfig::builder()
            .command("mcp-server".to_string())
            .args(vec!["--port".to_string(), "8080".to_string()])
            .environment(env_map)
            .cwd(PathBuf::from("/var/run"))
            .build()
            .unwrap();

        assert_eq!(config.command(), Some("mcp-server"));
        assert_eq!(config.args().len(), 2);
        assert_eq!(config.env().len(), 1);
        assert_eq!(config.cwd(), Some(&PathBuf::from("/var/run")));
    }

    #[test]
    #[should_panic(expected = "command")]
    fn test_server_config_builder_missing_command() {
        let _ = ServerConfig::builder().build().unwrap();
    }

    #[test]
    fn test_server_config_builder_build_missing_command() {
        let result = ServerConfig::builder().build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("command"));
    }

    /// #177 — security validation must be folded into construction: a
    /// `ServerConfig` carrying a shell metacharacter can no longer be built
    /// at all, rather than only being caught by a separate manual call to
    /// `validate_server_config` downstream.
    #[test]
    fn test_build_rejects_shell_metacharacters_at_construction() {
        let result = ServerConfig::builder()
            .command("docker".to_string())
            .arg("run; rm -rf /".to_string())
            .build();

        assert!(result.is_err());
        assert!(result.unwrap_err().is_security_error());
    }

    /// #177 — same guarantee for forbidden environment variables.
    #[test]
    fn test_build_rejects_forbidden_env_var_at_construction() {
        let result = ServerConfig::builder()
            .command("docker".to_string())
            .env("LD_PRELOAD".to_string(), "/evil.so".to_string())
            .build();

        assert!(result.is_err());
        assert!(result.unwrap_err().is_security_error());
    }

    #[test]
    fn test_server_config_accessors() {
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .arg("run".to_string())
            .env("VAR".to_string(), "value".to_string())
            .cwd(PathBuf::from("/tmp"))
            .build()
            .unwrap();

        assert_eq!(config.command(), Some("docker"));
        assert_eq!(config.args(), &["run".to_string()]);
        assert_eq!(config.env().len(), 1);
        assert_eq!(config.cwd(), Some(&PathBuf::from("/tmp")));
    }

    #[test]
    fn test_server_config_serialize_deserialize() {
        let config = ServerConfig::builder()
            .command("mcp-server".to_string())
            .arg("--verbose".to_string())
            .env("DEBUG".to_string(), "1".to_string())
            .build()
            .unwrap();

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: ServerConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(config, deserialized);
    }

    #[test]
    fn test_server_config_clone() {
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .build()
            .unwrap();

        let cloned = config.clone();
        assert_eq!(config, cloned);
    }

    #[test]
    fn test_server_config_debug() {
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .build()
            .unwrap();

        let debug_str = format!("{config:?}");
        assert!(debug_str.contains("docker"));
    }

    #[test]
    fn test_server_config_debug_redacts_header_values() {
        // headers are only populated for HTTP/SSE transport (see the
        // builder's `build`), so exercise them via `http_transport`.
        let config = ServerConfig::builder()
            .http_transport("https://api.example.com/mcp".to_string())
            .header(
                "Authorization".to_string(),
                "Bearer sk-secret-header-value".to_string(),
            )
            .build()
            .unwrap();

        let debug_str = format!("{config:?}");

        // The key is useful for debugging and is not secret.
        assert!(debug_str.contains("Authorization"));
        // The value must never appear.
        assert!(!debug_str.contains("sk-secret-header-value"));
    }

    #[test]
    fn test_server_config_debug_redacts_env_values() {
        // env is only populated for stdio transport (see the builder's
        // `build`), so exercise it via the default stdio transport.
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .env(
                "GITHUB_PERSONAL_ACCESS_TOKEN".to_string(),
                "ghp_supersecretvalue".to_string(),
            )
            .build()
            .unwrap();

        let debug_str = format!("{config:?}");

        // The key is useful for debugging and is not secret.
        assert!(debug_str.contains("GITHUB_PERSONAL_ACCESS_TOKEN"));
        // The value must never appear.
        assert!(!debug_str.contains("ghp_supersecretvalue"));
    }

    #[test]
    fn test_server_config_debug_redacts_args() {
        let secret = "sk-live-secret-arg-value";
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .arg("--api-key".to_string())
            .arg(secret.to_string())
            .build()
            .unwrap();

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

    #[test]
    fn test_server_config_debug_redacts_url_userinfo_and_query() {
        let secret = "hunter2";
        let config = ServerConfig::builder()
            .http_transport(format!(
                "https://user:{secret}@api.example.com/mcp?token={secret}"
            ))
            .build()
            .unwrap();

        let debug_str = format!("{config:?}");
        assert!(!debug_str.contains(secret));
        // Host/path stay readable.
        assert!(debug_str.contains("api.example.com/mcp"));
    }

    #[test]
    fn test_server_config_builder_debug_redacts_args() {
        let secret = "sk-live-secret-arg-value";
        let builder = ServerConfig::builder()
            .command("docker".to_string())
            .arg("--api-key".to_string())
            .arg(secret.to_string());

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

    #[test]
    fn test_server_config_builder_debug_redacts_url_userinfo_and_query() {
        let secret = "hunter2";
        let builder = ServerConfig::builder().url(format!(
            "https://user:{secret}@api.example.com/mcp?token={secret}"
        ));

        let debug_str = format!("{builder:?}");
        assert!(!debug_str.contains(secret));
        assert!(debug_str.contains("api.example.com/mcp"));
    }

    #[test]
    fn test_server_config_builder_debug_redacts_env_and_header_values() {
        // Unlike `ServerConfig::build()`, the builder itself doesn't drop
        // env/headers based on transport, so both can be populated at once
        // and inspected via `{:?}` before `build()` is ever called.
        let builder = ServerConfig::builder()
            .command("docker".to_string())
            .env(
                "GITHUB_PERSONAL_ACCESS_TOKEN".to_string(),
                "ghp_supersecretvalue".to_string(),
            )
            .header(
                "Authorization".to_string(),
                "Bearer sk-secret-header-value".to_string(),
            );

        let debug_str = format!("{builder:?}");

        // Keys are useful for debugging and are not secret.
        assert!(debug_str.contains("GITHUB_PERSONAL_ACCESS_TOKEN"));
        assert!(debug_str.contains("Authorization"));
        // Values must never appear.
        assert!(!debug_str.contains("ghp_supersecretvalue"));
        assert!(!debug_str.contains("sk-secret-header-value"));
    }

    #[test]
    fn test_server_config_serialize_still_contains_real_secret_values() {
        // Serialize/Deserialize must round-trip real values for config
        // persistence; only Debug formatting is redacted. Headers and env
        // are exercised separately since `build()` drops whichever one
        // doesn't match the config's transport.
        let http_config = ServerConfig::builder()
            .http_transport("https://api.example.com/mcp".to_string())
            .header(
                "Authorization".to_string(),
                "Bearer sk-secret-header-value".to_string(),
            )
            .build()
            .unwrap();

        let http_json = serde_json::to_string(&http_config).unwrap();
        assert!(http_json.contains("sk-secret-header-value"));

        let http_deserialized: ServerConfig = serde_json::from_str(&http_json).unwrap();
        assert_eq!(http_config, http_deserialized);

        let stdio_config = ServerConfig::builder()
            .command("docker".to_string())
            .env(
                "GITHUB_PERSONAL_ACCESS_TOKEN".to_string(),
                "ghp_supersecretvalue".to_string(),
            )
            .build()
            .unwrap();

        let stdio_json = serde_json::to_string(&stdio_config).unwrap();
        assert!(stdio_json.contains("ghp_supersecretvalue"));

        let stdio_deserialized: ServerConfig = serde_json::from_str(&stdio_json).unwrap();
        assert_eq!(stdio_config, stdio_deserialized);
    }

    #[test]
    fn test_transport_kind_default() {
        assert_eq!(TransportKind::default(), TransportKind::Stdio);
    }

    #[test]
    fn test_server_config_http_transport() {
        let config = ServerConfig::builder()
            .http_transport("https://api.example.com/mcp".to_string())
            .build()
            .unwrap();

        assert!(matches!(config.transport(), Transport::Http { .. }));
        assert_eq!(config.url(), Some("https://api.example.com/mcp"));
        assert!(config.headers().is_empty());
        assert!(config.command().is_none());
        assert!(config.args().is_empty());
        assert!(config.env().is_empty());
        assert_eq!(config.cwd(), None);
    }

    #[test]
    fn test_server_config_http_with_headers() {
        let config = ServerConfig::builder()
            .http_transport("https://api.example.com/mcp".to_string())
            .header("Authorization".to_string(), "Bearer token".to_string())
            .header("Content-Type".to_string(), "application/json".to_string())
            .build()
            .unwrap();

        assert!(matches!(config.transport(), Transport::Http { .. }));
        assert_eq!(config.headers().len(), 2);
        assert_eq!(
            config.headers().get("Authorization"),
            Some(&"Bearer token".to_string())
        );
        assert_eq!(
            config.headers().get("Content-Type"),
            Some(&"application/json".to_string())
        );
    }

    #[test]
    fn test_server_config_http_with_headers_map() {
        let mut headers = HashMap::new();
        headers.insert("Authorization".to_string(), "Bearer token".to_string());

        let config = ServerConfig::builder()
            .http_transport("https://api.example.com/mcp".to_string())
            .headers(headers)
            .build()
            .unwrap();

        assert_eq!(config.headers().len(), 1);
    }

    /// This does not call `.http_transport(...)`, so the builder's transport kind stays at its
    /// `Stdio` default — it exercises `build_structural`'s "command is required" branch, not an
    /// HTTP-specific one. See `test_server_config_http_build_missing_url` below for the actual
    /// HTTP-missing-url branch.
    #[test]
    fn test_server_config_default_builder_build_missing_command() {
        let result = ServerConfig::builder().build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("required"));
    }

    /// `TransportKind::Http` is only reachable through the public builder API via
    /// `.http_transport(url)`, which always sets `url` in the same call — so this branch of
    /// `build_structural` (url missing while the transport kind is `Http`) can't be reached
    /// through any public builder method. Poke the private `transport` field directly, mirroring
    /// `test_server_config_sse_build_missing_url` below, so the branch has coverage at all.
    #[test]
    fn test_server_config_http_build_missing_url() {
        let mut builder = ServerConfig::builder();
        builder.transport = TransportKind::Http;

        let result = builder.build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("url is required"));
    }

    #[test]
    fn test_server_config_http_accessors() {
        let config = ServerConfig::builder()
            .http_transport("https://api.example.com/mcp".to_string())
            .header("Auth".to_string(), "token".to_string())
            .build()
            .unwrap();

        assert!(matches!(config.transport(), Transport::Http { .. }));
        assert_eq!(config.url(), Some("https://api.example.com/mcp"));
        assert_eq!(config.headers().len(), 1);
    }

    #[test]
    fn test_server_config_stdio_default_transport() {
        let config = ServerConfig::builder()
            .command("docker".to_string())
            .build()
            .unwrap();

        assert!(matches!(config.transport(), Transport::Stdio { .. }));
    }

    #[test]
    fn test_server_config_sse_transport() {
        let config = ServerConfig::builder()
            .sse_transport("https://api.example.com/sse".to_string())
            .build()
            .unwrap();

        assert!(matches!(config.transport(), Transport::Sse { .. }));
        assert_eq!(config.url(), Some("https://api.example.com/sse"));
        assert!(config.headers().is_empty());
        assert!(config.command().is_none());
        assert!(config.args().is_empty());
        assert!(config.env().is_empty());
        assert_eq!(config.cwd(), None);
    }

    /// The `Debug` impl's `Transport::Sse` arm (see `impl fmt::Debug for ServerConfig` above)
    /// is otherwise never exercised — every other `Debug`-redaction test builds an `Http` or
    /// `Stdio` config.
    #[test]
    fn test_server_config_debug_sse() {
        let secret = "sk-secret-sse-header-value";
        let config = ServerConfig::builder()
            .sse_transport("https://api.example.com/sse".to_string())
            .header("Authorization".to_string(), secret.to_string())
            .build()
            .unwrap();

        let debug_str = format!("{config:?}");
        assert!(debug_str.contains("api.example.com/sse"));
        assert!(debug_str.contains("Authorization"));
        assert!(!debug_str.contains(secret));
    }

    /// Companion to `test_server_config_serialize_still_contains_real_secret_values`, which
    /// only exercises `Stdio`/`Http` round-tripping — `Sse` shares their `url`/`headers` shape
    /// but had no round-trip test of its own.
    #[test]
    fn test_server_config_sse_serialize_deserialize_round_trip() {
        let config = ServerConfig::builder()
            .sse_transport("https://api.example.com/sse".to_string())
            .header("Authorization".to_string(), "Bearer token".to_string())
            .build()
            .unwrap();

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: ServerConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, deserialized);
    }

    #[test]
    fn test_server_config_sse_with_headers() {
        let config = ServerConfig::builder()
            .sse_transport("https://api.example.com/sse".to_string())
            .header("Authorization".to_string(), "Bearer token".to_string())
            .header("X-Custom".to_string(), "value".to_string())
            .build()
            .unwrap();

        assert!(matches!(config.transport(), Transport::Sse { .. }));
        assert_eq!(config.headers().len(), 2);
        assert_eq!(
            config.headers().get("Authorization"),
            Some(&"Bearer token".to_string())
        );
        assert_eq!(config.headers().get("X-Custom"), Some(&"value".to_string()));
    }

    #[test]
    fn test_server_config_sse_build_missing_url() {
        let mut builder = ServerConfig::builder();
        builder.transport = TransportKind::Sse;

        let result = builder.build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("url is required"));
    }

    #[test]
    fn test_transport_serialization_tags_variant() {
        let stdio = ServerConfig::builder()
            .command("docker".to_string())
            .build()
            .unwrap();
        let http = ServerConfig::builder()
            .http_transport("https://api.example.com/mcp".to_string())
            .build()
            .unwrap();
        let sse = ServerConfig::builder()
            .sse_transport("https://api.example.com/sse".to_string())
            .build()
            .unwrap();

        assert!(
            serde_json::to_string(&stdio)
                .unwrap()
                .contains(r#""transport":"stdio""#)
        );
        assert!(
            serde_json::to_string(&http)
                .unwrap()
                .contains(r#""transport":"http""#)
        );
        assert!(
            serde_json::to_string(&sse)
                .unwrap()
                .contains(r#""transport":"sse""#)
        );
    }

    #[test]
    fn test_transport_deserialization_from_tag() {
        let stdio: ServerConfig =
            serde_json::from_str(r#"{"transport":"stdio","command":"docker"}"#).unwrap();
        let http: ServerConfig =
            serde_json::from_str(r#"{"transport":"http","url":"https://api.example.com/mcp"}"#)
                .unwrap();
        let sse: ServerConfig =
            serde_json::from_str(r#"{"transport":"sse","url":"https://api.example.com/sse"}"#)
                .unwrap();

        assert!(matches!(stdio.transport(), Transport::Stdio { .. }));
        assert!(matches!(http.transport(), Transport::Http { .. }));
        assert!(matches!(sse.transport(), Transport::Sse { .. }));
    }

    /// #313 — the enum shape makes an incomplete Http config impossible to deserialize at
    /// all: `url` is a required (non-`#[serde(default)]`) field of `Transport::Http`, so a
    /// hand-edited `mcp.json` with `"transport": "http"` and no `url` key now fails at
    /// deserialization time rather than silently producing an incomplete `ServerConfig` that
    /// only `validate_server_config` would have caught downstream.
    #[test]
    fn test_deserialize_http_config_missing_url_is_rejected() {
        let result: std::result::Result<ServerConfig, _> =
            serde_json::from_str(r#"{"transport": "http"}"#);
        assert!(result.is_err());
    }

    /// #313 — `Deserialize` itself now runs the same security validation `build()` does, so
    /// a hand-edited `mcp.json` carrying a shell metacharacter fails to deserialize at all.
    #[test]
    fn test_deserialize_rejects_shell_metacharacters() {
        let result: std::result::Result<ServerConfig, _> = serde_json::from_str(
            r#"{"transport":"stdio","command":"docker","args":["run; rm -rf /"]}"#,
        );
        assert!(result.is_err());
    }

    /// #345 — `Transport` used to derive plain `Debug`, so `format!("{:?}", transport)` on a
    /// bare value (e.g. matched out of `ServerConfig::transport()`) leaked secrets even though
    /// `ServerConfig`'s own `Debug` impl already redacted the same fields.
    #[test]
    fn test_transport_debug_redacts_stdio_args_and_env() {
        let secret_arg = "sk-live-secret-arg-value";
        let secret_env = "ghp_supersecretvalue";
        let transport = Transport::Stdio {
            command: "docker".to_string(),
            args: vec!["--api-key".to_string(), secret_arg.to_string()],
            env: HashMap::from([(
                "GITHUB_PERSONAL_ACCESS_TOKEN".to_string(),
                secret_env.to_string(),
            )]),
            cwd: None,
        };

        let debug_str = format!("{transport:?}");
        assert!(debug_str.contains("docker"));
        assert!(debug_str.contains("GITHUB_PERSONAL_ACCESS_TOKEN"));
        assert!(!debug_str.contains(secret_arg));
        assert!(!debug_str.contains(secret_env));
    }

    #[test]
    fn test_transport_debug_redacts_http_url_and_headers() {
        let secret = "hunter2";
        let transport = Transport::Http {
            url: format!("https://user:{secret}@api.example.com/mcp?token={secret}"),
            headers: HashMap::from([("Authorization".to_string(), secret.to_string())]),
        };

        let debug_str = format!("{transport:?}");
        assert!(debug_str.contains("api.example.com/mcp"));
        assert!(debug_str.contains("Authorization"));
        assert!(!debug_str.contains(secret));
    }

    /// Companion to the `Http` case above — `Transport::Sse` shares the same `url`/`headers`
    /// shape but is a distinct match arm in the `Debug` impl, so it needs its own coverage.
    #[test]
    fn test_transport_debug_redacts_sse_url_and_headers() {
        let secret = "sk-secret-sse-header-value";
        let transport = Transport::Sse {
            url: "https://api.example.com/sse".to_string(),
            headers: HashMap::from([("Authorization".to_string(), secret.to_string())]),
        };

        let debug_str = format!("{transport:?}");
        assert!(debug_str.contains("api.example.com/sse"));
        assert!(debug_str.contains("Authorization"));
        assert!(!debug_str.contains(secret));
    }
}