Skip to main content

vtcode_config/mcp/
transport.rs

1//! MCP provider transport configuration and deserialization.
2//!
3//! Extracted from the `mcp` module so the transport wire-decoding lives behind
4//! a strict interface: [`McpProviderConfig`] is the only public entry point and
5//! [`McpProviderConfigWire`] is private to this module. Callers never see the
6//! flat wire shape — they construct or deserialize [`McpProviderConfig`] and
7//! pattern-match on [`McpTransportConfig`].
8//!
9//! The manual [`Deserialize`] impl avoids the `#[serde(flatten)]` +
10//! `#[serde(untagged)]` map-buffering overhead: every transport field is
11//! decoded in a single pass and the transport enum is constructed afterwards,
12//! preserving the untagged Stdio-then-Http precedence. See the regression tests
13//! at the bottom of this file for the exact dispatch contract.
14//!
15//! # Validation semantics (intentional guardrail)
16//!
17//! Because every recognized field is decoded against its declared type in that
18//! single pass, a malformed *known* field is rejected even when it belongs to
19//! the transport variant that was not selected. The previous `#[serde(untagged)]`
20//! path trial-deserialized Stdio first and silently ignored irrelevant HTTP
21//! fields (and vice-versa), so a stray wrong-typed `endpoint` on a valid Stdio
22//! provider used to parse. Under the flat wire it now errors. This stricter
23//! behavior is an intentional interface guardrail — surfacing malformed known
24//! configuration early — and is not a behavior-preserving no-op relative to the
25//! derived path. Forward compatibility for *unknown* fields is unaffected: the
26//! wire ignores any field it does not declare.
27
28use crate::env_helpers::default_enabled;
29use hashbrown::HashMap;
30use serde::{Deserialize, Deserializer, Serialize};
31use std::collections::BTreeMap;
32use vtcode_auth::McpOAuthConfig;
33
34/// Transport configuration for MCP providers
35#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
36#[allow(
37    clippy::large_enum_variant,
38    reason = "Intentional compatibility, platform, or test-only suppression."
39)]
40#[derive(Debug, Clone, Deserialize, Serialize)]
41#[serde(untagged)]
42pub enum McpTransportConfig {
43    /// Standard I/O transport (stdio)
44    Stdio(McpStdioServerConfig),
45    /// HTTP transport
46    Http(McpHttpServerConfig),
47}
48
49/// Configuration for stdio-based MCP servers
50#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
51#[derive(Debug, Clone, Deserialize, Serialize, Default)]
52pub struct McpStdioServerConfig {
53    /// Command to execute
54    pub command: String,
55
56    /// Command arguments
57    pub args: Vec<String>,
58
59    /// Working directory for the command
60    #[serde(default)]
61    pub working_directory: Option<String>,
62}
63
64/// Pinned MCP protocol versions (single source of truth for version strings).
65///
66/// The typed rmcp counterparts live in `vtcode-mcp` (`stable_protocol_version`,
67/// `legacy_fallback_protocol_version`); keep both sides aligned when the spec
68/// publishes a new stable revision.
69pub const MCP_STABLE_PROTOCOL_VERSION: &str = "2025-11-25";
70pub const MCP_LEGACY_PROTOCOL_VERSION: &str = "2024-11-05";
71
72/// Handshake strategy for HTTP-based MCP servers.
73///
74/// `Legacy` performs the `initialize` / `notifications/initialized` handshake
75/// directly (rmcp `ClientLifecycleMode::Initialize`). `Auto` first probes
76/// `server/discover` and falls back to the legacy handshake when the peer
77/// reports a legacy server or stays silent past the discover timeout (rmcp
78/// `ClientLifecycleMode::Auto`). Legacy is the default: it avoids the
79/// discover-timeout penalty against legacy-only servers.
80#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
82#[serde(rename_all = "snake_case")]
83pub enum McpHttpHandshakeMode {
84    #[default]
85    Legacy,
86    Auto,
87}
88
89/// Configuration for HTTP-based MCP servers
90///
91/// Note: HTTP transport is partially implemented. Basic connectivity testing is supported,
92/// but full streamable HTTP MCP server support requires additional implementation
93/// using Server-Sent Events (SSE) or WebSocket connections.
94#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
95#[derive(Debug, Clone, Deserialize, Serialize)]
96pub struct McpHttpServerConfig {
97    /// Server endpoint URL
98    pub endpoint: String,
99
100    /// API key environment variable name
101    #[serde(default)]
102    pub api_key_env: Option<String>,
103
104    /// Optional OAuth configuration for providers that issue bearer tokens dynamically.
105    #[serde(default)]
106    pub oauth: Option<McpOAuthConfig>,
107
108    /// Protocol version
109    #[serde(default = "default_mcp_protocol_version")]
110    pub protocol_version: String,
111
112    /// Handshake strategy (`legacy` direct initialize, or `auto` discover
113    /// with legacy fallback). Defaults to `legacy`.
114    #[serde(default)]
115    pub handshake: McpHttpHandshakeMode,
116
117    /// Headers to include in requests
118    #[serde(default, alias = "headers")]
119    #[cfg_attr(feature = "schema", schemars(with = "BTreeMap<String, String>"))]
120    pub http_headers: HashMap<String, String>,
121
122    /// Headers whose values are sourced from environment variables
123    /// (`{ header-name = "ENV_VAR" }`). Empty values are ignored.
124    #[serde(default)]
125    #[cfg_attr(feature = "schema", schemars(with = "BTreeMap<String, String>"))]
126    pub env_http_headers: HashMap<String, String>,
127}
128
129impl Default for McpHttpServerConfig {
130    fn default() -> Self {
131        Self {
132            endpoint: String::new(),
133            api_key_env: None,
134            oauth: None,
135            protocol_version: default_mcp_protocol_version(),
136            handshake: McpHttpHandshakeMode::default(),
137            http_headers: HashMap::new(),
138            env_http_headers: HashMap::new(),
139        }
140    }
141}
142
143/// Per-server sandbox overrides, narrowed from the session sandbox policy.
144///
145/// Every field is optional: unset fields inherit the parent policy, and an
146/// absent `sandbox` section leaves the session policy unchanged. Setting any
147/// resource limit opts the server into the conservative cap family for the
148/// unset siblings; limits require a workspace-write session policy, since a
149/// read-only policy carries nothing to intersect.
150#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
151#[derive(Debug, Clone, Default, Deserialize, Serialize)]
152pub struct McpSandboxOverrideConfig {
153    /// Memory cap (MB) applied to this server's child processes.
154    #[serde(default)]
155    pub max_memory_mb: Option<u64>,
156    /// Maximum number of processes / pids in this server's sandbox.
157    #[serde(default)]
158    pub max_pids: Option<u64>,
159    /// CPU time budget in seconds.
160    #[serde(default)]
161    pub cpu_time_secs: Option<u64>,
162    /// Wall-clock timeout in seconds.
163    #[serde(default)]
164    pub timeout_secs: Option<u64>,
165    /// Optional writable root, which must match every explicit parent root.
166    #[serde(default)]
167    pub writable_root: Option<std::path::PathBuf>,
168}
169
170/// Configuration for a single MCP provider
171#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
172#[derive(Debug, Clone, Serialize)]
173pub struct McpProviderConfig {
174    /// Provider name (used for identification)
175    pub name: String,
176
177    /// Transport configuration
178    #[serde(flatten)]
179    pub transport: McpTransportConfig,
180
181    /// Provider-specific environment variables
182    #[serde(default)]
183    #[cfg_attr(feature = "schema", schemars(with = "BTreeMap<String, String>"))]
184    pub env: HashMap<String, String>,
185
186    /// Whether this provider is enabled
187    #[serde(default = "default_provider_enabled")]
188    pub enabled: bool,
189
190    /// Maximum number of concurrent requests to this provider
191    #[serde(default = "default_provider_max_concurrent")]
192    pub max_concurrent_requests: usize,
193
194    /// Startup timeout in milliseconds for this provider
195    #[serde(default)]
196    pub startup_timeout_ms: Option<u64>,
197
198    /// Per-server sandbox overrides, narrowed from the session sandbox policy.
199    /// Absent means inherit the session policy unchanged.
200    #[serde(default)]
201    pub sandbox: Option<McpSandboxOverrideConfig>,
202}
203
204impl<'de> Deserialize<'de> for McpProviderConfig {
205    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
206    where
207        D: Deserializer<'de>,
208    {
209        // Deserialize every provider + transport field in a single pass.
210        // `#[serde(flatten)]` + `#[serde(untagged)]` on `transport` would force
211        // Serde to buffer the whole provider object into a `Map<String, Value>`
212        // and then trial-deserialize each transport variant. A provider has only
213        // two mutually-exclusive transport forms — stdio (`command` + `args`) or
214        // HTTP (`endpoint`) — so the fields are decoded directly and the
215        // transport enum is constructed afterwards, matching the untagged
216        // Stdio-then-Http precedence.
217        //
218        // Note: because every declared field is type-checked in this pass, a
219        // malformed known field is rejected even on the non-selected variant
220        // (stricter than the old untagged trial-deserialize, which ignored
221        // irrelevant fields). See the module-level "Validation semantics" note.
222        let wire = McpProviderConfigWire::deserialize(deserializer)?;
223
224        let transport = if let (Some(command), Some(args)) = (wire.command, wire.args) {
225            McpTransportConfig::Stdio(McpStdioServerConfig {
226                command,
227                args,
228                working_directory: wire.working_directory,
229            })
230        } else if let Some(endpoint) = wire.endpoint {
231            McpTransportConfig::Http(McpHttpServerConfig {
232                endpoint,
233                api_key_env: wire.api_key_env,
234                oauth: wire.oauth,
235                protocol_version: wire.protocol_version,
236                handshake: wire.handshake,
237                http_headers: wire.http_headers,
238                env_http_headers: wire.env_http_headers,
239            })
240        } else {
241            return Err(serde::de::Error::custom(
242                "MCP provider must specify either a stdio `command` (with `args`) or an HTTP `endpoint`",
243            ));
244        };
245
246        Ok(McpProviderConfig {
247            name: wire.name,
248            transport,
249            env: wire.env,
250            enabled: wire.enabled,
251            max_concurrent_requests: wire.max_concurrent_requests,
252            startup_timeout_ms: wire.startup_timeout_ms,
253            sandbox: wire.sandbox,
254        })
255    }
256}
257
258/// Flat wire shape for [`McpProviderConfig`] (see [`McpProviderConfig::deserialize`]).
259///
260/// Every transport field is declared directly so no intermediate map is
261/// buffered. Fields belonging to the unused transport variant simply stay at
262/// their `Option`/default values and are ignored when constructing the
263/// [`McpTransportConfig`].
264#[derive(Deserialize)]
265struct McpProviderConfigWire {
266    name: String,
267    // stdio transport
268    #[serde(default)]
269    command: Option<String>,
270    #[serde(default)]
271    args: Option<Vec<String>>,
272    #[serde(default)]
273    working_directory: Option<String>,
274    // http transport
275    #[serde(default)]
276    endpoint: Option<String>,
277    #[serde(default)]
278    api_key_env: Option<String>,
279    #[serde(default)]
280    oauth: Option<McpOAuthConfig>,
281    #[serde(default = "default_mcp_protocol_version")]
282    protocol_version: String,
283    #[serde(default)]
284    handshake: McpHttpHandshakeMode,
285    #[serde(default, alias = "headers")]
286    http_headers: HashMap<String, String>,
287    #[serde(default)]
288    env_http_headers: HashMap<String, String>,
289    // provider-level
290    #[serde(default)]
291    env: HashMap<String, String>,
292    #[serde(default = "default_provider_enabled")]
293    enabled: bool,
294    #[serde(default = "default_provider_max_concurrent")]
295    max_concurrent_requests: usize,
296    #[serde(default)]
297    startup_timeout_ms: Option<u64>,
298    #[serde(default)]
299    sandbox: Option<McpSandboxOverrideConfig>,
300}
301
302impl Default for McpProviderConfig {
303    fn default() -> Self {
304        Self {
305            name: String::new(),
306            transport: McpTransportConfig::Stdio(McpStdioServerConfig::default()),
307            env: HashMap::new(),
308            enabled: default_provider_enabled(),
309            max_concurrent_requests: default_provider_max_concurrent(),
310            startup_timeout_ms: None,
311            sandbox: None,
312        }
313    }
314}
315
316fn default_provider_enabled() -> bool {
317    default_enabled()
318}
319
320fn default_provider_max_concurrent() -> usize {
321    3
322}
323
324fn default_mcp_protocol_version() -> String {
325    // Default to the current stable spec revision, not the draft. Draft
326    // revisions are in-progress and not ready for consumption
327    // (https://modelcontextprotocol.io/docs/draft/learn/versioning.md);
328    // explicit opt-in to a draft remains possible via config and is still
329    // clamped to the last stable version on the legacy handshake path.
330    MCP_STABLE_PROTOCOL_VERSION.into()
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    #[test]
338    fn test_mcp_provider_config_http_transport_from_toml() {
339        // HTTP provider, discriminated by `endpoint`. Locks in the flat-wire
340        // deserialize path (no `#[serde(flatten)]` + `#[serde(untagged)]`
341        // buffering) for the HTTP transport branch.
342        let toml_str = r#"
343name = "deepwiki"
344enabled = true
345endpoint = "https://mcp.deepwiki.com/mcp"
346protocol_version = "2024-11-05"
347max_concurrent_requests = 3
348
349[http_headers]
350Authorization = "Bearer token"
351"#;
352        let provider: McpProviderConfig = toml::from_str(toml_str).expect("http provider must parse");
353
354        assert_eq!(provider.name, "deepwiki");
355        assert!(provider.enabled);
356        assert_eq!(provider.max_concurrent_requests, 3);
357        match provider.transport {
358            McpTransportConfig::Http(http) => {
359                assert_eq!(http.endpoint, "https://mcp.deepwiki.com/mcp");
360                assert_eq!(http.protocol_version, "2024-11-05");
361                assert_eq!(http.http_headers.get("Authorization"), Some(&"Bearer token".to_string()));
362            }
363            McpTransportConfig::Stdio(_) => panic!("expected HTTP transport"),
364        }
365    }
366
367    #[test]
368    fn test_mcp_provider_config_http_minimal_fields_from_toml() {
369        // Minimal HTTP provider (only `name`, `enabled`, `endpoint`) — the
370        // shape repository `vtcode.toml` provider entries use. Locks in the
371        // serde defaults for every omitted field so config loading cannot
372        // silently start requiring them. Oracles are hardcoded, not the
373        // `default_*` helpers, so a helper regression cannot mask itself.
374        let toml_str = r#"
375name = "cve-now"
376enabled = true
377endpoint = "https://mcp.cve.now/mcp"
378"#;
379        let provider: McpProviderConfig = toml::from_str(toml_str).expect("minimal http provider must parse");
380
381        assert_eq!(provider.name, "cve-now");
382        assert!(provider.enabled);
383        match provider.transport {
384            McpTransportConfig::Http(http) => {
385                assert_eq!(http.endpoint, "https://mcp.cve.now/mcp");
386                assert_eq!(http.protocol_version, "2025-11-25");
387                assert_eq!(http.handshake, McpHttpHandshakeMode::Legacy);
388                assert!(http.oauth.is_none());
389                assert!(http.http_headers.is_empty());
390                assert!(http.env_http_headers.is_empty());
391            }
392            McpTransportConfig::Stdio(_) => panic!("expected HTTP transport"),
393        }
394    }
395
396    #[test]
397    fn test_mcp_provider_config_stdio_transport_from_toml() {
398        let toml_str = r#"
399name = "time"
400command = "uvx"
401args = ["mcp-server-time"]
402working_directory = "/tmp"
403"#;
404        let provider: McpProviderConfig = toml::from_str(toml_str).expect("stdio provider must parse");
405        match provider.transport {
406            McpTransportConfig::Stdio(stdio) => {
407                assert_eq!(stdio.command, "uvx");
408                assert_eq!(stdio.args, vec!["mcp-server-time"]);
409                assert_eq!(stdio.working_directory.as_deref(), Some("/tmp"));
410            }
411            McpTransportConfig::Http(_) => panic!("expected stdio transport"),
412        }
413    }
414
415    #[test]
416    fn test_mcp_provider_config_sandbox_absent_by_default() {
417        let toml_str = r#"
418name = "plain"
419command = "uvx"
420args = ["mcp-server-time"]
421"#;
422        let provider: McpProviderConfig = toml::from_str(toml_str).expect("provider without sandbox must parse");
423        assert!(provider.sandbox.is_none());
424    }
425
426    #[test]
427    fn test_mcp_provider_config_sandbox_overrides_parse() {
428        let toml_str = r#"
429name = "capped"
430command = "uvx"
431args = ["mcp-server-time"]
432
433[sandbox]
434max_memory_mb = 256
435timeout_secs = 30
436writable_root = "/tmp/work"
437"#;
438        let provider: McpProviderConfig = toml::from_str(toml_str).expect("provider with sandbox must parse");
439        let sandbox = provider.sandbox.expect("sandbox section must parse");
440        assert_eq!(sandbox.max_memory_mb, Some(256));
441        assert_eq!(sandbox.timeout_secs, Some(30));
442        assert_eq!(sandbox.max_pids, None);
443        assert_eq!(sandbox.writable_root.as_deref(), Some(std::path::Path::new("/tmp/work")));
444    }
445
446    #[test]
447    fn test_mcp_provider_config_stdio_wins_when_both_transports_present() {
448        // Replicates the untagged Stdio-then-Http precedence: `command` + `args`
449        // select stdio even when `endpoint` is also set.
450        let toml_str = r#"
451name = "mixed"
452command = "uvx"
453args = ["mcp-server-time"]
454endpoint = "https://example.com/mcp"
455"#;
456        let provider: McpProviderConfig = toml::from_str(toml_str).expect("mixed provider must parse");
457        assert!(matches!(provider.transport, McpTransportConfig::Stdio(_)));
458    }
459
460    #[test]
461    fn test_mcp_provider_config_http_fallback_when_command_lacks_args() {
462        // `command` without `args` cannot form a stdio transport, so the
463        // presence of `endpoint` selects HTTP (matches untagged fallback).
464        let toml_str = r#"
465name = "fallback"
466command = "uvx"
467endpoint = "https://example.com/mcp"
468"#;
469        let provider: McpProviderConfig = toml::from_str(toml_str).expect("fallback provider must parse");
470        assert!(matches!(provider.transport, McpTransportConfig::Http(_)));
471    }
472
473    #[test]
474    fn test_mcp_provider_config_rejects_missing_transport() {
475        let toml_str = "name = \"bare\"";
476        let result: Result<McpProviderConfig, _> = toml::from_str(toml_str);
477        assert!(result.is_err(), "provider without command/endpoint must error");
478    }
479
480    #[test]
481    fn test_mcp_provider_config_rejects_malformed_known_field_on_non_selected_transport() {
482        // Intentional strict guardrail: a wrong-typed *known* field is rejected
483        // even when it belongs to the transport variant that was not selected.
484        // The old `#[serde(untagged)]` path would select Stdio (valid
485        // `command` + `args`) and silently ignore the malformed `endpoint`; the
486        // flat wire type-checks every declared field in one pass, so this now
487        // errors. See the module-level "Validation semantics" note.
488        let toml_str = r#"
489name = "strict"
490command = "uvx"
491args = ["mcp-server-time"]
492endpoint = 42
493"#;
494        let result: Result<McpProviderConfig, _> = toml::from_str(toml_str);
495        assert!(result.is_err(), "malformed known field on non-selected transport must error under the flat wire");
496    }
497
498    #[test]
499    fn test_mcp_http_handshake_defaults_to_legacy() {
500        let config = McpHttpServerConfig::default();
501        assert_eq!(config.handshake, McpHttpHandshakeMode::Legacy);
502
503        let toml_str = r#"
504name = "plain"
505endpoint = "https://example.com/mcp"
506"#;
507        let provider: McpProviderConfig = toml::from_str(toml_str).expect("http provider must parse");
508        match provider.transport {
509            McpTransportConfig::Http(http) => assert_eq!(http.handshake, McpHttpHandshakeMode::Legacy),
510            McpTransportConfig::Stdio(_) => panic!("expected HTTP transport"),
511        }
512    }
513
514    #[test]
515    fn test_mcp_http_handshake_parses_auto() {
516        let toml_str = r#"
517name = "modern"
518endpoint = "https://example.com/mcp"
519handshake = "auto"
520"#;
521        let provider: McpProviderConfig = toml::from_str(toml_str).expect("http provider must parse");
522        match provider.transport {
523            McpTransportConfig::Http(http) => assert_eq!(http.handshake, McpHttpHandshakeMode::Auto),
524            McpTransportConfig::Stdio(_) => panic!("expected HTTP transport"),
525        }
526    }
527}