Skip to main content

vtcode_config/
mcp.rs

1use hashbrown::HashMap;
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4
5mod transport;
6#[cfg(test)]
7mod wildcard_tests;
8
9pub use transport::{
10    MCP_LEGACY_PROTOCOL_VERSION, MCP_STABLE_PROTOCOL_VERSION, McpHttpHandshakeMode, McpHttpServerConfig,
11    McpProviderConfig, McpSandboxOverrideConfig, McpStdioServerConfig, McpTransportConfig,
12};
13
14/// Top-level MCP configuration
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16#[derive(Debug, Clone, Deserialize, Serialize)]
17pub struct McpClientConfig {
18    /// Enable MCP functionality
19    #[serde(default = "default_mcp_enabled")]
20    pub enabled: bool,
21
22    /// MCP UI display configuration
23    #[serde(default)]
24    pub ui: McpUiConfig,
25
26    /// Configured MCP providers
27    #[serde(default)]
28    pub providers: Vec<McpProviderConfig>,
29
30    /// Optional transport-identity requirements for provider admission
31    #[serde(default)]
32    pub requirements: McpRequirementsConfig,
33
34    /// MCP server configuration (for vtcode to expose tools)
35    #[serde(default)]
36    pub server: McpServerConfig,
37
38    /// Allow list configuration for MCP access control
39    #[serde(default)]
40    pub allowlist: McpAllowListConfig,
41
42    /// Maximum number of concurrent MCP connections
43    #[serde(default = "default_max_concurrent_connections")]
44    pub max_concurrent_connections: usize,
45
46    /// Timeout (seconds) for a single MCP tool call.
47    ///
48    /// Distinct from `connection_timeout_seconds`, which bounds the
49    /// connect-and-handshake phase during startup.
50    #[serde(default = "default_request_timeout_seconds")]
51    pub request_timeout_seconds: u64,
52
53    /// Connection retry attempts
54    #[serde(default = "default_retry_attempts")]
55    pub retry_attempts: u32,
56
57    /// Optional timeout (seconds) when starting providers
58    #[serde(default)]
59    pub startup_timeout_seconds: Option<u64>,
60
61    /// Optional timeout (seconds) for tool execution
62    #[serde(default)]
63    pub tool_timeout_seconds: Option<u64>,
64
65    /// Toggle experimental RMCP client features
66    #[serde(default = "default_experimental_use_rmcp_client")]
67    pub experimental_use_rmcp_client: bool,
68
69    /// Enable connection pooling for better performance
70    #[serde(default = "default_connection_pooling_enabled")]
71    pub connection_pooling_enabled: bool,
72
73    /// Cache capacity for tool discovery results
74    #[serde(default = "default_tool_cache_capacity")]
75    pub tool_cache_capacity: usize,
76
77    /// Connection timeout in seconds
78    #[serde(default = "default_connection_timeout_seconds")]
79    pub connection_timeout_seconds: u64,
80
81    /// Security configuration for MCP
82    #[serde(default)]
83    pub security: McpSecurityConfig,
84
85    /// Model-driven MCP lifecycle controls (connect/disconnect).
86    #[serde(default)]
87    pub lifecycle: McpLifecycleConfig,
88}
89
90/// Security configuration for MCP
91#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
92#[derive(Debug, Clone, Deserialize, Serialize)]
93pub struct McpSecurityConfig {
94    /// Enable authentication for MCP server
95    #[serde(default = "default_mcp_auth_enabled")]
96    pub auth_enabled: bool,
97
98    /// API key for MCP server authentication (environment variable name)
99    #[serde(default)]
100    pub api_key_env: Option<String>,
101
102    /// Rate limiting configuration
103    #[serde(default)]
104    rate_limit: McpRateLimitConfig,
105
106    /// Tool call validation configuration
107    #[serde(default)]
108    pub validation: McpValidationConfig,
109}
110
111impl Default for McpSecurityConfig {
112    fn default() -> Self {
113        Self {
114            auth_enabled: default_mcp_auth_enabled(),
115            api_key_env: None,
116            rate_limit: McpRateLimitConfig::default(),
117            validation: McpValidationConfig::default(),
118        }
119    }
120}
121
122/// Rate limiting configuration for MCP
123#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
124#[derive(Debug, Clone, Deserialize, Serialize)]
125pub struct McpRateLimitConfig {
126    /// Maximum requests per minute per client
127    #[serde(default = "default_requests_per_minute")]
128    requests_per_minute: u32,
129
130    /// Maximum concurrent requests per client
131    #[serde(default = "default_concurrent_requests")]
132    concurrent_requests: u32,
133}
134
135impl Default for McpRateLimitConfig {
136    fn default() -> Self {
137        Self {
138            requests_per_minute: default_requests_per_minute(),
139            concurrent_requests: default_concurrent_requests(),
140        }
141    }
142}
143
144/// Validation configuration for MCP
145#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
146#[derive(Debug, Clone, Deserialize, Serialize)]
147pub struct McpValidationConfig {
148    /// Enable JSON schema validation for tool arguments
149    #[serde(default = "default_schema_validation_enabled")]
150    schema_validation_enabled: bool,
151
152    /// Enable path traversal protection
153    #[serde(default = "default_path_traversal_protection_enabled")]
154    pub path_traversal_protection: bool,
155
156    /// Maximum argument size in bytes
157    #[serde(default = "default_max_argument_size")]
158    pub max_argument_size: u32,
159}
160
161impl Default for McpValidationConfig {
162    fn default() -> Self {
163        Self {
164            schema_validation_enabled: default_schema_validation_enabled(),
165            path_traversal_protection: default_path_traversal_protection_enabled(),
166            max_argument_size: default_max_argument_size(),
167        }
168    }
169}
170
171impl Default for McpClientConfig {
172    fn default() -> Self {
173        Self {
174            enabled: default_mcp_enabled(),
175            ui: McpUiConfig::default(),
176            providers: Vec::new(),
177            requirements: McpRequirementsConfig::default(),
178            server: McpServerConfig::default(),
179            allowlist: McpAllowListConfig::default(),
180            max_concurrent_connections: default_max_concurrent_connections(),
181            request_timeout_seconds: default_request_timeout_seconds(),
182            retry_attempts: default_retry_attempts(),
183            startup_timeout_seconds: None,
184            tool_timeout_seconds: None,
185            experimental_use_rmcp_client: default_experimental_use_rmcp_client(),
186            security: McpSecurityConfig::default(),
187            lifecycle: McpLifecycleConfig::default(),
188            connection_pooling_enabled: default_connection_pooling_enabled(),
189            connection_timeout_seconds: default_connection_timeout_seconds(),
190            tool_cache_capacity: default_tool_cache_capacity(),
191        }
192    }
193}
194
195/// Lifecycle controls for MCP server management.
196#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
197#[derive(Debug, Clone, Deserialize, Serialize)]
198pub struct McpLifecycleConfig {
199    /// Allow model-callable tools to connect/disconnect MCP servers at runtime.
200    #[serde(default = "default_allow_model_lifecycle_control")]
201    pub allow_model_control: bool,
202}
203
204impl Default for McpLifecycleConfig {
205    fn default() -> Self {
206        Self {
207            allow_model_control: default_allow_model_lifecycle_control(),
208        }
209    }
210}
211
212/// Requirements used to admit MCP providers by transport identity.
213#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
214#[derive(Debug, Clone, Deserialize, Serialize)]
215pub struct McpRequirementsConfig {
216    /// Whether requirement checks are enforced
217    #[serde(default = "default_mcp_requirements_enforce")]
218    pub enforce: bool,
219
220    /// Allowed stdio command names when enforcement is enabled
221    #[serde(default)]
222    pub allowed_stdio_commands: Vec<String>,
223
224    /// Allowed HTTP endpoints when enforcement is enabled
225    #[serde(default)]
226    pub allowed_http_endpoints: Vec<String>,
227}
228
229impl Default for McpRequirementsConfig {
230    fn default() -> Self {
231        Self {
232            enforce: default_mcp_requirements_enforce(),
233            allowed_stdio_commands: Vec::new(),
234            allowed_http_endpoints: Vec::new(),
235        }
236    }
237}
238
239/// UI configuration for MCP display
240#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
241#[derive(Debug, Clone, Deserialize, Serialize)]
242pub struct McpUiConfig {
243    /// UI mode for MCP events: "compact" or "full"
244    #[serde(default = "default_mcp_ui_mode")]
245    pub mode: McpUiMode,
246
247    /// Maximum number of MCP events to display
248    #[serde(default = "default_max_mcp_events")]
249    pub max_events: usize,
250
251    /// Show MCP provider names in UI
252    #[serde(default = "default_show_provider_names")]
253    pub show_provider_names: bool,
254
255    /// Custom renderer profiles for provider-specific output formatting
256    #[serde(default)]
257    #[cfg_attr(feature = "schema", schemars(with = "BTreeMap<String, McpRendererProfile>"))]
258    pub renderers: HashMap<String, McpRendererProfile>,
259
260    /// MCP Apps preview tier ("off" refuses app UI without fetching and emits a sandbox-denied event,
261    /// "static" shows disclosure rows plus an inert HTML preview, "interactive" needs an app engine and is
262    /// currently rejected). Options: "off", "static", "interactive"
263    #[serde(default = "default_mcp_ui_apps")]
264    pub apps: McpUiAppsTier,
265}
266
267impl Default for McpUiConfig {
268    fn default() -> Self {
269        Self {
270            mode: default_mcp_ui_mode(),
271            max_events: default_max_mcp_events(),
272            show_provider_names: default_show_provider_names(),
273            renderers: HashMap::new(),
274            apps: default_mcp_ui_apps(),
275        }
276    }
277}
278
279impl McpUiConfig {
280    /// Resolve renderer profile for a provider or tool identifier
281    fn renderer_for_identifier(&self, identifier: &str) -> Option<McpRendererProfile> {
282        let normalized_identifier = normalize_mcp_identifier(identifier);
283        if normalized_identifier.is_empty() {
284            return None;
285        }
286
287        self.renderers.iter().find_map(|(key, profile)| {
288            let normalized_key = normalize_mcp_identifier(key);
289            if normalized_identifier.starts_with(&normalized_key) {
290                Some(*profile)
291            } else {
292                None
293            }
294        })
295    }
296
297    /// Resolve renderer profile for a fully qualified tool name
298    pub fn renderer_for_tool(&self, tool_name: &str) -> Option<McpRendererProfile> {
299        let identifier = tool_name.trim_prefix("mcp_");
300        self.renderer_for_identifier(identifier)
301    }
302}
303
304/// UI mode for MCP event display
305#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
306#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
307#[serde(rename_all = "snake_case")]
308#[derive(Default)]
309pub enum McpUiMode {
310    /// Compact mode - shows only event titles
311    #[default]
312    Compact,
313    /// Full mode - shows detailed event logs
314    Full,
315}
316
317impl std::fmt::Display for McpUiMode {
318    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319        match self {
320            McpUiMode::Compact => write!(f, "compact"),
321            McpUiMode::Full => write!(f, "full"),
322        }
323    }
324}
325
326/// MCP Apps presentation tier: how a surface may present `ui://` app resources.
327#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
329#[serde(rename_all = "snake_case")]
330#[derive(Default)]
331pub enum McpUiAppsTier {
332    /// Refuse app UI: no `ui://` fetch, no disclosure rows. Refused URIs
333    /// surface through a sandbox-denied event instead.
334    #[default]
335    Off,
336    /// Disclosure rows plus an opt-in static preview of sanitized app structure; no interactivity.
337    Static,
338    /// Full interactive app. Rejected until a sandboxed webview host exists.
339    Interactive,
340}
341
342impl McpUiAppsTier {
343    /// Whether this tier may advertise the `io.modelcontextprotocol/ui` extension.
344    ///
345    /// Only `Interactive` can honor app round-trips; a static preview must not
346    /// advertise support it cannot fulfill.
347    #[must_use]
348    pub fn advertises_ui_extension(self) -> bool {
349        matches!(self, McpUiAppsTier::Interactive)
350    }
351}
352
353impl std::fmt::Display for McpUiAppsTier {
354    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355        match self {
356            McpUiAppsTier::Off => write!(f, "off"),
357            McpUiAppsTier::Static => write!(f, "static"),
358            McpUiAppsTier::Interactive => write!(f, "interactive"),
359        }
360    }
361}
362
363/// Named renderer profiles for MCP tool output formatting
364#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
365#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
366#[serde(rename_all = "kebab-case")]
367pub enum McpRendererProfile {
368    /// Context7 knowledge base renderer
369    Context7,
370    /// Sequential thinking trace renderer
371    SequentialThinking,
372}
373
374/// Allow list configuration for MCP providers
375#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
376#[derive(Debug, Clone, Deserialize, Serialize)]
377pub struct McpAllowListConfig {
378    /// Whether to enforce allow list checks
379    #[serde(default = "default_allowlist_enforced")]
380    pub enforce: bool,
381
382    /// Default rules applied when provider-specific rules are absent
383    #[serde(default)]
384    pub default: McpAllowListRules,
385
386    /// Provider-specific allow list rules
387    #[serde(default)]
388    pub providers: BTreeMap<String, McpAllowListRules>,
389}
390
391impl Default for McpAllowListConfig {
392    fn default() -> Self {
393        Self {
394            enforce: default_allowlist_enforced(),
395            default: McpAllowListRules::default(),
396            providers: BTreeMap::new(),
397        }
398    }
399}
400
401impl McpAllowListConfig {
402    /// Determine whether a tool is permitted for the given provider
403    #[must_use]
404    pub fn is_tool_allowed(&self, provider: &str, tool_name: &str) -> bool {
405        if !self.enforce {
406            return true;
407        }
408
409        self.resolve_match(provider, tool_name, |rules| rules.tools.as_deref())
410    }
411
412    /// Determine whether a resource is permitted for the given provider
413    #[must_use]
414    pub fn is_resource_allowed(&self, provider: &str, resource: &str) -> bool {
415        if !self.enforce {
416            return true;
417        }
418
419        self.resolve_match(provider, resource, |rules| rules.resources.as_deref())
420    }
421
422    /// Determine whether a prompt is permitted for the given provider
423    #[must_use]
424    pub fn is_prompt_allowed(&self, provider: &str, prompt: &str) -> bool {
425        if !self.enforce {
426            return true;
427        }
428
429        self.resolve_match(provider, prompt, |rules| rules.prompts.as_deref())
430    }
431
432    /// Determine whether a logging channel is permitted
433    fn is_logging_channel_allowed(&self, provider: Option<&str>, channel: &str) -> bool {
434        if !self.enforce {
435            return true;
436        }
437
438        if let Some(name) = provider
439            && let Some(rules) = self.providers.get(name)
440            && let Some(patterns) = &rules.logging
441        {
442            return pattern_matches(patterns, channel);
443        }
444
445        if let Some(patterns) = &self.default.logging
446            && pattern_matches(patterns, channel)
447        {
448            return true;
449        }
450
451        false
452    }
453
454    /// Determine whether a configuration key can be modified
455    fn is_configuration_allowed(&self, provider: Option<&str>, category: &str, key: &str) -> bool {
456        if !self.enforce {
457            return true;
458        }
459
460        if let Some(name) = provider
461            && let Some(rules) = self.providers.get(name)
462            && let Some(result) = configuration_allowed(rules, category, key)
463        {
464            return result;
465        }
466
467        if let Some(result) = configuration_allowed(&self.default, category, key) {
468            return result;
469        }
470
471        false
472    }
473
474    fn resolve_match<'a, F>(&'a self, provider: &str, candidate: &str, accessor: F) -> bool
475    where
476        F: Fn(&'a McpAllowListRules) -> Option<&'a [String]>,
477    {
478        if let Some(rules) = self.providers.get(provider)
479            && let Some(patterns) = accessor(rules)
480        {
481            return pattern_matches(patterns, candidate);
482        }
483
484        if let Some(patterns) = accessor(&self.default)
485            && pattern_matches(patterns, candidate)
486        {
487            return true;
488        }
489
490        false
491    }
492}
493
494fn configuration_allowed(rules: &McpAllowListRules, category: &str, key: &str) -> Option<bool> {
495    rules
496        .configuration
497        .as_ref()
498        .and_then(|entries| entries.get(category).map(|patterns| pattern_matches(patterns, key)))
499}
500
501fn pattern_matches(patterns: &[String], candidate: &str) -> bool {
502    patterns.iter().any(|pattern| wildcard_match(pattern, candidate))
503}
504
505/// Match a user-authored allow-list pattern against a tool/resource/prompt name.
506///
507/// Only `*` (any run of characters) and `?` (exactly one character) are
508/// metacharacters; every other character is literal and the whole pattern must
509/// match. This is the exact grammar the previous regex translation implemented,
510/// including its treatment of `[`, `{`, `\`, repeated `*`, and newlines.
511///
512/// A dedicated matcher is deliberate: the battle-tested alternatives change
513/// this grammar. `glob::Pattern` parses `**` as a recursive token (`a**b` fails
514/// to compile, `docs/**/*` matches `docs/foo.md`), reads `[...]` as a character
515/// class, and lets wildcards cross newlines — each of which would silently
516/// widen or narrow an authorization allow-list. `regex` would have to compile a
517/// pattern for every candidate. The two-pointer scan below is allocation-free
518/// (apart from the char vectors) and keeps the allow-list semantics stable.
519fn wildcard_match(pattern: &str, candidate: &str) -> bool {
520    // Preserve the legacy short-circuit: a bare `*` matches even inputs with
521    // embedded newlines, which the wildcard branch below cannot consume.
522    if pattern == "*" {
523        return true;
524    }
525
526    let pattern: Vec<char> = pattern.chars().collect();
527    let candidate: Vec<char> = candidate.chars().collect();
528    let (mut pi, mut ci) = (0usize, 0usize);
529    let mut star = None;
530    let mut star_consumed = 0usize;
531
532    while ci < candidate.len() {
533        if pi < pattern.len() && pattern[pi] == '*' {
534            star = Some(pi);
535            star_consumed = ci;
536            pi += 1;
537        } else if pi < pattern.len() && ((pattern[pi] == '?' && candidate[ci] != '\n') || pattern[pi] == candidate[ci])
538        {
539            pi += 1;
540            ci += 1;
541        } else if let Some(star_pos) = star
542            && candidate[star_consumed] != '\n'
543        {
544            star_consumed += 1;
545            ci = star_consumed;
546            pi = star_pos + 1;
547        } else {
548            return false;
549        }
550    }
551
552    while pi < pattern.len() && pattern[pi] == '*' {
553        pi += 1;
554    }
555    pi == pattern.len()
556}
557
558/// Allow list rules for a provider or default configuration
559#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
560#[derive(Debug, Clone, Deserialize, Serialize, Default)]
561pub struct McpAllowListRules {
562    /// Tool name patterns permitted for the provider
563    #[serde(default)]
564    pub tools: Option<Vec<String>>,
565
566    /// Resource name patterns permitted for the provider
567    #[serde(default)]
568    pub resources: Option<Vec<String>>,
569
570    /// Prompt name patterns permitted for the provider
571    #[serde(default)]
572    pub prompts: Option<Vec<String>>,
573
574    /// Logging channels permitted for the provider
575    #[serde(default)]
576    pub logging: Option<Vec<String>>,
577
578    /// Configuration keys permitted for the provider grouped by category
579    #[serde(default)]
580    pub configuration: Option<BTreeMap<String, Vec<String>>>,
581}
582
583/// Configuration for the MCP server (vtcode acting as an MCP server)
584#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
585#[derive(Debug, Clone, Deserialize, Serialize)]
586pub struct McpServerConfig {
587    /// Enable vtcode's MCP server capability
588    #[serde(default = "default_mcp_server_enabled")]
589    pub enabled: bool,
590
591    /// Bind address for the MCP server
592    #[serde(default = "default_mcp_server_bind")]
593    pub bind_address: String,
594
595    /// Port for the MCP server
596    #[serde(default = "default_mcp_server_port")]
597    pub port: u16,
598
599    /// Server transport type
600    #[serde(default = "default_mcp_server_transport")]
601    pub transport: McpServerTransport,
602
603    /// Server identifier
604    #[serde(default = "default_mcp_server_name")]
605    pub name: String,
606
607    /// Server version
608    #[serde(default = "default_mcp_server_version")]
609    pub version: String,
610
611    /// Tools exposed by the vtcode MCP server
612    #[serde(default)]
613    pub exposed_tools: Vec<String>,
614}
615
616impl Default for McpServerConfig {
617    fn default() -> Self {
618        Self {
619            enabled: default_mcp_server_enabled(),
620            bind_address: default_mcp_server_bind(),
621            port: default_mcp_server_port(),
622            transport: default_mcp_server_transport(),
623            name: default_mcp_server_name(),
624            version: default_mcp_server_version(),
625            exposed_tools: Vec::new(),
626        }
627    }
628}
629
630/// MCP server transport types
631#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
632#[derive(Debug, Clone, Deserialize, Serialize)]
633#[serde(rename_all = "snake_case")]
634#[derive(Default)]
635pub enum McpServerTransport {
636    /// Server Sent Events transport
637    #[default]
638    Sse,
639    /// HTTP transport
640    Http,
641}
642
643/// Default value functions
644fn default_mcp_enabled() -> bool {
645    false
646}
647
648fn default_mcp_ui_mode() -> McpUiMode {
649    McpUiMode::Compact
650}
651
652fn default_max_mcp_events() -> usize {
653    50
654}
655
656fn default_show_provider_names() -> bool {
657    true
658}
659
660fn default_mcp_ui_apps() -> McpUiAppsTier {
661    McpUiAppsTier::Off
662}
663
664fn default_max_concurrent_connections() -> usize {
665    5
666}
667
668fn default_request_timeout_seconds() -> u64 {
669    30
670}
671
672fn default_retry_attempts() -> u32 {
673    3
674}
675
676fn default_experimental_use_rmcp_client() -> bool {
677    true
678}
679
680fn default_allowlist_enforced() -> bool {
681    false
682}
683
684fn default_mcp_server_enabled() -> bool {
685    false
686}
687
688fn default_connection_pooling_enabled() -> bool {
689    true
690}
691
692fn default_tool_cache_capacity() -> usize {
693    100
694}
695
696fn default_connection_timeout_seconds() -> u64 {
697    30
698}
699
700fn default_allow_model_lifecycle_control() -> bool {
701    false
702}
703
704fn default_mcp_server_bind() -> String {
705    "127.0.0.1".into()
706}
707
708fn default_mcp_server_port() -> u16 {
709    3000
710}
711
712fn default_mcp_server_transport() -> McpServerTransport {
713    McpServerTransport::Sse
714}
715
716fn default_mcp_server_name() -> String {
717    "vtcode-mcp-server".into()
718}
719
720fn default_mcp_server_version() -> String {
721    env!("CARGO_PKG_VERSION").into()
722}
723
724fn normalize_mcp_identifier(value: &str) -> String {
725    value
726        .chars()
727        .filter(|ch| ch.is_ascii_alphanumeric())
728        .map(|ch| ch.to_ascii_lowercase())
729        .collect()
730}
731
732fn default_mcp_auth_enabled() -> bool {
733    false
734}
735
736fn default_requests_per_minute() -> u32 {
737    100
738}
739
740fn default_concurrent_requests() -> u32 {
741    10
742}
743
744fn default_schema_validation_enabled() -> bool {
745    true
746}
747
748fn default_path_traversal_protection_enabled() -> bool {
749    true
750}
751
752fn default_max_argument_size() -> u32 {
753    1024 * 1024 // 1MB
754}
755
756fn default_mcp_requirements_enforce() -> bool {
757    false
758}
759
760#[cfg(test)]
761mod tests {
762    use super::*;
763    use crate::constants::mcp as mcp_constants;
764    use std::collections::BTreeMap;
765
766    #[test]
767    fn test_mcp_config_defaults() {
768        let config = McpClientConfig::default();
769        assert!(!config.enabled);
770        assert_eq!(config.ui.mode, McpUiMode::Compact);
771        assert_eq!(config.ui.max_events, 50);
772        assert!(config.ui.show_provider_names);
773        assert!(config.ui.renderers.is_empty());
774        assert_eq!(config.ui.apps, McpUiAppsTier::Off);
775        assert_eq!(config.max_concurrent_connections, 5);
776        assert_eq!(config.request_timeout_seconds, 30);
777        assert_eq!(config.retry_attempts, 3);
778        assert!(!config.lifecycle.allow_model_control);
779        assert!(config.providers.is_empty());
780        assert!(!config.requirements.enforce);
781        assert!(config.requirements.allowed_stdio_commands.is_empty());
782        assert!(config.requirements.allowed_http_endpoints.is_empty());
783        assert!(!config.server.enabled);
784        assert!(!config.allowlist.enforce);
785        assert!(config.allowlist.default.tools.is_none());
786    }
787
788    #[test]
789    fn test_ui_apps_tier_advertises_only_interactive() {
790        assert!(!McpUiAppsTier::Off.advertises_ui_extension());
791        assert!(!McpUiAppsTier::Static.advertises_ui_extension());
792        assert!(McpUiAppsTier::Interactive.advertises_ui_extension());
793    }
794
795    #[test]
796    fn test_ui_apps_tier_serde_names() {
797        for (tier, name) in [
798            (McpUiAppsTier::Off, "off"),
799            (McpUiAppsTier::Static, "static"),
800            (McpUiAppsTier::Interactive, "interactive"),
801        ] {
802            let value = serde_json::to_value(tier).expect("serialize tier");
803            assert_eq!(value, serde_json::Value::String(name.to_string()));
804            let round_trip: McpUiAppsTier = serde_json::from_value(value).expect("deserialize tier");
805            assert_eq!(round_trip, tier);
806            assert_eq!(tier.to_string(), name);
807        }
808        let ui: McpUiConfig = toml::from_str("mode = \"full\"\n").expect("partial ui table");
809        assert_eq!(ui.apps, McpUiAppsTier::Off);
810        let ui: McpUiConfig = toml::from_str("apps = \"static\"\n").expect("apps key");
811        assert_eq!(ui.apps, McpUiAppsTier::Static);
812    }
813
814    #[test]
815    fn test_allowlist_pattern_matching() {
816        let patterns = vec!["get_*".to_string(), "convert_timezone".to_string()];
817        assert!(pattern_matches(&patterns, "get_current_time"));
818        assert!(pattern_matches(&patterns, "convert_timezone"));
819        assert!(!pattern_matches(&patterns, "delete_timezone"));
820    }
821
822    #[test]
823    fn test_allowlist_provider_override() {
824        let mut config = McpAllowListConfig {
825            enforce: true,
826            default: McpAllowListRules {
827                tools: Some(vec!["get_*".to_string()]),
828                ..Default::default()
829            },
830            ..Default::default()
831        };
832
833        let provider_rules = McpAllowListRules {
834            tools: Some(vec!["list_*".to_string()]),
835            ..Default::default()
836        };
837        config.providers.insert("context7".to_string(), provider_rules);
838
839        assert!(config.is_tool_allowed("context7", "list_documents"));
840        assert!(!config.is_tool_allowed("context7", "get_current_time"));
841        assert!(config.is_tool_allowed("other", "get_timezone"));
842        assert!(!config.is_tool_allowed("other", "list_documents"));
843    }
844
845    #[test]
846    fn test_allowlist_configuration_rules() {
847        let mut config = McpAllowListConfig {
848            enforce: true,
849            default: McpAllowListRules {
850                configuration: Some(BTreeMap::from([(
851                    "ui".to_string(),
852                    vec!["mode".to_string(), "max_events".to_string()],
853                )])),
854                ..Default::default()
855            },
856            ..Default::default()
857        };
858
859        let provider_rules = McpAllowListRules {
860            configuration: Some(BTreeMap::from([(
861                "provider".to_string(),
862                vec!["max_concurrent_requests".to_string()],
863            )])),
864            ..Default::default()
865        };
866        config.providers.insert("time".to_string(), provider_rules);
867
868        assert!(config.is_configuration_allowed(None, "ui", "mode"));
869        assert!(!config.is_configuration_allowed(None, "ui", "show_provider_names"));
870        assert!(config.is_configuration_allowed(Some("time"), "provider", "max_concurrent_requests"));
871        assert!(!config.is_configuration_allowed(Some("time"), "provider", "retry_attempts"));
872    }
873
874    #[test]
875    fn test_allowlist_resource_override() {
876        let mut config = McpAllowListConfig {
877            enforce: true,
878            default: McpAllowListRules {
879                resources: Some(vec!["docs/**/*".to_string()]),
880                ..Default::default()
881            },
882            ..Default::default()
883        };
884
885        let provider_rules = McpAllowListRules {
886            resources: Some(vec!["journals/*".to_string()]),
887            ..Default::default()
888        };
889        config.providers.insert("context7".to_string(), provider_rules);
890
891        assert!(config.is_resource_allowed("context7", "journals/2024"));
892        assert!(config.is_resource_allowed("other", "docs/config/config.md"));
893        assert!(config.is_resource_allowed("other", "docs/guides/zed-acp.md"));
894        assert!(!config.is_resource_allowed("other", "journals/2023"));
895    }
896
897    #[test]
898    fn test_allowlist_logging_override() {
899        let mut config = McpAllowListConfig {
900            enforce: true,
901            default: McpAllowListRules {
902                logging: Some(vec!["info".to_string(), "debug".to_string()]),
903                ..Default::default()
904            },
905            ..Default::default()
906        };
907
908        let provider_rules = McpAllowListRules {
909            logging: Some(vec!["audit".to_string()]),
910            ..Default::default()
911        };
912        config.providers.insert("sequential".to_string(), provider_rules);
913
914        assert!(config.is_logging_channel_allowed(Some("sequential"), "audit"));
915        assert!(!config.is_logging_channel_allowed(Some("sequential"), "info"));
916        assert!(config.is_logging_channel_allowed(Some("other"), "info"));
917        assert!(!config.is_logging_channel_allowed(Some("other"), "trace"));
918    }
919
920    #[test]
921    fn test_mcp_ui_renderer_resolution() {
922        let mut config = McpUiConfig::default();
923        config
924            .renderers
925            .insert(mcp_constants::RENDERER_CONTEXT7.to_string(), McpRendererProfile::Context7);
926        config
927            .renderers
928            .insert(mcp_constants::RENDERER_SEQUENTIAL_THINKING.to_string(), McpRendererProfile::SequentialThinking);
929
930        assert_eq!(config.renderer_for_tool("mcp_context7_lookup"), Some(McpRendererProfile::Context7));
931        assert_eq!(config.renderer_for_tool("mcp_context7lookup"), Some(McpRendererProfile::Context7));
932        assert_eq!(
933            config.renderer_for_tool("mcp_sequentialthinking_run"),
934            Some(McpRendererProfile::SequentialThinking)
935        );
936        assert_eq!(
937            config.renderer_for_identifier("sequential-thinking-analyze"),
938            Some(McpRendererProfile::SequentialThinking)
939        );
940        assert_eq!(config.renderer_for_tool("mcp_unknown"), None);
941    }
942}