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    #[expect(clippy::cognitive_complexity, reason = "MCP dispatch; split request/response")]
171    pub async fn refresh_mcp_tools(&self) -> Result<()> {
172        let mcp_client_opt = self.mcp_client.read().clone();
173        if let Some(mcp_client) = mcp_client_opt {
174            debug!("Refreshing MCP tools for {} providers", mcp_client.get_status().provider_count);
175
176            let mut tools: Option<Vec<McpToolInfo>> = None;
177            let mut last_err: Option<anyhow::Error> = None;
178            // Total list attempts (initial + retries) for one refresh cycle.
179            const REFRESH_MAX_ATTEMPTS: u32 = 3;
180            // Same 200ms-doubling, 3s-capped budget as before, via the canonical
181            // policy so the delay math has one owner.
182            let retry_policy = vtcode_commons::retry::RetryPolicy::from_retries(
183                REFRESH_MAX_ATTEMPTS - 1,
184                Duration::from_millis(200),
185                Duration::from_secs(3),
186                2.0,
187            )
188            .with_jitter(vtcode_commons::retry::RetryPolicy::DEFAULT_JITTER);
189            for attempt in 0..(REFRESH_MAX_ATTEMPTS as usize) {
190                match mcp_client.list_mcp_tools().await {
191                    Ok(list) => {
192                        tools = Some(list);
193                        break;
194                    }
195                    Err(err) => {
196                        let retry_allowed = mcp_refresh_retry_allowed(&err);
197                        last_err = Some(err);
198                        if !retry_allowed {
199                            warn!(
200                                attempt = attempt + 1,
201                                "MCP tool refresh failed due to configuration; skipping retries"
202                            );
203                            break;
204                        }
205                        if attempt + 1 >= REFRESH_MAX_ATTEMPTS as usize {
206                            break;
207                        }
208                        let backoff = retry_policy.delay_for_attempt(u32::try_from(attempt).unwrap_or(u32::MAX));
209                        warn!(
210                            attempt = attempt + 1,
211                            delay_ms = %backoff.as_millis(),
212                            "Failed to list MCP tools, retrying with backoff"
213                        );
214                        tokio::time::sleep(backoff).await;
215                    }
216                }
217            }
218
219            let tools = match tools {
220                Some(list) => list,
221                None => {
222                    let Some(error) = last_err else {
223                        warn!("Failed to refresh MCP tools without an error payload; keeping existing cache");
224                        return Ok(());
225                    };
226                    if let Some(guidance) = vtcode_commons::detect_misconfiguration_in_anyhow(&error) {
227                        return Err(anyhow!("{error:#}: {}", guidance.user_message()))
228                            .context("MCP tool refresh is blocked by configuration");
229                    }
230                    warn!(
231                        error = %error,
232                        "Failed to refresh MCP tools after retries; keeping existing cache"
233                    );
234                    let category = classify_anyhow_error(&error);
235                    self.mcp_circuit_breaker.record_failure_category(category);
236                    return Ok(());
237                }
238            };
239            let existing_tools: Vec<String> = {
240                let index = self.mcp_tool_index.read().await;
241                index
242                    .iter()
243                    .flat_map(|(provider, names)| names.iter().map(move |name| format!("mcp::{provider}::{name}")))
244                    .collect()
245            };
246            for canonical_name in existing_tools {
247                if let Err(err) = self.inventory.remove_tool(&canonical_name) {
248                    warn!(
249                        tool = %canonical_name,
250                        error = %err,
251                        "failed to remove stale MCP proxy tool"
252                    );
253                }
254            }
255
256            let mut provider_map: FxHashMap<String, Vec<String>> = FxHashMap::default();
257            let mut seen_tools = FxHashSet::default();
258
259            for tool in &tools {
260                let canonical_name = format!("mcp::{}::{}", tool.provider, tool.name);
261                if !seen_tools.insert(canonical_name) {
262                    continue;
263                }
264                let registration = match build_mcp_registration(Arc::clone(&mcp_client), &tool.provider, tool, None) {
265                    Ok(registration) => registration,
266                    Err(error) => {
267                        warn!(%error, "Rejected MCP proxy metadata");
268                        continue;
269                    }
270                };
271                if let Err(error) = self.inventory.register_tool(registration) {
272                    warn!(%error, "Failed to register MCP proxy tool");
273                    continue;
274                }
275                provider_map.entry(tool.provider.clone()).or_default().push(tool.name.clone());
276            }
277
278            for tools in provider_map.values_mut() {
279                tools.sort();
280                tools.dedup();
281            }
282
283            *self.mcp_tool_index.write().await = provider_map;
284            {
285                let mut reverse_index = self.mcp_reverse_index.write().await;
286                reverse_index.clear();
287                let index = self.mcp_tool_index.read().await;
288                // First provider by name owns a colliding tool name, matching `McpClient` routing.
289                for (provider, tools) in sorted_providers(&index) {
290                    for tool in tools {
291                        let _ = reverse_index.entry(tool.clone()).or_insert_with(|| provider.clone());
292                    }
293                }
294            }
295
296            let mcp_index = self.mcp_tool_index.read().await;
297            let std_index: hashbrown::HashMap<String, Vec<String>> =
298                mcp_index.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
299            let allowlist = {
300                let gateway = self.policy_gateway.clone();
301                gateway.update_mcp_tools(&std_index).await?
302            };
303            if let Some(allowlist) = allowlist {
304                mcp_client.update_allowlist(allowlist);
305            }
306
307            *self.cached_available_tools.write() = None;
308            self.rebuild_tool_assembly().await;
309            self.tool_catalog_state.note_explicit_refresh("mcp_tool_refresh");
310            self.sync_policy_catalog().await;
311            // MP-3: Record success in circuit breaker
312            self.mcp_circuit_breaker.record_success();
313            Ok(())
314        } else {
315            debug!("No MCP client configured, pruning stale MCP proxy tools");
316            self.remove_all_mcp_proxy_tools();
317            self.mcp_tool_index.write().await.clear();
318            self.mcp_reverse_index.write().await.clear();
319            *self.cached_available_tools.write() = None;
320            self.rebuild_tool_assembly().await;
321            self.tool_catalog_state.note_explicit_refresh("mcp_tool_refresh_no_client");
322            self.sync_policy_catalog().await;
323            Ok(())
324        }
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::{mcp_refresh_retry_allowed, sorted_providers};
331    use anyhow::anyhow;
332    use rustc_hash::FxHashMap;
333
334    #[test]
335    fn mcp_refresh_skips_configuration_failures_but_retries_transient_errors() {
336        assert!(!mcp_refresh_retry_allowed(&anyhow!("MCP server URL invalid: endpoint must use https")));
337        assert!(mcp_refresh_retry_allowed(&anyhow!("MCP server connection reset by peer")));
338    }
339
340    #[test]
341    fn sorted_providers_orders_by_name_independent_of_insertion() {
342        let mut index: FxHashMap<String, Vec<String>> = FxHashMap::default();
343        for name in ["zeta", "Alpha", "alpha", "beta"] {
344            drop(index.insert(name.to_owned(), vec![format!("{name}_tool")]));
345        }
346
347        let names: Vec<&str> = sorted_providers(&index).iter().map(|(name, _)| name.as_str()).collect();
348        assert_eq!(names, ["Alpha", "alpha", "beta", "zeta"]);
349    }
350}