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 config: McpProviderConfig,
42 elicitation_handler: Option<Arc<dyn McpElicitationHandler>>,
44 advertise_ui_apps: bool,
46 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 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 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 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 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 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 pub(super) async fn is_healthy(&self) -> bool {
554 let client = self.client.load_full();
555 client.is_healthy().await
556 }
557
558 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 {
572 let old = self.client.load_full();
573 drop(old.shutdown().await);
574 }
575
576 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 {
588 let new_client = new_provider.client.load_full();
589 self.client.store(new_client);
590 }
591
592 self.invalidate_caches();
594
595 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
618fn 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
626fn 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#[cfg(test)]
711#[path = "provider_tests.rs"]
712mod tests;