Skip to main content

vtcode_mcp/
provider.rs

1use anyhow::{Context, Result, anyhow};
2use arc_swap::ArcSwap;
3use hashbrown::HashMap;
4use rmcp::model::{
5    CallToolRequestParams, CallToolResult, GetPromptRequestParams, InitializeRequestParams, Prompt,
6    ReadResourceRequestParams, Resource, ServerPeerInfo, Tool,
7};
8use rmcp::service::ClientLifecycleMode;
9use serde_json::{Map, Value};
10use std::ffi::OsString;
11use std::path::PathBuf;
12use std::sync::Arc;
13use std::time::Duration;
14use tokio::sync::{Mutex, Semaphore};
15use tracing::{Instrument, Span, warn};
16use url::Url;
17
18use super::rmcp_client::{auto_lifecycle_mode, latest_protocol_version};
19use super::{LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS};
20
21use vtcode_config::auth::McpOAuthService;
22use vtcode_config::mcp::{McpAllowListConfig, McpHttpHandshakeMode, McpProviderConfig, McpTransportConfig};
23use vtcode_utility_tool_specs::parse_mcp_tool;
24
25use super::sandbox_context::resolve_provider_sandbox_context;
26use super::{McpClient, McpSandboxContext, RmcpClient};
27use super::{
28    McpElicitationHandler, McpPromptDetail, McpPromptInfo, McpResourceData, McpResourceInfo, McpToolInfo,
29    TIMEZONE_ARGUMENT, apply_ui_extension_gate, build_headers, ensure_timezone_argument, schema_requires_field,
30};
31
32pub struct McpProvider {
33    pub(super) name: String,
34    #[expect(
35        dead_code,
36        reason = "Intentional compatibility, platform, test, or API-shape suppression."
37    )]
38    protocol_version: String,
39    client: ArcSwap<RmcpClient>,
40    /// Stored config so we can reconnect after disconnection.
41    config: McpProviderConfig,
42    /// Stored elicitation handler for reconnection.
43    elicitation_handler: Option<Arc<dyn McpElicitationHandler>>,
44    /// Whether to advertise the MCP Apps UI extension, retained for reconnects.
45    advertise_ui_apps: bool,
46    /// Sandbox inherited by stdio launches and reconnects.
47    sandbox_context: Option<McpSandboxContext>,
48    pub(crate) semaphore: Arc<Semaphore>,
49    caches: Mutex<ProviderCaches>,
50    initialize_result: Mutex<Option<ServerPeerInfo>>,
51}
52
53#[derive(Default)]
54struct ProviderCaches {
55    tools: Option<Arc<Vec<McpToolInfo>>>,
56    resources: Option<Arc<Vec<McpResourceInfo>>>,
57    prompts: Option<Arc<Vec<McpPromptInfo>>>,
58}
59
60impl McpProvider {
61    pub(super) async fn connect(
62        config: McpProviderConfig,
63        elicitation_handler: Option<Arc<dyn McpElicitationHandler>>,
64        sandbox_context: Option<McpSandboxContext>,
65        advertise_ui_apps: bool,
66    ) -> Result<Self> {
67        if config.name.trim().is_empty() {
68            return Err(anyhow!("MCP provider name cannot be empty"));
69        }
70
71        let sandbox_context = resolve_provider_sandbox_context(sandbox_context, config.sandbox.as_ref())
72            .with_context(|| format!("MCP provider '{}' has unsatisfiable sandbox overrides", config.name))?;
73
74        let max_requests = std::cmp::max(1, config.max_concurrent_requests);
75
76        let (client, protocol_version) = match &config.transport {
77            McpTransportConfig::Stdio(stdio) => {
78                let program = OsString::from(&stdio.command);
79                let args: Vec<OsString> = stdio.args.iter().map(OsString::from).collect();
80                let working_dir = stdio.working_directory.as_ref().map(PathBuf::from);
81                let env: HashMap<OsString, OsString> = config
82                    .env
83                    .iter()
84                    .map(|(key, value)| (OsString::from(key), OsString::from(value)))
85                    .collect();
86                let client = RmcpClient::new_stdio_client(
87                    config.name.clone(),
88                    program,
89                    args,
90                    working_dir,
91                    Some(env),
92                    elicitation_handler.clone(),
93                    sandbox_context.clone(),
94                )
95                .await?;
96                (client, LATEST_PROTOCOL_VERSION.to_string())
97            }
98            McpTransportConfig::Http(http) => {
99                if !SUPPORTED_PROTOCOL_VERSIONS
100                    .iter()
101                    .any(|supported| supported == &http.protocol_version)
102                {
103                    return Err(anyhow!(
104                        "MCP HTTP provider '{}' requested unsupported protocol version '{}'",
105                        config.name,
106                        http.protocol_version
107                    ));
108                }
109
110                let bearer_token = if let Some(oauth) = http.oauth.as_ref() {
111                    McpOAuthService::new()
112                        .resolve_access_token_for_resource(&config.name, oauth, &http.endpoint)
113                        .await?
114                        .ok_or_else(|| {
115                            anyhow!(
116                                "MCP HTTP provider '{}' requires OAuth login. Run `vtcode mcp login {}`.",
117                                config.name,
118                                config.name
119                            )
120                        })
121                        .map(Some)?
122                } else {
123                    match http.api_key_env.as_ref() {
124                        Some(var) => Some(
125                            std::env::var(var)
126                                .with_context(|| format!("Missing MCP API key environment variable: {var}"))?,
127                        ),
128                        None => None,
129                    }
130                };
131
132                let headers = build_headers(&http.http_headers, &http.env_http_headers);
133                let client = RmcpClient::new_streamable_http_client(
134                    config.name.clone(),
135                    &http.endpoint,
136                    bearer_token,
137                    headers,
138                    elicitation_handler.clone(),
139                )
140                .await?;
141                (client, http.protocol_version.clone())
142            }
143        };
144
145        Ok(Self {
146            name: config.name.clone(),
147            protocol_version,
148            client: ArcSwap::from_pointee(client),
149            config,
150            elicitation_handler,
151            advertise_ui_apps,
152            sandbox_context,
153            semaphore: Arc::new(Semaphore::new(max_requests)),
154            caches: Mutex::new(ProviderCaches::default()),
155            initialize_result: Mutex::new(None),
156        })
157    }
158
159    pub(super) fn invalidate_caches(&self) {
160        if let Ok(mut caches) = self.caches.try_lock() {
161            caches.tools = None;
162            caches.resources = None;
163            caches.prompts = None;
164        }
165    }
166
167    pub(super) async fn initialize(
168        &self,
169        params: InitializeRequestParams,
170        startup_timeout: Option<Duration>,
171        _tool_timeout: Option<Duration>,
172        _allowlist: &McpAllowListConfig,
173    ) -> Result<()> {
174        let client = self.client.load_full();
175        let result = client.initialize(params, startup_timeout, self.handshake_lifecycle()).await?;
176
177        let protocol_version_str = result.protocol_version.to_string();
178        if !SUPPORTED_PROTOCOL_VERSIONS
179            .iter()
180            .any(|supported| *supported == protocol_version_str)
181        {
182            return Err(anyhow!(
183                "MCP server for '{}' negotiated unsupported protocol version '{}'",
184                self.name,
185                protocol_version_str
186            ));
187        }
188
189        *self.initialize_result.lock().await = Some(result);
190        Ok(())
191    }
192
193    /// Lifecycle mode for the rmcp handshake, derived from the transport.
194    ///
195    /// stdio always probes `server/discover` first (`Auto`) since a local
196    /// child process answers immediately either way. HTTP defaults to the
197    /// direct legacy handshake so legacy-only servers (e.g. DeepWiki) are not
198    /// penalized by the discover-timeout fallback; opt in to `Auto` per
199    /// provider via `handshake = "auto"` for modern servers.
200    fn handshake_lifecycle(&self) -> ClientLifecycleMode {
201        match &self.config.transport {
202            McpTransportConfig::Stdio(_) => auto_lifecycle_mode(),
203            McpTransportConfig::Http(http) => match http.handshake {
204                McpHttpHandshakeMode::Legacy => ClientLifecycleMode::Initialize,
205                McpHttpHandshakeMode::Auto => auto_lifecycle_mode(),
206            },
207        }
208    }
209
210    /// Protocol version negotiated during the last successful handshake, if any.
211    pub(super) async fn negotiated_protocol_version(&self) -> Option<String> {
212        self.initialize_result
213            .lock()
214            .await
215            .as_ref()
216            .map(|info| info.protocol_version.to_string())
217    }
218
219    pub(super) async fn list_tools(
220        &self,
221        allowlist: &McpAllowListConfig,
222        timeout: Option<Duration>,
223    ) -> Result<Vec<McpToolInfo>> {
224        Ok(self.list_tools_shared(allowlist, timeout).await?.as_ref().clone())
225    }
226
227    async fn list_tools_shared(
228        &self,
229        allowlist: &McpAllowListConfig,
230        timeout: Option<Duration>,
231    ) -> Result<Arc<Vec<McpToolInfo>>> {
232        let mut caches = self.caches.lock().await;
233        if self.client.load_full().take_tool_list_changed() {
234            caches.tools = None;
235        }
236
237        if let Some(cache) = &caches.tools {
238            return Ok(Arc::clone(cache));
239        }
240        drop(caches);
241
242        self.refresh_tools_shared(allowlist, timeout).await
243    }
244
245    pub(super) async fn refresh_tools(
246        &self,
247        allowlist: &McpAllowListConfig,
248        timeout: Option<Duration>,
249    ) -> Result<Vec<McpToolInfo>> {
250        Ok(self.refresh_tools_shared(allowlist, timeout).await?.as_ref().clone())
251    }
252
253    async fn refresh_tools_shared(
254        &self,
255        allowlist: &McpAllowListConfig,
256        timeout: Option<Duration>,
257    ) -> Result<Arc<Vec<McpToolInfo>>> {
258        let client = self.client.load_full();
259        let tools = client.list_all_tools(timeout).await?;
260        let filtered = Arc::new(self.filter_tools(tools, allowlist));
261        self.caches.lock().await.tools = Some(Arc::clone(&filtered));
262        Ok(filtered)
263    }
264
265    pub(super) async fn has_tool(
266        &self,
267        tool_name: &str,
268        allowlist: &McpAllowListConfig,
269        timeout: Option<Duration>,
270    ) -> Result<bool> {
271        let tools = self.list_tools_shared(allowlist, timeout).await?;
272        Ok(tools.iter().any(|tool| tool.name == tool_name))
273    }
274
275    pub(super) async fn call_tool(
276        &self,
277        tool_name: &str,
278        args: &Value,
279        timeout: Option<Duration>,
280        allowlist: &McpAllowListConfig,
281    ) -> Result<CallToolResult> {
282        if !allowlist.is_tool_allowed(&self.name, tool_name) {
283            return Err(anyhow!("Tool '{}' is blocked by the MCP allow list for provider '{}'", tool_name, self.name));
284        }
285
286        let _permit = self
287            .semaphore
288            .clone()
289            .acquire_owned()
290            .await
291            .context("Failed to acquire MCP request slot")?;
292        let mut arguments = McpClient::normalize_arguments(args);
293        self.add_argument_defaults(tool_name, &mut arguments, allowlist, timeout)
294            .await
295            .with_context(|| {
296                format!("failed to prepare arguments for MCP tool '{}' on provider '{}'", tool_name, self.name)
297            })?;
298        let params = CallToolRequestParams::new(tool_name.to_string()).with_arguments(arguments);
299        let client = self.client.load_full();
300        async move { client.call_tool(params, timeout).await }
301            .instrument(mcp_tool_call_span(&self.name, tool_name, &self.config.transport))
302            .await
303    }
304
305    async fn add_argument_defaults(
306        &self,
307        tool_name: &str,
308        arguments: &mut Map<String, Value>,
309        allowlist: &McpAllowListConfig,
310        timeout: Option<Duration>,
311    ) -> Result<()> {
312        let requires_timezone = self
313            .tool_requires_field(tool_name, TIMEZONE_ARGUMENT, allowlist, timeout)
314            .await?;
315        ensure_timezone_argument(arguments, requires_timezone)?;
316        Ok(())
317    }
318
319    async fn tool_requires_field(
320        &self,
321        tool_name: &str,
322        field: &str,
323        allowlist: &McpAllowListConfig,
324        timeout: Option<Duration>,
325    ) -> Result<bool> {
326        if let Some(tools) = &self.caches.lock().await.tools
327            && let Some(tool) = tools.iter().find(|tool| tool.name == tool_name)
328        {
329            return Ok(schema_requires_field(&tool.input_schema, field));
330        }
331
332        match self.refresh_tools_shared(allowlist, timeout).await {
333            Ok(tools) => Ok(tools
334                .iter()
335                .find(|tool| tool.name == tool_name)
336                .map(|tool| schema_requires_field(&tool.input_schema, field))
337                .unwrap_or(false)),
338            Err(err) => {
339                warn!(
340                    "Failed to refresh tools while inspecting schema for '{}' on provider '{}': {err}",
341                    tool_name, self.name
342                );
343                Ok(false)
344            }
345        }
346    }
347
348    pub(super) async fn list_resources(
349        &self,
350        allowlist: &McpAllowListConfig,
351        timeout: Option<Duration>,
352    ) -> Result<Vec<McpResourceInfo>> {
353        Ok(self.list_resources_shared(allowlist, timeout).await?.as_ref().clone())
354    }
355
356    async fn list_resources_shared(
357        &self,
358        allowlist: &McpAllowListConfig,
359        timeout: Option<Duration>,
360    ) -> Result<Arc<Vec<McpResourceInfo>>> {
361        let mut caches = self.caches.lock().await;
362        if self.client.load_full().take_resource_list_changed() {
363            caches.resources = None;
364        }
365
366        if let Some(cache) = &caches.resources {
367            return Ok(Arc::clone(cache));
368        }
369        drop(caches);
370
371        self.refresh_resources_shared(allowlist, timeout).await
372    }
373
374    pub(super) async fn refresh_resources(
375        &self,
376        allowlist: &McpAllowListConfig,
377        timeout: Option<Duration>,
378    ) -> Result<Vec<McpResourceInfo>> {
379        Ok(self.refresh_resources_shared(allowlist, timeout).await?.as_ref().clone())
380    }
381
382    async fn refresh_resources_shared(
383        &self,
384        allowlist: &McpAllowListConfig,
385        timeout: Option<Duration>,
386    ) -> Result<Arc<Vec<McpResourceInfo>>> {
387        let client = self.client.load_full();
388        let resources = client.list_all_resources(timeout).await?;
389        let filtered = Arc::new(self.filter_resources(resources, allowlist));
390        self.caches.lock().await.resources = Some(Arc::clone(&filtered));
391        Ok(filtered)
392    }
393
394    pub(super) async fn has_resource(
395        &self,
396        uri: &str,
397        allowlist: &McpAllowListConfig,
398        timeout: Option<Duration>,
399    ) -> Result<bool> {
400        let resources = self.list_resources_shared(allowlist, timeout).await?;
401        Ok(resources.iter().any(|resource| resource.uri == uri))
402    }
403
404    pub(super) async fn read_resource(
405        &self,
406        uri: &str,
407        timeout: Option<Duration>,
408        allowlist: &McpAllowListConfig,
409    ) -> Result<McpResourceData> {
410        if !allowlist.is_resource_allowed(&self.name, uri) {
411            return Err(anyhow!("Resource '{}' is blocked by the MCP allow list for provider '{}'", uri, self.name));
412        }
413
414        let _permit = self
415            .semaphore
416            .clone()
417            .acquire_owned()
418            .await
419            .context("Failed to acquire MCP request slot")?;
420        let params = ReadResourceRequestParams::new(uri.to_string());
421        let client = self.client.load_full();
422        let result = client.read_resource(params, timeout).await?;
423        Ok(McpResourceData {
424            provider: self.name.clone(),
425            uri: uri.to_string(),
426            contents: result.contents,
427            meta: Map::new(),
428        })
429    }
430
431    pub(super) async fn list_prompts(
432        &self,
433        allowlist: &McpAllowListConfig,
434        timeout: Option<Duration>,
435    ) -> Result<Vec<McpPromptInfo>> {
436        Ok(self.list_prompts_shared(allowlist, timeout).await?.as_ref().clone())
437    }
438
439    async fn list_prompts_shared(
440        &self,
441        allowlist: &McpAllowListConfig,
442        timeout: Option<Duration>,
443    ) -> Result<Arc<Vec<McpPromptInfo>>> {
444        let mut caches = self.caches.lock().await;
445        if self.client.load_full().take_prompt_list_changed() {
446            caches.prompts = None;
447        }
448
449        if let Some(cache) = &caches.prompts {
450            return Ok(Arc::clone(cache));
451        }
452        drop(caches);
453
454        self.refresh_prompts_shared(allowlist, timeout).await
455    }
456
457    pub(super) async fn refresh_prompts(
458        &self,
459        allowlist: &McpAllowListConfig,
460        timeout: Option<Duration>,
461    ) -> Result<Vec<McpPromptInfo>> {
462        Ok(self.refresh_prompts_shared(allowlist, timeout).await?.as_ref().clone())
463    }
464
465    async fn refresh_prompts_shared(
466        &self,
467        allowlist: &McpAllowListConfig,
468        timeout: Option<Duration>,
469    ) -> Result<Arc<Vec<McpPromptInfo>>> {
470        let client = self.client.load_full();
471        let prompts = client.list_all_prompts(timeout).await?;
472        let filtered = Arc::new(self.filter_prompts(prompts, allowlist));
473        self.caches.lock().await.prompts = Some(Arc::clone(&filtered));
474        Ok(filtered)
475    }
476
477    pub(super) async fn has_prompt(
478        &self,
479        prompt_name: &str,
480        allowlist: &McpAllowListConfig,
481        timeout: Option<Duration>,
482    ) -> Result<bool> {
483        let prompts = self.list_prompts_shared(allowlist, timeout).await?;
484        Ok(prompts.iter().any(|prompt| prompt.name == prompt_name))
485    }
486
487    pub(super) async fn get_prompt(
488        &self,
489        prompt_name: &str,
490        arguments: HashMap<String, String>,
491        timeout: Option<Duration>,
492        allowlist: &McpAllowListConfig,
493    ) -> Result<McpPromptDetail> {
494        if !allowlist.is_prompt_allowed(&self.name, prompt_name) {
495            return Err(anyhow!(
496                "Prompt '{}' is blocked by the MCP allow list for provider '{}'",
497                prompt_name,
498                self.name
499            ));
500        }
501
502        let _permit = self
503            .semaphore
504            .clone()
505            .acquire_owned()
506            .await
507            .context("Failed to acquire MCP request slot")?;
508        // Convert HashMap<String, String> to JsonObject (BTreeMap<String, Value>)
509        let args_json: Map<String, Value> = arguments.into_iter().map(|(k, v)| (k, Value::String(v))).collect();
510
511        let params = GetPromptRequestParams::new(prompt_name.to_string()).with_arguments(args_json);
512        let client = self.client.load_full();
513        let result = client.get_prompt(params, timeout).await?;
514        Ok(McpPromptDetail {
515            provider: self.name.clone(),
516            name: prompt_name.to_string(),
517            description: result.description,
518            messages: result.messages,
519            meta: Map::new(),
520        })
521    }
522
523    /// Return the cached tool list as a shared handle.
524    ///
525    /// The cache already stores `Arc<Vec<McpToolInfo>>`; returning the `Arc`
526    /// avoids deep-cloning every tool description and JSON schema on each hit.
527    pub(super) async fn cached_tools_shared(&self) -> Option<Arc<Vec<McpToolInfo>>> {
528        self.caches.lock().await.tools.as_ref().map(Arc::clone)
529    }
530
531    /// Return cached tools or refresh them, handing back the shared cache entry.
532    ///
533    /// Callers that only need to read/record the list can keep the `Arc` and
534    /// skip the per-call deep clone that the owned-`Vec` return used to force.
535    pub(super) async fn cached_tools_or_refresh_shared(
536        &self,
537        allowlist: &McpAllowListConfig,
538        timeout: Option<Duration>,
539    ) -> Result<Arc<Vec<McpToolInfo>>> {
540        if let Some(tools) = self.cached_tools_shared().await {
541            return Ok(tools);
542        }
543
544        self.refresh_tools_shared(allowlist, timeout).await
545    }
546
547    pub(super) async fn shutdown(&self) -> Result<()> {
548        let client = self.client.load_full();
549        client.shutdown().await
550    }
551
552    /// Returns `true` when the underlying transport is still connected and responsive.
553    pub(super) async fn is_healthy(&self) -> bool {
554        let client = self.client.load_full();
555        client.is_healthy().await
556    }
557
558    /// Attempt to re-establish the MCP connection using the stored configuration.
559    ///
560    /// This replaces the inner [`RmcpClient`] with a freshly connected one, then
561    /// re-initialises the provider (tools/resources/prompts caches are invalidated).
562    pub(super) async fn reconnect(
563        &self,
564        startup_timeout: Option<Duration>,
565        tool_timeout: Option<Duration>,
566        allowlist: &McpAllowListConfig,
567    ) -> Result<()> {
568        tracing::info!(provider = self.name.as_str(), "Attempting MCP reconnection");
569
570        // Shut down the old client (best-effort).
571        {
572            let old = self.client.load_full();
573            drop(old.shutdown().await);
574        }
575
576        // Create a fresh client from the stored config.
577        let new_provider = McpProvider::connect(
578            self.config.clone(),
579            self.elicitation_handler.clone(),
580            self.sandbox_context.clone(),
581            self.advertise_ui_apps,
582        )
583        .await
584        .with_context(|| format!("MCP reconnect failed for provider '{}'", self.name))?;
585
586        // Swap inner client.
587        {
588            let new_client = new_provider.client.load_full();
589            self.client.store(new_client);
590        }
591
592        // Invalidate all caches before re-initialisation.
593        self.invalidate_caches();
594
595        // Re-initialise (handshake + tool refresh).
596        let init_params = build_reconnect_initialize_params(self.advertise_ui_apps);
597        self.initialize(init_params, startup_timeout, tool_timeout, allowlist)
598            .await
599            .with_context(|| format!("MCP re-initialization failed for provider '{}'", self.name))?;
600
601        tracing::info!(provider = self.name.as_str(), "MCP reconnection successful");
602        Ok(())
603    }
604
605    fn filter_tools(&self, tools: Vec<Tool>, allowlist: &McpAllowListConfig) -> Vec<McpToolInfo> {
606        filter_tools_sorted(&self.name, tools, allowlist)
607    }
608
609    fn filter_resources(&self, resources: Vec<Resource>, allowlist: &McpAllowListConfig) -> Vec<McpResourceInfo> {
610        filter_resources_sorted(&self.name, resources, allowlist)
611    }
612
613    fn filter_prompts(&self, prompts: Vec<Prompt>, allowlist: &McpAllowListConfig) -> Vec<McpPromptInfo> {
614        filter_prompts_sorted(&self.name, prompts, allowlist)
615    }
616}
617
618/// Build initialize params for a provider reconnect, retaining the UI advertisement.
619fn build_reconnect_initialize_params(advertise_ui_apps: bool) -> InitializeRequestParams {
620    let mut capabilities = rmcp::model::ClientCapabilities::default();
621    apply_ui_extension_gate(&mut capabilities, advertise_ui_apps);
622    InitializeRequestParams::new(capabilities, super::utils::build_client_implementation())
623        .with_protocol_version(latest_protocol_version())
624}
625
626// Servers may reorder lists between calls; a stable order keeps LLM prompt-cache prefixes valid.
627fn filter_tools_sorted(provider: &str, tools: Vec<Tool>, allowlist: &McpAllowListConfig) -> Vec<McpToolInfo> {
628    let mut filtered: Vec<McpToolInfo> = tools
629        .into_iter()
630        .filter(|tool| allowlist.is_tool_allowed(provider, &tool.name))
631        .map(|tool| {
632            let parsed = parse_mcp_tool(&tool);
633            McpToolInfo {
634                description: parsed.description,
635                input_schema: parsed.input_schema,
636                output_schema: parsed.output_schema,
637                provider: provider.to_owned(),
638                name: parsed.name,
639                ui: parsed.ui,
640                visibility: parsed.visibility,
641            }
642        })
643        .collect();
644    filtered.sort_by(|a, b| a.name.cmp(&b.name));
645    filtered
646}
647
648fn filter_resources_sorted(
649    provider: &str,
650    resources: Vec<Resource>,
651    allowlist: &McpAllowListConfig,
652) -> Vec<McpResourceInfo> {
653    let mut filtered: Vec<McpResourceInfo> = resources
654        .into_iter()
655        .filter(|resource| allowlist.is_resource_allowed(provider, &resource.uri))
656        .map(|resource| McpResourceInfo {
657            provider: provider.to_owned(),
658            uri: resource.uri.clone(),
659            name: resource.name.clone(),
660            description: resource.description.clone(),
661            mime_type: resource.mime_type.clone(),
662            size: resource.size.map(|s| i64::try_from(s).unwrap_or(i64::MAX)),
663        })
664        .collect();
665    filtered.sort_by(|a, b| a.uri.cmp(&b.uri));
666    filtered
667}
668
669fn filter_prompts_sorted(provider: &str, prompts: Vec<Prompt>, allowlist: &McpAllowListConfig) -> Vec<McpPromptInfo> {
670    let mut filtered: Vec<McpPromptInfo> = prompts
671        .into_iter()
672        .filter(|prompt| allowlist.is_prompt_allowed(provider, &prompt.name))
673        .map(|prompt| McpPromptInfo {
674            provider: provider.to_owned(),
675            name: prompt.name.clone(),
676            description: prompt.description.clone(),
677            arguments: prompt.arguments.clone().unwrap_or_default(),
678        })
679        .collect();
680    filtered.sort_by(|a, b| a.name.cmp(&b.name));
681    filtered
682}
683
684fn mcp_tool_call_span(provider_name: &str, tool_name: &str, transport: &McpTransportConfig) -> Span {
685    let (transport_label, server_address, server_port) = match transport {
686        McpTransportConfig::Stdio(_) => ("stdio", String::new(), 0_u16),
687        McpTransportConfig::Http(http) => {
688            let (server_address, server_port) = Url::parse(&http.endpoint)
689                .ok()
690                .and_then(|url| {
691                    url.host_str()
692                        .map(|host| (host.to_string(), url.port_or_known_default().unwrap_or_default()))
693                })
694                .unwrap_or_default();
695            ("streamable_http", server_address, server_port)
696        }
697    };
698
699    tracing::info_span!(
700        "mcp.tools.call",
701        provider = provider_name,
702        tool = tool_name,
703        rpc_system = "jsonrpc",
704        rpc_method = "tools/call",
705        transport = transport_label,
706        server_address = server_address.as_str(),
707        server_port = server_port,
708    )
709}
710
711#[cfg(test)]
712mod tests {
713    use super::mcp_tool_call_span;
714    use std::fs::{self, File, OpenOptions};
715    use std::io::{BufWriter, Write};
716    use std::sync::{Arc, Mutex};
717    use tempfile::tempdir;
718    use tracing_subscriber::{fmt::format::FmtSpan, prelude::*};
719    use vtcode_config::mcp::{McpHttpServerConfig, McpStdioServerConfig, McpTransportConfig};
720
721    /// Minimal clonable buffered writer for tests. Implements `Write` so it can
722    /// be passed to `tracing_subscriber::fmt::layer().with_writer(..)`.
723    #[derive(Clone)]
724    struct TestWriter(Arc<Mutex<BufWriter<File>>>);
725
726    impl TestWriter {
727        fn open(path: &std::path::Path) -> Self {
728            let file = OpenOptions::new()
729                .create(true)
730                .truncate(true)
731                .write(true)
732                .open(path)
733                .expect("open trace log");
734            Self(Arc::new(Mutex::new(BufWriter::new(file))))
735        }
736
737        fn flush(&self) {
738            if let Ok(mut w) = self.0.lock() {
739                drop(w.flush());
740            }
741        }
742    }
743
744    impl Write for TestWriter {
745        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
746            self.0.lock().map_err(|e| std::io::Error::other(e.to_string()))?.write(buf)
747        }
748
749        fn flush(&mut self) -> std::io::Result<()> {
750            self.0.lock().map_err(|e| std::io::Error::other(e.to_string()))?.flush()
751        }
752    }
753
754    #[test]
755    fn mcp_tool_call_span_records_http_metadata() {
756        let tempdir = tempdir().expect("tempdir");
757        let log_file = tempdir.path().join("trace.log");
758        let writer = TestWriter::open(&log_file);
759        let writer_for_layer = writer.clone();
760        let subscriber = tracing_subscriber::registry().with(
761            tracing_subscriber::fmt::layer()
762                .with_writer(move || writer_for_layer.clone())
763                .with_span_events(FmtSpan::FULL)
764                .with_ansi(false),
765        );
766        let _guard = tracing::subscriber::set_default(subscriber);
767
768        {
769            let span = mcp_tool_call_span(
770                "calendar",
771                "get_events",
772                &McpTransportConfig::Http(McpHttpServerConfig {
773                    endpoint: "https://example.com:8443/mcp".to_string(),
774                    api_key_env: None,
775                    oauth: None,
776                    protocol_version: "2024-11-05".to_string(),
777                    handshake: McpHttpHandshakeMode::Legacy,
778                    http_headers: Default::default(),
779                    env_http_headers: Default::default(),
780                }),
781            );
782            let _entered = span.enter();
783        }
784
785        writer.flush();
786        let logs = fs::read_to_string(&log_file).expect("trace log");
787        assert!(logs.contains("mcp.tools.call"));
788        assert!(logs.contains("provider=\"calendar\""));
789        assert!(logs.contains("tool=\"get_events\""));
790        assert!(logs.contains("rpc_system=\"jsonrpc\""));
791        assert!(logs.contains("rpc_method=\"tools/call\""));
792        assert!(logs.contains("transport=\"streamable_http\""));
793        assert!(logs.contains("server_address=\"example.com\""));
794        assert!(logs.contains("server_port=8443"));
795    }
796
797    #[test]
798    fn mcp_tool_call_span_defaults_stdio_transport() {
799        let span = mcp_tool_call_span(
800            "filesystem",
801            "read_file",
802            &McpTransportConfig::Stdio(McpStdioServerConfig {
803                command: "rmcp-server".to_string(),
804                args: Vec::new(),
805                working_directory: None,
806            }),
807        );
808
809        assert_eq!(span.metadata().expect("metadata").name(), "mcp.tools.call");
810    }
811
812    use rmcp::model::{ProtocolVersion, ServerCapabilities, ServerPeerInfo};
813    use rmcp::service::ClientLifecycleMode;
814    use vtcode_config::mcp::{McpHttpHandshakeMode, McpProviderConfig, McpSandboxOverrideConfig};
815
816    async fn stdio_provider(name: &str) -> super::McpProvider {
817        let config = McpProviderConfig {
818            name: name.to_string(),
819            transport: McpTransportConfig::Stdio(McpStdioServerConfig {
820                command: "true".to_string(),
821                args: Vec::new(),
822                working_directory: None,
823            }),
824            ..McpProviderConfig::default()
825        };
826        super::McpProvider::connect(config, None, None, false)
827            .await
828            .expect("stdio provider connects")
829    }
830
831    async fn http_provider(name: &str, handshake: McpHttpHandshakeMode) -> super::McpProvider {
832        let config = McpProviderConfig {
833            name: name.to_string(),
834            transport: McpTransportConfig::Http(McpHttpServerConfig {
835                endpoint: "https://example.com/mcp".to_string(),
836                handshake,
837                ..McpHttpServerConfig::default()
838            }),
839            ..McpProviderConfig::default()
840        };
841        super::McpProvider::connect(config, None, None, false)
842            .await
843            .expect("http provider connects")
844    }
845
846    #[tokio::test]
847    async fn connect_rejects_sandbox_overrides_without_session_context() {
848        let mut config = McpProviderConfig {
849            name: "sandboxed".to_string(),
850            transport: McpTransportConfig::Stdio(McpStdioServerConfig {
851                command: "true".to_string(),
852                args: Vec::new(),
853                working_directory: None,
854            }),
855            ..McpProviderConfig::default()
856        };
857        config.sandbox = Some(McpSandboxOverrideConfig {
858            max_memory_mb: Some(256),
859            ..McpSandboxOverrideConfig::default()
860        });
861        let err = super::McpProvider::connect(config, None, None, false)
862            .await
863            .err()
864            .expect("overrides without session context must fail before spawn");
865        let message = format!("{err:#}");
866        assert!(message.contains("unsatisfiable sandbox overrides"), "unexpected error: {message}");
867        assert!(message.contains("session sandboxing is disabled"), "unexpected error: {message}");
868    }
869
870    #[tokio::test]
871    async fn handshake_lifecycle_defaults_to_legacy_initialize_for_http() {
872        let provider = http_provider("legacy", McpHttpHandshakeMode::Legacy).await;
873        assert!(matches!(provider.handshake_lifecycle(), ClientLifecycleMode::Initialize));
874    }
875
876    #[tokio::test]
877    async fn handshake_lifecycle_uses_auto_for_stdio_and_opt_in_http() {
878        let stdio = stdio_provider("local").await;
879        match stdio.handshake_lifecycle() {
880            ClientLifecycleMode::Auto { preferred_versions, legacy_version } => {
881                let versions: Vec<String> = preferred_versions.iter().map(ToString::to_string).collect();
882                assert_eq!(versions, vec!["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]);
883                assert_eq!(legacy_version.map(|version| version.to_string()), Some("2024-11-05".to_string()));
884            }
885            other => panic!("expected Auto lifecycle, got {other:?}"),
886        }
887
888        let modern = http_provider("modern", McpHttpHandshakeMode::Auto).await;
889        assert!(matches!(modern.handshake_lifecycle(), ClientLifecycleMode::Auto { .. }));
890    }
891
892    #[tokio::test]
893    async fn negotiated_protocol_version_tracks_last_handshake() {
894        let provider = http_provider("probe", McpHttpHandshakeMode::Legacy).await;
895        assert_eq!(provider.negotiated_protocol_version().await, None);
896
897        *provider.initialize_result.lock().await =
898            Some(ServerPeerInfo::new(ProtocolVersion::V_2025_11_25, ServerCapabilities::default()));
899        assert_eq!(provider.negotiated_protocol_version().await.as_deref(), Some("2025-11-25"));
900    }
901
902    #[test]
903    fn filtered_catalogs_are_sorted_regardless_of_server_order() {
904        use super::{filter_prompts_sorted, filter_resources_sorted, filter_tools_sorted};
905        use rmcp::model::{Prompt, Resource, Tool};
906        use serde_json::Map;
907        use std::sync::Arc;
908        use vtcode_config::mcp::McpAllowListConfig;
909
910        let allowlist = McpAllowListConfig::default();
911        // Uppercase sorts before lowercase and a prefix sorts before its extension in byte order.
912        let tool_names = ["search_v2", "Zeta", "search", "alpha"];
913        let tools = tool_names
914            .iter()
915            .map(|name| Tool::new(*name, "desc", Arc::new(Map::new())))
916            .collect();
917        let sorted_tools: Vec<String> = filter_tools_sorted("p", tools, &allowlist)
918            .into_iter()
919            .map(|tool| tool.name)
920            .collect();
921        assert_eq!(sorted_tools, ["Zeta", "alpha", "search", "search_v2"]);
922
923        let resources = ["file:///b", "file:///a/z", "file:///a"]
924            .iter()
925            .map(|uri| Resource::new(*uri, "r"))
926            .collect();
927        let sorted_resources: Vec<String> = filter_resources_sorted("p", resources, &allowlist)
928            .into_iter()
929            .map(|resource| resource.uri)
930            .collect();
931        assert_eq!(sorted_resources, ["file:///a", "file:///a/z", "file:///b"]);
932
933        let prompts = ["review", "Explain", "review2"]
934            .iter()
935            .map(|name| Prompt::new(*name, None::<String>, None))
936            .collect();
937        let sorted_prompts: Vec<String> = filter_prompts_sorted("p", prompts, &allowlist)
938            .into_iter()
939            .map(|prompt| prompt.name)
940            .collect();
941        assert_eq!(sorted_prompts, ["Explain", "review", "review2"]);
942    }
943
944    #[test]
945    fn reconnect_initialize_params_gate_ui_extension_on_flag() {
946        let advertised = super::build_reconnect_initialize_params(true);
947        assert!(
948            advertised
949                .capabilities
950                .extensions
951                .as_ref()
952                .is_some_and(|extensions| extensions.contains_key("io.modelcontextprotocol/ui")),
953        );
954        let silent = super::build_reconnect_initialize_params(false);
955        assert_eq!(silent.capabilities.extensions, None);
956    }
957
958    #[tokio::test]
959    async fn connect_retains_ui_advertisement_flag_for_reconnects() {
960        let config = McpProviderConfig {
961            name: "flagged".to_string(),
962            transport: McpTransportConfig::Stdio(McpStdioServerConfig {
963                command: "true".to_string(),
964                args: Vec::new(),
965                working_directory: None,
966            }),
967            ..McpProviderConfig::default()
968        };
969        let provider = super::McpProvider::connect(config, None, None, true)
970            .await
971            .expect("stdio provider connects");
972        assert!(provider.advertise_ui_apps);
973    }
974}