Skip to main content

vtcode_core/tools/registry/
mcp_facade.rs

1//! MCP client integration for ToolRegistry.
2
3use rustc_hash::{FxHashMap, FxHashSet};
4use std::sync::Arc;
5use std::time::Duration;
6
7use anyhow::{Context, Result, anyhow};
8use serde_json::Value;
9use tracing::{debug, warn};
10
11use crate::mcp::{McpClient, McpToolExecutor, McpToolInfo, McpToolVisibility};
12use crate::tools::mcp::build_mcp_registration;
13use vtcode_commons::classify_anyhow_error;
14
15use super::ToolRegistry;
16use super::mcp_helpers::normalize_mcp_tool_identifier;
17use super::registration::ToolCatalogSource;
18
19/// Provider-name order keeps listings and collision ownership independent of hash order.
20fn sorted_providers(index: &FxHashMap<String, Vec<String>>) -> Vec<(&String, &Vec<String>)> {
21    let mut providers: Vec<_> = index.iter().collect();
22    providers.sort_unstable_by(|a, b| a.0.cmp(b.0));
23    providers
24}
25
26fn mcp_refresh_retry_allowed(error: &anyhow::Error) -> bool {
27    vtcode_commons::detect_misconfiguration_in_anyhow(error).is_none()
28}
29
30impl ToolRegistry {
31    /// Remove every MCP proxy registration from the inventory.
32    ///
33    /// Proxy tools hold a cloned `Arc<McpClient>` from registration time, so
34    /// they outlive a client detach/replace unless explicitly removed. Leaving
35    /// them behind advertises tools that the canonical `mcp::provider::tool`
36    /// execution path (which requires the registry-level client) cannot run,
37    /// producing the confusing "visible but not executable" state.
38    fn remove_all_mcp_proxy_tools(&self) {
39        let stale: Vec<String> = self
40            .inventory
41            .registrations_snapshot()
42            .into_iter()
43            .filter(|registration| registration.catalog_source() == ToolCatalogSource::Mcp)
44            .map(|registration| registration.name().to_string())
45            .collect();
46        for name in stale {
47            if let Err(err) = self.inventory.remove_tool(&name) {
48                warn!(tool = %name, error = %err, "failed to remove stale MCP proxy tool");
49            }
50        }
51    }
52
53    /// Set the MCP client for this registry.
54    pub async fn with_mcp_client(self, mcp_client: Arc<McpClient>) -> Self {
55        self.remove_all_mcp_proxy_tools();
56        *self.mcp_client.write() = Some(mcp_client);
57        self.mcp_tool_index.write().await.clear();
58        self.mcp_reverse_index.write().await.clear();
59        *self.cached_available_tools.write() = None;
60        self.initialized.store(false, std::sync::atomic::Ordering::Relaxed);
61        self
62    }
63
64    /// Attach an MCP client without consuming the registry.
65    pub async fn set_mcp_client(&self, mcp_client: Arc<McpClient>) {
66        self.remove_all_mcp_proxy_tools();
67        *self.mcp_client.write() = Some(mcp_client);
68        self.mcp_tool_index.write().await.clear();
69        self.mcp_reverse_index.write().await.clear();
70        *self.cached_available_tools.write() = None;
71        self.initialized.store(false, std::sync::atomic::Ordering::Relaxed);
72    }
73
74    /// Detach the current MCP client and clear MCP tool indexes.
75    ///
76    /// Also removes MCP proxy registrations from the inventory and rebuilds
77    /// the tool assembly so `model_tools()` no longer advertises MCP tools
78    /// that cannot be executed. Without this, a primary-agent switch (which
79    /// clears the client pending re-attach) leaves stale `mcp__*` tools on
80    /// the wire that fail with "MCP client not available".
81    pub async fn clear_mcp_client(&self) {
82        self.remove_all_mcp_proxy_tools();
83        *self.mcp_client.write() = None;
84        self.mcp_tool_index.write().await.clear();
85        self.mcp_reverse_index.write().await.clear();
86        *self.cached_available_tools.write() = None;
87        self.initialized.store(false, std::sync::atomic::Ordering::Relaxed);
88        self.rebuild_tool_assembly().await;
89        self.tool_catalog_state.note_explicit_refresh("mcp_client_cleared");
90        self.sync_policy_catalog().await;
91    }
92
93    /// Get the MCP client if available.
94    pub fn mcp_client(&self) -> Option<Arc<McpClient>> {
95        self.mcp_client.read().clone()
96    }
97
98    /// List all MCP tools.
99    pub async fn list_mcp_tools(&self) -> Result<Vec<McpToolInfo>> {
100        let index = self.mcp_tool_index.read().await;
101        if index.is_empty() {
102            return Ok(Vec::new());
103        }
104
105        let providers = sorted_providers(&index);
106
107        let mut mcp_tools = Vec::new();
108        for (provider, tools) in providers {
109            for tool_name in tools {
110                let canonical_name = format!("mcp::{provider}::{tool_name}");
111                if let Some(registration) = self.inventory.get_registration(&canonical_name) {
112                    mcp_tools.push(McpToolInfo {
113                        name: tool_name.clone(),
114                        description: registration.metadata().description().unwrap_or("").to_string(),
115                        provider: provider.clone(),
116                        input_schema: registration.parameter_schema().cloned().unwrap_or(Value::Null),
117                        // The registry index path rebuilds from stored metadata,
118                        // which carries no output schema; live discovery via
119                        // `ToolDiscovery` retains it.
120                        output_schema: None,
121                        // Stored registration metadata carries no MCP Apps
122                        // linkage either; live discovery retains it.
123                        ui: None,
124                        // Registered tools are model tools by construction.
125                        visibility: McpToolVisibility::default(),
126                    });
127                }
128            }
129        }
130
131        Ok(mcp_tools)
132    }
133
134    /// Check if an MCP tool exists.
135    pub async fn has_mcp_tool(&self, tool_name: &str) -> bool {
136        self.mcp_reverse_index.read().await.contains_key(tool_name)
137    }
138
139    /// Execute an MCP tool.
140    pub async fn execute_mcp_tool(&self, tool_name: &str, args: Value) -> Result<Value> {
141        let client_opt = self.mcp_client.read().clone();
142        if let Some(mcp_client) = client_opt {
143            mcp_client.execute_mcp_tool(tool_name, &args).await
144        } else {
145            Err(anyhow!(
146                "MCP client not available (no active MCP connections). The requested MCP tool '{tool_name}' cannot run while disconnected. Use `/mcp repair` or `mcp connect <server>` to reconnect, then retry."
147            ))
148        }
149    }
150
151    pub(super) async fn resolve_mcp_tool_alias(&self, tool_name: &str) -> Option<String> {
152        let normalized = normalize_mcp_tool_identifier(tool_name);
153        if normalized.is_empty() {
154            return None;
155        }
156
157        let index = self.mcp_tool_index.read().await;
158        for tools in index.values() {
159            for tool in tools {
160                if normalize_mcp_tool_identifier(tool) == normalized {
161                    return Some(tool.clone());
162                }
163            }
164        }
165
166        None
167    }
168
169    /// Refresh MCP tools (reconnect to providers and update tool lists).
170    pub async fn refresh_mcp_tools(&self) -> Result<()> {
171        let mcp_client_opt = self.mcp_client.read().clone();
172        if let Some(mcp_client) = mcp_client_opt {
173            debug!("Refreshing MCP tools for {} providers", mcp_client.get_status().provider_count);
174
175            let mut tools: Option<Vec<McpToolInfo>> = None;
176            let mut last_err: Option<anyhow::Error> = None;
177            // Total list attempts (initial + retries) for one refresh cycle.
178            const REFRESH_MAX_ATTEMPTS: u32 = 3;
179            // Same 200ms-doubling, 3s-capped budget as before, via the canonical
180            // policy so the delay math has one owner.
181            let retry_policy = vtcode_commons::retry::RetryPolicy::from_retries(
182                REFRESH_MAX_ATTEMPTS - 1,
183                Duration::from_millis(200),
184                Duration::from_secs(3),
185                2.0,
186            )
187            .with_jitter(vtcode_commons::retry::RetryPolicy::DEFAULT_JITTER);
188            for attempt in 0..(REFRESH_MAX_ATTEMPTS as usize) {
189                match mcp_client.list_mcp_tools().await {
190                    Ok(list) => {
191                        tools = Some(list);
192                        break;
193                    }
194                    Err(err) => {
195                        let retry_allowed = mcp_refresh_retry_allowed(&err);
196                        last_err = Some(err);
197                        if !retry_allowed {
198                            warn!(
199                                attempt = attempt + 1,
200                                "MCP tool refresh failed due to configuration; skipping retries"
201                            );
202                            break;
203                        }
204                        if attempt + 1 >= REFRESH_MAX_ATTEMPTS as usize {
205                            break;
206                        }
207                        let backoff = retry_policy.delay_for_attempt(u32::try_from(attempt).unwrap_or(u32::MAX));
208                        warn!(
209                            attempt = attempt + 1,
210                            delay_ms = %backoff.as_millis(),
211                            "Failed to list MCP tools, retrying with backoff"
212                        );
213                        tokio::time::sleep(backoff).await;
214                    }
215                }
216            }
217
218            let tools = match tools {
219                Some(list) => list,
220                None => {
221                    let Some(error) = last_err else {
222                        warn!("Failed to refresh MCP tools without an error payload; keeping existing cache");
223                        return Ok(());
224                    };
225                    if let Some(guidance) = vtcode_commons::detect_misconfiguration_in_anyhow(&error) {
226                        return Err(anyhow!("{error:#}: {}", guidance.user_message()))
227                            .context("MCP tool refresh is blocked by configuration");
228                    }
229                    warn!(
230                        error = %error,
231                        "Failed to refresh MCP tools after retries; keeping existing cache"
232                    );
233                    let category = classify_anyhow_error(&error);
234                    self.mcp_circuit_breaker.record_failure_category(category);
235                    return Ok(());
236                }
237            };
238            let existing_tools: Vec<String> = {
239                let index = self.mcp_tool_index.read().await;
240                index
241                    .iter()
242                    .flat_map(|(provider, names)| names.iter().map(move |name| format!("mcp::{provider}::{name}")))
243                    .collect()
244            };
245            for canonical_name in existing_tools {
246                if let Err(err) = self.inventory.remove_tool(&canonical_name) {
247                    warn!(
248                        tool = %canonical_name,
249                        error = %err,
250                        "failed to remove stale MCP proxy tool"
251                    );
252                }
253            }
254
255            let mut provider_map: FxHashMap<String, Vec<String>> = FxHashMap::default();
256            let mut seen_tools = FxHashSet::default();
257
258            for tool in &tools {
259                let canonical_name = format!("mcp::{}::{}", tool.provider, tool.name);
260                if !seen_tools.insert(canonical_name) {
261                    continue;
262                }
263                let registration = match build_mcp_registration(Arc::clone(&mcp_client), &tool.provider, tool, None) {
264                    Ok(registration) => registration,
265                    Err(error) => {
266                        warn!(%error, "Rejected MCP proxy metadata");
267                        continue;
268                    }
269                };
270                if let Err(error) = self.inventory.register_tool(registration) {
271                    warn!(%error, "Failed to register MCP proxy tool");
272                    continue;
273                }
274                provider_map.entry(tool.provider.clone()).or_default().push(tool.name.clone());
275            }
276
277            for tools in provider_map.values_mut() {
278                tools.sort();
279                tools.dedup();
280            }
281
282            *self.mcp_tool_index.write().await = provider_map;
283            {
284                let mut reverse_index = self.mcp_reverse_index.write().await;
285                reverse_index.clear();
286                let index = self.mcp_tool_index.read().await;
287                // First provider by name owns a colliding tool name, matching `McpClient` routing.
288                for (provider, tools) in sorted_providers(&index) {
289                    for tool in tools {
290                        let _ = reverse_index.entry(tool.clone()).or_insert_with(|| provider.clone());
291                    }
292                }
293            }
294
295            let mcp_index = self.mcp_tool_index.read().await;
296            let std_index: hashbrown::HashMap<String, Vec<String>> =
297                mcp_index.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
298            let allowlist = {
299                let gateway = self.policy_gateway.clone();
300                gateway.update_mcp_tools(&std_index).await?
301            };
302            if let Some(allowlist) = allowlist {
303                mcp_client.update_allowlist(allowlist);
304            }
305
306            *self.cached_available_tools.write() = None;
307            self.rebuild_tool_assembly().await;
308            self.tool_catalog_state.note_explicit_refresh("mcp_tool_refresh");
309            self.sync_policy_catalog().await;
310            // MP-3: Record success in circuit breaker
311            self.mcp_circuit_breaker.record_success();
312            Ok(())
313        } else {
314            debug!("No MCP client configured, pruning stale MCP proxy tools");
315            self.remove_all_mcp_proxy_tools();
316            self.mcp_tool_index.write().await.clear();
317            self.mcp_reverse_index.write().await.clear();
318            *self.cached_available_tools.write() = None;
319            self.rebuild_tool_assembly().await;
320            self.tool_catalog_state.note_explicit_refresh("mcp_tool_refresh_no_client");
321            self.sync_policy_catalog().await;
322            Ok(())
323        }
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::{mcp_refresh_retry_allowed, sorted_providers};
330    use anyhow::anyhow;
331    use rustc_hash::FxHashMap;
332
333    #[test]
334    fn mcp_refresh_skips_configuration_failures_but_retries_transient_errors() {
335        assert!(!mcp_refresh_retry_allowed(&anyhow!("MCP server URL invalid: endpoint must use https")));
336        assert!(mcp_refresh_retry_allowed(&anyhow!("MCP server connection reset by peer")));
337    }
338
339    #[test]
340    fn sorted_providers_orders_by_name_independent_of_insertion() {
341        let mut index: FxHashMap<String, Vec<String>> = FxHashMap::default();
342        for name in ["zeta", "Alpha", "alpha", "beta"] {
343            drop(index.insert(name.to_owned(), vec![format!("{name}_tool")]));
344        }
345
346        let names: Vec<&str> = sorted_providers(&index).iter().map(|(name, _)| name.as_str()).collect();
347        assert_eq!(names, ["Alpha", "alpha", "beta", "zeta"]);
348    }
349}