Skip to main content

vtcode_mcp/client/
mod.rs

1use anyhow::{Context, Result, anyhow, bail};
2use async_trait::async_trait;
3use chrono::Utc;
4use parking_lot::RwLock;
5use rmcp::model::{CallToolResult, ClientCapabilities, InitializeRequestParams, RootsCapabilities};
6use rustc_hash::FxHashMap;
7use serde_json::{Map, Value, json};
8use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11use std::time::Duration;
12use tracing::{info, warn};
13use vtcode_commons::fs::{ensure_dir_exists, write_file_with_context};
14use vtcode_config::mcp::{McpAllowListConfig, McpClientConfig, McpProviderConfig, McpTransportConfig, McpUiAppsTier};
15
16use super::McpSandboxContext;
17use super::{
18    McpClientStatus, McpElicitationHandler, McpPromptDetail, McpPromptInfo, McpProvider, McpResourceData,
19    McpResourceInfo, McpToolExecutor, McpToolInfo, apply_ui_extension_gate, format_tool_markdown,
20    reject_unsupported_ui_apps_tier, sanitize_filename,
21};
22use crate::connection_pool::McpConnectionPool;
23
24mod status;
25
26pub(super) struct McpClientState {
27    providers: FxHashMap<String, Arc<McpProvider>>,
28    allowlist: McpAllowListConfig,
29    tool_provider_index: FxHashMap<String, String>,
30    resource_provider_index: FxHashMap<String, String>,
31    prompt_provider_index: FxHashMap<String, String>,
32}
33
34/// Stable provider order keeps the aggregated catalog (and LLM prompt-cache prefix) deterministic.
35fn providers_sorted_by_name<V: Clone>(providers: &FxHashMap<String, V>) -> Vec<V> {
36    let mut entries: Vec<(&String, &V)> = providers.iter().collect();
37    entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
38    entries.into_iter().map(|(_, provider)| provider.clone()).collect()
39}
40
41pub struct McpClient {
42    pub(super) config: McpClientConfig,
43    pub(super) state: RwLock<McpClientState>,
44    elicitation_handler: Option<Arc<dyn McpElicitationHandler>>,
45    sandbox_context: Option<McpSandboxContext>,
46}
47
48impl McpClient {
49    /// Create a new MCP client from the configuration.
50    pub fn new(config: McpClientConfig) -> Self {
51        Self::with_sandbox_context(config, None)
52    }
53
54    /// Create an MCP client with an optional inherited stdio sandbox context.
55    pub fn with_sandbox_context(config: McpClientConfig, sandbox_context: Option<McpSandboxContext>) -> Self {
56        let allowlist = config.allowlist.clone();
57
58        Self {
59            config,
60            state: RwLock::new(McpClientState {
61                providers: FxHashMap::default(),
62                allowlist,
63                tool_provider_index: FxHashMap::default(),
64                resource_provider_index: FxHashMap::default(),
65                prompt_provider_index: FxHashMap::default(),
66            }),
67            elicitation_handler: None,
68            sandbox_context,
69        }
70    }
71
72    /// Register a handler used to satisfy elicitation requests from providers.
73    pub fn set_elicitation_handler(&mut self, handler: Arc<dyn McpElicitationHandler>) {
74        self.elicitation_handler = Some(handler);
75    }
76
77    /// MCP Apps presentation tier from `[mcp.ui].apps`.
78    ///
79    /// Execution consults this before enriching results: `Off` refuses app UI
80    /// (marking refused URIs under [`crate::types::MCP_APP_SUPPRESSED_KEY`])
81    /// instead of fetching `ui://` resources.
82    #[must_use]
83    pub fn ui_apps_tier(&self) -> McpUiAppsTier {
84        self.config.ui.apps
85    }
86
87    /// Resolve `(connection timeout, tool timeout)` in seconds.
88    ///
89    /// `connection_timeout_seconds` bounds the connect-and-handshake phase and
90    /// `request_timeout_seconds` the per-tool call budget. They are distinct on
91    /// purpose: a provider that never finishes connecting must fail on the short
92    /// connection key, not consume the tool budget. Both clamp to at least one
93    /// second so a `0` cannot produce an instantly-failing deadline.
94    fn pool_timeouts(&self) -> (u64, u64) {
95        (self.config.connection_timeout_seconds.max(1), self.config.request_timeout_seconds.max(1))
96    }
97
98    /// Establish connections to all configured providers and complete the
99    /// MCP handshake.
100    pub async fn initialize(&mut self) -> Result<()> {
101        if !self.config.enabled {
102            info!("MCP client is disabled in configuration");
103            return Ok(());
104        }
105        reject_unsupported_ui_apps_tier(&self.config.ui)?;
106
107        info!("Initializing MCP client with {} configured providers", self.config.providers.len());
108
109        let max_connections = self.config.max_concurrent_connections.max(1);
110        let (connection_timeout_seconds, tool_timeout_seconds) = self.pool_timeouts();
111        let pool = McpConnectionPool::new(max_connections, connection_timeout_seconds);
112        let tool_timeout = Some(Duration::from_secs(tool_timeout_seconds));
113        let allowlist_snapshot = self.state.read().allowlist.clone();
114
115        let provider_configs: Vec<McpProviderConfig> =
116            self.config.providers.iter().filter(|c| c.enabled).cloned().collect();
117
118        let results = pool
119            .initialize_providers_parallel(
120                provider_configs,
121                self.elicitation_handler.clone(),
122                self.sandbox_context.clone(),
123                tool_timeout,
124                &allowlist_snapshot,
125                self.config.ui.apps.advertises_ui_extension(),
126            )
127            .await
128            .map_err(|e| anyhow::anyhow!("MCP connection pool initialization failed: {e}"))?;
129
130        let mut initialized = FxHashMap::default();
131        for (name, provider) in results {
132            drop(initialized.insert(name, provider));
133        }
134
135        self.state.write().providers = initialized;
136        info!("MCP client initialization complete. Active providers: {}", self.state.read().providers.len());
137
138        Ok(())
139    }
140
141    /// Validate tool arguments based on security configuration
142    fn validate_tool_arguments(&self, _tool_name: &str, args: &Value) -> Result<()> {
143        // Check argument size
144        if self.config.security.validation.max_argument_size > 0 {
145            let args_size = serde_json::to_string(args).map_or(0, |s| u32::try_from(s.len()).unwrap_or(u32::MAX));
146
147            if args_size > self.config.security.validation.max_argument_size {
148                return Err(anyhow::anyhow!(
149                    "Tool arguments exceed maximum size of {} bytes",
150                    self.config.security.validation.max_argument_size
151                ));
152            }
153        }
154
155        // Check for path traversal in file-related arguments
156        if self.config.security.validation.path_traversal_protection
157            && let Some(path) = args.get("path").and_then(|v| v.as_str())
158            && (path.contains("../") || path.starts_with("../") || path.contains("..\\") || path.starts_with("..\\"))
159        {
160            return Err(anyhow::anyhow!("Path traversal detected in arguments"));
161        }
162
163        Ok(())
164    }
165
166    /// Execute a tool call after validating arguments.
167    ///
168    /// Public-facing version that takes ownership of `args` for compatibility
169    /// with existing callers. Delegates to the reference-taking implementation
170    /// to avoid unnecessary cloning when the caller already has a reference.
171    async fn execute_tool_with_validation(&self, tool_name: &str, args: Value) -> Result<Value> {
172        self.execute_tool_with_validation_ref(tool_name, &args).await
173    }
174
175    // Internal reference-taking implementation to avoid cloning when not necessary.
176    async fn execute_tool_with_validation_ref(&self, tool_name: &str, args: &Value) -> Result<Value> {
177        if !self.config.enabled {
178            return Err(anyhow!("MCP support is disabled in the current configuration"));
179        }
180
181        self.validate_tool_arguments(tool_name, args)?;
182
183        let provider = self.resolve_provider_for_tool(tool_name).await?;
184        let allowlist_snapshot = self.state.read().allowlist.clone();
185        // Defense in depth: listing hides app-only tools, but a model could
186        // still name one directly. Unknown names fall through to the
187        // provider's own error below.
188        let tools = provider
189            .cached_tools_or_refresh_shared(&allowlist_snapshot, self.tool_timeout())
190            .await?;
191        if let Some(tool) = tools.iter().find(|tool| tool.name == tool_name)
192            && !tool.visibility.model
193        {
194            bail!("MCP tool '{tool_name}' is not available to the model (app-only visibility)");
195        }
196        let result = provider
197            .call_tool(tool_name, args, self.tool_timeout(), &allowlist_snapshot)
198            .await?;
199
200        Self::format_tool_result(&provider.name, tool_name, result)
201    }
202
203    /// Refresh the internal allow list at runtime.
204    pub fn update_allowlist(&self, allowlist: McpAllowListConfig) {
205        let providers: Vec<Arc<McpProvider>> = {
206            let mut state = self.state.write();
207            state.allowlist = allowlist;
208            state.tool_provider_index.clear();
209            state.resource_provider_index.clear();
210            state.prompt_provider_index.clear();
211            state.providers.values().cloned().collect()
212        };
213
214        for provider in providers {
215            provider.invalidate_caches();
216        }
217    }
218
219    /// Current allow list snapshot.
220    pub fn current_allowlist(&self) -> McpAllowListConfig {
221        self.state.read().allowlist.clone()
222    }
223
224    /// Return the provider name serving the given tool if previously cached.
225    pub fn provider_for_tool(&self, tool_name: &str) -> Option<String> {
226        self.state.read().tool_provider_index.get(tool_name).cloned()
227    }
228
229    /// Return the provider responsible for the given resource URI if known.
230    pub fn provider_for_resource(&self, uri: &str) -> Option<String> {
231        self.state.read().resource_provider_index.get(uri).cloned()
232    }
233
234    /// Return the provider that exposes the given prompt if known.
235    pub fn provider_for_prompt(&self, prompt_name: &str) -> Option<String> {
236        self.state.read().prompt_provider_index.get(prompt_name).cloned()
237    }
238
239    /// Execute a tool call on the appropriate provider.
240    pub async fn execute_tool(&self, tool_name: &str, args: Value) -> Result<Value> {
241        self.execute_tool_with_validation(tool_name, args).await
242    }
243
244    /// List all model-visible tools from all active providers.
245    ///
246    /// Tools without model visibility (SEP-1865 `visibility: ["app"]`) are
247    /// hidden here; provider caches keep them for future app-side callers.
248    pub async fn list_tools(&self) -> Result<Vec<McpToolInfo>> {
249        Ok(self
250            .collect_tools(false)
251            .await?
252            .into_iter()
253            .filter(|tool| tool.visibility.model)
254            .collect())
255    }
256
257    /// List all resources exposed by connected MCP providers.
258    pub async fn list_resources(&self) -> Result<Vec<McpResourceInfo>> {
259        self.collect_resources(false).await
260    }
261
262    /// Force refresh and list resources from providers.
263    pub async fn refresh_resources(&self) -> Result<Vec<McpResourceInfo>> {
264        self.collect_resources(true).await
265    }
266
267    /// List all prompts advertised by connected MCP providers.
268    pub async fn list_prompts(&self) -> Result<Vec<McpPromptInfo>> {
269        self.collect_prompts(false).await
270    }
271
272    /// Force refresh and list prompts from providers.
273    pub async fn refresh_prompts(&self) -> Result<Vec<McpPromptInfo>> {
274        self.collect_prompts(true).await
275    }
276
277    /// Read a single resource from its originating provider.
278    pub async fn read_resource(&self, uri: &str) -> Result<McpResourceData> {
279        let provider = self.resolve_provider_for_resource(uri).await?;
280        let provider_name = provider.name.clone();
281        let allowlist_snapshot = self.state.read().allowlist.clone();
282        let data = provider.read_resource(uri, self.request_timeout(), &allowlist_snapshot).await?;
283        drop(self.state.write().resource_provider_index.insert(uri.into(), provider_name));
284        Ok(data)
285    }
286
287    /// Retrieve a rendered prompt from its originating provider.
288    pub async fn get_prompt(
289        &self,
290        prompt_name: &str,
291        arguments: Option<hashbrown::HashMap<String, String>>,
292    ) -> Result<McpPromptDetail> {
293        let provider = self.resolve_provider_for_prompt(prompt_name).await?;
294        let provider_name = provider.name.clone();
295        let allowlist_snapshot = self.state.read().allowlist.clone();
296        let prompt = provider
297            .get_prompt(prompt_name, arguments.unwrap_or_default(), self.request_timeout(), &allowlist_snapshot)
298            .await?;
299        drop(
300            self.state
301                .write()
302                .prompt_provider_index
303                .insert(prompt_name.into(), provider_name),
304        );
305        Ok(prompt)
306    }
307
308    /// Shutdown all active provider connections.
309    pub async fn shutdown(&self) -> Result<()> {
310        let providers: Vec<Arc<McpProvider>> = {
311            let mut state = self.state.write();
312            let values: Vec<_> = state.providers.values().cloned().collect();
313            state.providers.clear();
314            state.tool_provider_index.clear();
315            state.resource_provider_index.clear();
316            state.prompt_provider_index.clear();
317            values
318        };
319
320        if providers.is_empty() {
321            info!("No active MCP connections to shutdown");
322            return Ok(());
323        }
324
325        info!("Shutting down {} MCP providers", providers.len());
326        for provider in providers {
327            if let Err(err) = provider.shutdown().await {
328                warn!("Provider '{}' shutdown returned error: {err}", provider.name);
329            }
330        }
331        Ok(())
332    }
333
334    async fn collect_tools(&self, force_refresh: bool) -> Result<Vec<McpToolInfo>> {
335        // Collect provider references in one pass
336        let (providers, allowlist) = {
337            let state = self.state.read();
338            (providers_sorted_by_name(&state.providers), state.allowlist.clone())
339        };
340
341        if providers.is_empty() {
342            return Ok(Vec::new());
343        }
344
345        let timeout = self.tool_timeout();
346        let mut all_tools = Vec::with_capacity(128);
347        let mut index_updates: FxHashMap<String, String> = FxHashMap::with_capacity_and_hasher(128, Default::default());
348
349        for provider in providers {
350            let provider_name = provider.name.clone();
351            let tools = if force_refresh {
352                provider.refresh_tools(&allowlist, timeout).await
353            } else {
354                provider.list_tools(&allowlist, timeout).await
355            };
356
357            match tools {
358                Ok(tools) => {
359                    for tool in &tools {
360                        let _ = index_updates.entry(tool.name.clone()).or_insert_with(|| provider_name.clone());
361                    }
362                    all_tools.extend(tools);
363                }
364                Err(err) => {
365                    warn!("Failed to list tools for provider '{}': {err}", provider_name);
366                }
367            }
368        }
369
370        if !index_updates.is_empty() || force_refresh {
371            let mut state = self.state.write();
372            if index_updates.is_empty() {
373                state.tool_provider_index.clear();
374            } else {
375                state.tool_provider_index = index_updates;
376            }
377        }
378
379        Ok(all_tools)
380    }
381
382    async fn collect_resources(&self, force_refresh: bool) -> Result<Vec<McpResourceInfo>> {
383        // Collect provider references in one pass
384        let (providers, allowlist) = {
385            let state = self.state.read();
386            (providers_sorted_by_name(&state.providers), state.allowlist.clone())
387        };
388
389        if providers.is_empty() {
390            self.state.write().resource_provider_index.clear();
391            return Ok(Vec::new());
392        }
393
394        let timeout = self.request_timeout();
395        let mut all_resources = Vec::with_capacity(64);
396
397        for provider in providers {
398            let resources = if force_refresh {
399                provider.refresh_resources(&allowlist, timeout).await
400            } else {
401                provider.list_resources(&allowlist, timeout).await
402            };
403
404            match resources {
405                Ok(resources) => {
406                    all_resources.extend(resources);
407                }
408                Err(err) => {
409                    warn!("Failed to list resources for provider '{}': {err}", provider.name);
410                }
411            }
412        }
413
414        let mut state = self.state.write();
415        let index = &mut state.resource_provider_index;
416        index.clear();
417        for resource in &all_resources {
418            let _ = index.entry(resource.uri.clone()).or_insert_with(|| resource.provider.clone());
419        }
420
421        Ok(all_resources)
422    }
423
424    async fn collect_prompts(&self, force_refresh: bool) -> Result<Vec<McpPromptInfo>> {
425        // Collect provider references in one pass
426        let (providers, allowlist) = {
427            let state = self.state.read();
428            (providers_sorted_by_name(&state.providers), state.allowlist.clone())
429        };
430
431        if providers.is_empty() {
432            self.state.write().prompt_provider_index.clear();
433            return Ok(Vec::new());
434        }
435
436        let timeout = self.request_timeout();
437        let mut all_prompts = Vec::with_capacity(32);
438
439        for provider in providers {
440            let prompts = if force_refresh {
441                provider.refresh_prompts(&allowlist, timeout).await
442            } else {
443                provider.list_prompts(&allowlist, timeout).await
444            };
445
446            match prompts {
447                Ok(prompts) => {
448                    all_prompts.extend(prompts);
449                }
450                Err(err) => {
451                    warn!("Failed to list prompts for provider '{}': {err}", provider.name);
452                }
453            }
454        }
455
456        let mut state = self.state.write();
457        let index = &mut state.prompt_provider_index;
458        index.clear();
459        for prompt in &all_prompts {
460            let _ = index.entry(prompt.name.clone()).or_insert_with(|| prompt.provider.clone());
461        }
462
463        Ok(all_prompts)
464    }
465
466    async fn resolve_provider_for_tool(&self, tool_name: &str) -> Result<Arc<McpProvider>> {
467        if !self.config.enabled {
468            return Err(anyhow!("MCP support is disabled in the current configuration"));
469        }
470
471        if let Some(provider) = self.provider_for_tool(tool_name)
472            && let Some(found) = self.state.read().providers.get(&provider)
473        {
474            return Ok(found.clone());
475        }
476
477        let (allowlist, providers) = {
478            let state = self.state.read();
479            (state.allowlist.clone(), providers_sorted_by_name(&state.providers))
480        };
481        let timeout = self.tool_timeout();
482
483        if providers.is_empty() {
484            if self.config.providers.is_empty() {
485                return Err(anyhow!(
486                    "No MCP providers are configured. Use `vtcode mcp add` or update vtcode.toml to register one."
487                ));
488            }
489
490            return Err(anyhow!(
491                "No MCP providers are currently connected. Ensure MCP initialization completed successfully."
492            ));
493        }
494
495        for provider in providers {
496            match provider.has_tool(tool_name, &allowlist, timeout).await {
497                Ok(true) => {
498                    drop(
499                        self.state
500                            .write()
501                            .tool_provider_index
502                            .insert(tool_name.into(), provider.name.clone()),
503                    );
504                    return Ok(provider);
505                }
506                Ok(false) => continue,
507                Err(err) => {
508                    warn!("Error checking tool '{}' on provider '{}': {err}", tool_name, provider.name);
509                }
510            }
511        }
512
513        match self.collect_tools(true).await {
514            Ok(_) => {
515                if let Some(provider) = self.provider_for_tool(tool_name)
516                    && let Some(found) = self.state.read().providers.get(&provider)
517                {
518                    return Ok(found.clone());
519                }
520            }
521            Err(err) => {
522                warn!("Failed to refresh MCP tool caches while resolving '{}': {err}", tool_name);
523            }
524        }
525
526        Err(anyhow!(
527            "Tool '{tool_name}' not found on any MCP provider.\n\n\
528            To use this tool:\n\
529            1. Install the MCP server: `uv tool install mcp-server-{tool_name}`\n\
530            2. Add to vtcode.toml:\n   \
531               [[mcp.providers]]\n   \
532               name = \"{tool_name}\"\n   \
533               command = \"uvx\"\n   \
534               args = [\"mcp-server-{tool_name}\"]\n\
535            3. Restart VT Code\n\n\
536            Or use the built-in alternative if available (e.g., web_fetch instead of mcp_fetch)"
537        ))
538    }
539
540    async fn resolve_provider_for_resource(&self, uri: &str) -> Result<Arc<McpProvider>> {
541        if let Some(provider) = self.provider_for_resource(uri)
542            && let Some(found) = self.state.read().providers.get(&provider)
543        {
544            return Ok(found.clone());
545        }
546
547        let (allowlist, providers) = {
548            let state = self.state.read();
549            (state.allowlist.clone(), providers_sorted_by_name(&state.providers))
550        };
551        let timeout = self.request_timeout();
552
553        for provider in providers {
554            match provider.has_resource(uri, &allowlist, timeout).await {
555                Ok(true) => {
556                    drop(
557                        self.state
558                            .write()
559                            .resource_provider_index
560                            .insert(uri.into(), provider.name.clone()),
561                    );
562                    return Ok(provider);
563                }
564                Ok(false) => continue,
565                Err(err) => {
566                    warn!("Error checking resource '{}' on provider '{}': {err}", uri, provider.name);
567                }
568            }
569        }
570
571        Err(anyhow!("Resource '{uri}' not found on any MCP provider"))
572    }
573
574    async fn resolve_provider_for_prompt(&self, prompt_name: &str) -> Result<Arc<McpProvider>> {
575        if let Some(provider) = self.provider_for_prompt(prompt_name)
576            && let Some(found) = self.state.read().providers.get(&provider)
577        {
578            return Ok(found.clone());
579        }
580
581        let (allowlist, providers) = {
582            let state = self.state.read();
583            (state.allowlist.clone(), providers_sorted_by_name(&state.providers))
584        };
585        let timeout = self.request_timeout();
586
587        for provider in providers {
588            match provider.has_prompt(prompt_name, &allowlist, timeout).await {
589                Ok(true) => {
590                    drop(
591                        self.state
592                            .write()
593                            .prompt_provider_index
594                            .insert(prompt_name.into(), provider.name.clone()),
595                    );
596                    return Ok(provider);
597                }
598                Ok(false) => continue,
599                Err(err) => {
600                    warn!("Error checking prompt '{}' on provider '{}': {err}", prompt_name, provider.name);
601                }
602            }
603        }
604
605        Err(anyhow!("Prompt '{prompt_name}' not found on any MCP provider"))
606    }
607
608    pub(super) fn record_tool_provider(&self, provider: &str, tools: &[McpToolInfo]) {
609        let mut state = self.state.write();
610        let index = &mut state.tool_provider_index;
611        for tool in tools {
612            let _ = index
613                .entry(tool.name.clone())
614                .and_modify(|owner| {
615                    if provider < owner.as_str() {
616                        *owner = provider.to_string();
617                    }
618                })
619                .or_insert_with(|| provider.to_string());
620        }
621    }
622
623    async fn connect_and_initialize_provider(
624        &self,
625        provider_config: &McpProviderConfig,
626        allowlist_snapshot: &McpAllowListConfig,
627        tool_timeout: Option<Duration>,
628    ) -> Result<McpProvider> {
629        let total_attempts = self.provider_retry_attempts();
630        let mut last_error: Option<anyhow::Error> = None;
631
632        for attempt_idx in 0..total_attempts {
633            let attempt_number = attempt_idx + 1;
634            match self
635                .connect_and_initialize_provider_once(provider_config, allowlist_snapshot, tool_timeout)
636                .await
637            {
638                Ok(provider) => return Ok(provider),
639                Err(err) => {
640                    if attempt_number == total_attempts {
641                        return Err(err);
642                    }
643
644                    let retries_remaining = total_attempts - attempt_number;
645                    warn!(
646                        provider = provider_config.name.as_str(),
647                        attempt = attempt_number,
648                        retries_remaining,
649                        error = %err,
650                        "MCP provider initialization failed; retrying"
651                    );
652                    last_error = Some(err);
653                    tokio::time::sleep(Self::provider_retry_delay(attempt_idx)).await;
654                }
655            }
656        }
657
658        Err(last_error.unwrap_or_else(|| anyhow!("Failed to initialize MCP provider '{}'", provider_config.name)))
659    }
660
661    async fn connect_and_initialize_provider_once(
662        &self,
663        provider_config: &McpProviderConfig,
664        allowlist_snapshot: &McpAllowListConfig,
665        tool_timeout: Option<Duration>,
666    ) -> Result<McpProvider> {
667        let provider = McpProvider::connect(
668            provider_config.clone(),
669            self.elicitation_handler.clone(),
670            self.sandbox_context.clone(),
671            self.config.ui.apps.advertises_ui_extension(),
672        )
673        .await
674        .with_context(|| format!("Failed to connect to MCP provider '{}'", provider_config.name))?;
675        let provider_startup_timeout = self.resolve_startup_timeout(provider_config);
676        provider
677            .initialize(self.build_initialize_params(), provider_startup_timeout, tool_timeout, allowlist_snapshot)
678            .await
679            .with_context(|| format!("Failed to initialize MCP provider '{}'", provider_config.name))?;
680        Ok(provider)
681    }
682
683    fn startup_timeout(&self) -> Option<Duration> {
684        match self.config.startup_timeout_seconds {
685            Some(0) => None,
686            Some(value) => Some(Duration::from_secs(value)),
687            None => self.request_timeout(),
688        }
689    }
690
691    pub(super) fn requirement_mismatch_reason(&self, provider_config: &McpProviderConfig) -> Option<String> {
692        let requirements = &self.config.requirements;
693        if !requirements.enforce {
694            return None;
695        }
696
697        match &provider_config.transport {
698            McpTransportConfig::Stdio(stdio) => {
699                if requirements
700                    .allowed_stdio_commands
701                    .iter()
702                    .any(|allowed| allowed == &stdio.command)
703                {
704                    None
705                } else {
706                    Some(format!("stdio command '{}' is not allowlisted", stdio.command))
707                }
708            }
709            McpTransportConfig::Http(http) => {
710                if requirements
711                    .allowed_http_endpoints
712                    .iter()
713                    .any(|allowed| allowed == &http.endpoint)
714                {
715                    None
716                } else {
717                    Some(format!("HTTP endpoint '{}' is not allowlisted", http.endpoint))
718                }
719            }
720        }
721    }
722
723    fn resolve_startup_timeout(&self, provider_config: &McpProviderConfig) -> Option<Duration> {
724        if let Some(timeout_ms) = provider_config.startup_timeout_ms {
725            if timeout_ms == 0 {
726                None
727            } else {
728                Some(Duration::from_millis(timeout_ms))
729            }
730        } else {
731            self.startup_timeout()
732        }
733    }
734
735    fn provider_retry_attempts(&self) -> usize {
736        self.config.retry_attempts.try_into().unwrap_or(usize::MAX).saturating_add(1)
737    }
738
739    #[must_use]
740    fn provider_retry_delay(attempt_idx: usize) -> Duration {
741        // Canonical 250ms-to-5s curve with the standard jitter: concurrent
742        // provider reconnects must not retry in lockstep.
743        let attempt = u32::try_from(attempt_idx).unwrap_or(u32::MAX);
744        vtcode_commons::retry::RetryPolicy::from_retries(
745            u32::MAX,
746            Duration::from_millis(250),
747            Duration::from_secs(5),
748            2.0,
749        )
750        .with_jitter(vtcode_commons::retry::RetryPolicy::DEFAULT_JITTER)
751        .delay_for_attempt(attempt)
752    }
753
754    pub(super) fn tool_timeout(&self) -> Option<Duration> {
755        match self.config.tool_timeout_seconds {
756            Some(0) => None,
757            Some(value) => Some(Duration::from_secs(value)),
758            None => self.request_timeout(),
759        }
760    }
761
762    fn request_timeout(&self) -> Option<Duration> {
763        if self.config.request_timeout_seconds == 0 {
764            None
765        } else {
766            Some(Duration::from_secs(self.config.request_timeout_seconds))
767        }
768    }
769
770    fn build_initialize_params(&self) -> InitializeRequestParams {
771        let mut capabilities = ClientCapabilities::default();
772        {
773            let mut roots_cap = RootsCapabilities::default();
774            roots_cap.list_changed = Some(true);
775            capabilities.roots = Some(roots_cap);
776        }
777
778        if self.elicitation_handler.is_some() {
779            // Elicitation is now a first-class capability in rmcp
780            capabilities.elicitation = Some(
781                rmcp::model::ElicitationCapability::new()
782                    .with_form(rmcp::model::FormElicitationCapability::new().with_schema_validation(true)),
783            );
784        }
785
786        apply_ui_extension_gate(&mut capabilities, self.config.ui.apps.advertises_ui_extension());
787
788        InitializeRequestParams::new(capabilities, super::utils::build_client_implementation())
789            .with_protocol_version(super::rmcp_client::latest_protocol_version())
790    }
791
792    pub(super) fn normalize_arguments(args: &Value) -> Map<String, Value> {
793        match args {
794            Value::Null => Map::new(),
795            Value::Object(map) => map.clone(),
796            other => {
797                let mut map = Map::new();
798                drop(map.insert("value".to_owned(), other.clone()));
799                map
800            }
801        }
802    }
803
804    fn format_tool_result(provider_name: &str, tool_name: &str, result: CallToolResult) -> Result<Value> {
805        if result.is_error == Some(true) {
806            let message = result
807                .content
808                .iter()
809                .filter_map(|block| block.as_text())
810                .map(|block| block.text.as_str())
811                .find(|text| !text.trim().is_empty())
812                .unwrap_or("Unknown MCP tool error");
813            return Err(anyhow!("MCP tool '{tool_name}' on provider '{provider_name}' reported an error: {message}"));
814        }
815
816        let mut payload = Map::new();
817        drop(payload.insert("provider".into(), Value::String(provider_name.to_string())));
818        drop(payload.insert("tool".into(), Value::String(tool_name.to_string())));
819
820        if !result.content.is_empty() {
821            let mut content = serde_json::to_value(result.content)?;
822            if let Some(blocks) = content.as_array_mut() {
823                for block in blocks {
824                    if let Some(block) = block.as_object_mut() {
825                        // Strip only protocol envelopes, never application data or text.
826                        drop(block.remove("_meta"));
827                        if block.get("type").and_then(Value::as_str) == Some("resource")
828                            && let Some(resource) = block.get_mut("resource").and_then(Value::as_object_mut)
829                        {
830                            drop(resource.remove("_meta"));
831                        }
832                    }
833                }
834            }
835            drop(payload.insert("content".into(), content));
836        }
837        if let Some(structured_content) = result.structured_content {
838            drop(payload.insert("structuredContent".into(), structured_content));
839        }
840
841        Ok(Value::Object(payload))
842    }
843}
844
845#[async_trait]
846impl McpToolExecutor for McpClient {
847    async fn execute_mcp_tool(&self, tool_name: &str, args: &Value) -> Result<Value> {
848        self.execute_tool_with_validation_ref(tool_name, args).await
849    }
850
851    async fn list_mcp_tools(&self) -> Result<Vec<McpToolInfo>> {
852        self.list_tools().await
853    }
854
855    async fn has_mcp_tool(&self, tool_name: &str) -> Result<bool> {
856        if !self.config.enabled {
857            return Ok(false);
858        }
859
860        if self.provider_for_tool(tool_name).is_some() {
861            return Ok(true);
862        }
863
864        if self.state.read().providers.is_empty() {
865            if self.config.providers.is_empty() {
866                return Ok(false);
867            }
868
869            bail!("No MCP providers are currently connected. Ensure MCP initialization completed successfully.");
870        }
871
872        let tools = self.collect_tools(false).await?;
873        Ok(tools.iter().any(|tool| tool.name == tool_name))
874    }
875
876    fn get_status(&self) -> McpClientStatus {
877        self.get_status()
878    }
879}
880
881#[cfg(test)]
882mod tests;