vtcode_core/tools/registry/
mcp_facade.rs1use 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
19fn 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 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 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 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 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 pub fn mcp_client(&self) -> Option<Arc<McpClient>> {
95 self.mcp_client.read().clone()
96 }
97
98 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 output_schema: None,
121 ui: None,
124 visibility: McpToolVisibility::default(),
126 });
127 }
128 }
129 }
130
131 Ok(mcp_tools)
132 }
133
134 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 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 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 for attempt in 0..3 {
178 match mcp_client.list_mcp_tools().await {
179 Ok(list) => {
180 tools = Some(list);
181 break;
182 }
183 Err(err) => {
184 let retry_allowed = mcp_refresh_retry_allowed(&err);
185 last_err = Some(err);
186 if !retry_allowed {
187 warn!(
188 attempt = attempt + 1,
189 "MCP tool refresh failed due to configuration; skipping retries"
190 );
191 break;
192 }
193 let jitter = (attempt * 37) % 80;
194 let pow = 2_u64.saturating_pow(attempt.min(4) as u32); let backoff = Duration::from_millis(200 * pow + jitter).min(Duration::from_secs(3));
196 warn!(
197 attempt = attempt + 1,
198 delay_ms = %backoff.as_millis(),
199 "Failed to list MCP tools, retrying with backoff"
200 );
201 tokio::time::sleep(backoff).await;
202 }
203 }
204 }
205
206 let tools = match tools {
207 Some(list) => list,
208 None => {
209 let Some(error) = last_err else {
210 warn!("Failed to refresh MCP tools without an error payload; keeping existing cache");
211 return Ok(());
212 };
213 if let Some(guidance) = vtcode_commons::detect_misconfiguration_in_anyhow(&error) {
214 return Err(anyhow!("{error:#}: {}", guidance.user_message()))
215 .context("MCP tool refresh is blocked by configuration");
216 }
217 warn!(
218 error = %error,
219 "Failed to refresh MCP tools after retries; keeping existing cache"
220 );
221 let category = classify_anyhow_error(&error);
222 self.mcp_circuit_breaker.record_failure_category(category);
223 return Ok(());
224 }
225 };
226 let existing_tools: Vec<String> = {
227 let index = self.mcp_tool_index.read().await;
228 index
229 .iter()
230 .flat_map(|(provider, names)| names.iter().map(move |name| format!("mcp::{provider}::{name}")))
231 .collect()
232 };
233 for canonical_name in existing_tools {
234 if let Err(err) = self.inventory.remove_tool(&canonical_name) {
235 warn!(
236 tool = %canonical_name,
237 error = %err,
238 "failed to remove stale MCP proxy tool"
239 );
240 }
241 }
242
243 let mut provider_map: FxHashMap<String, Vec<String>> = FxHashMap::default();
244 let mut seen_tools = FxHashSet::default();
245
246 for tool in &tools {
247 let canonical_name = format!("mcp::{}::{}", tool.provider, tool.name);
248 if !seen_tools.insert(canonical_name) {
249 continue;
250 }
251 let registration = match build_mcp_registration(Arc::clone(&mcp_client), &tool.provider, tool, None) {
252 Ok(registration) => registration,
253 Err(error) => {
254 warn!(%error, "Rejected MCP proxy metadata");
255 continue;
256 }
257 };
258 if let Err(error) = self.inventory.register_tool(registration) {
259 warn!(%error, "Failed to register MCP proxy tool");
260 continue;
261 }
262 provider_map.entry(tool.provider.clone()).or_default().push(tool.name.clone());
263 }
264
265 for tools in provider_map.values_mut() {
266 tools.sort();
267 tools.dedup();
268 }
269
270 *self.mcp_tool_index.write().await = provider_map;
271 {
272 let mut reverse_index = self.mcp_reverse_index.write().await;
273 reverse_index.clear();
274 let index = self.mcp_tool_index.read().await;
275 for (provider, tools) in sorted_providers(&index) {
277 for tool in tools {
278 let _ = reverse_index.entry(tool.clone()).or_insert_with(|| provider.clone());
279 }
280 }
281 }
282
283 let mcp_index = self.mcp_tool_index.read().await;
284 let std_index: hashbrown::HashMap<String, Vec<String>> =
285 mcp_index.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
286 let allowlist = {
287 let gateway = self.policy_gateway.clone();
288 gateway.update_mcp_tools(&std_index).await?
289 };
290 if let Some(allowlist) = allowlist {
291 mcp_client.update_allowlist(allowlist);
292 }
293
294 *self.cached_available_tools.write() = None;
295 self.rebuild_tool_assembly().await;
296 self.tool_catalog_state.note_explicit_refresh("mcp_tool_refresh");
297 self.sync_policy_catalog().await;
298 self.mcp_circuit_breaker.record_success();
300 Ok(())
301 } else {
302 debug!("No MCP client configured, pruning stale MCP proxy tools");
303 self.remove_all_mcp_proxy_tools();
304 self.mcp_tool_index.write().await.clear();
305 self.mcp_reverse_index.write().await.clear();
306 *self.cached_available_tools.write() = None;
307 self.rebuild_tool_assembly().await;
308 self.tool_catalog_state.note_explicit_refresh("mcp_tool_refresh_no_client");
309 self.sync_policy_catalog().await;
310 Ok(())
311 }
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::{mcp_refresh_retry_allowed, sorted_providers};
318 use anyhow::anyhow;
319 use rustc_hash::FxHashMap;
320
321 #[test]
322 fn mcp_refresh_skips_configuration_failures_but_retries_transient_errors() {
323 assert!(!mcp_refresh_retry_allowed(&anyhow!("MCP server URL invalid: endpoint must use https")));
324 assert!(mcp_refresh_retry_allowed(&anyhow!("MCP server connection reset by peer")));
325 }
326
327 #[test]
328 fn sorted_providers_orders_by_name_independent_of_insertion() {
329 let mut index: FxHashMap<String, Vec<String>> = FxHashMap::default();
330 for name in ["zeta", "Alpha", "alpha", "beta"] {
331 drop(index.insert(name.to_owned(), vec![format!("{name}_tool")]));
332 }
333
334 let names: Vec<&str> = sorted_providers(&index).iter().map(|(name, _)| name.as_str()).collect();
335 assert_eq!(names, ["Alpha", "alpha", "beta", "zeta"]);
336 }
337}