Skip to main content

vtcode_mcp/
tool_discovery.rs

1//! Tool discovery and search functionality for MCP tools.
2//!
3//! This module implements progressive disclosure of MCP tools to agents,
4//! allowing for context-efficient tool discovery without flooding the
5//! model's context with full tool schemas.
6//!
7//! # Example
8//!
9//! ```ignore
10//! let discovery = ToolDiscovery::new(mcp_client);
11//!
12//! // Search for tools by keyword
13//! let results = discovery.search_tools("file", DetailLevel::NameOnly).await?;
14//!
15//! // Get detailed schema for a specific tool
16//! let detail = discovery.get_tool_detail("read_file").await?;
17//! ```
18
19use crate::McpToolInfo;
20use anyhow::Result;
21use serde_json::Value;
22use std::cmp::Ordering;
23use std::sync::Arc;
24use tracing::{debug, info};
25
26/// Level of detail returned in tool search results.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum DetailLevel {
29    /// Only tool name (minimal context)
30    NameOnly,
31    /// Name and description (default)
32    NameAndDescription,
33    /// Full schema including input parameters
34    Full,
35}
36
37impl DetailLevel {
38    pub fn as_str(&self) -> &'static str {
39        match self {
40            Self::NameOnly => "name-only",
41            Self::NameAndDescription => "name-and-description",
42            Self::Full => "full",
43        }
44    }
45}
46
47/// Result of a tool discovery operation.
48#[derive(Debug, Clone, serde::Serialize)]
49pub struct ToolDiscoveryResult {
50    pub name: String,
51    pub provider: String,
52    description: String,
53    relevance_score: f32,
54    /// Present only when detail_level is Full or NameAndDescription
55    input_schema: Option<Value>,
56    /// Present only when detail_level is Full and the server advertises it
57    output_schema: Option<Value>,
58}
59
60impl ToolDiscoveryResult {
61    /// Serialize to compact JSON based on detail level.
62    pub fn to_json(&self, detail_level: DetailLevel) -> Value {
63        match detail_level {
64            DetailLevel::NameOnly => serde_json::json!({
65                "name": self.name,
66                "provider": self.provider,
67            }),
68            DetailLevel::NameAndDescription => serde_json::json!({
69                "name": self.name,
70                "provider": self.provider,
71                "description": self.description,
72            }),
73            DetailLevel::Full => {
74                let mut item = serde_json::json!({
75                    "name": self.name,
76                    "provider": self.provider,
77                    "description": self.description,
78                    "input_schema": self.input_schema,
79                });
80                if let Some(schema) = self.output_schema.as_ref()
81                    && let Some(object) = item.as_object_mut()
82                {
83                    drop(object.insert("output_schema".to_string(), schema.clone()));
84                }
85                item
86            }
87        }
88    }
89}
90
91/// Tool discovery service for progressive disclosure of MCP tools.
92pub struct ToolDiscovery {
93    mcp_client: Arc<dyn crate::McpToolExecutor>,
94}
95
96fn group_results_by_provider_preserving_order(
97    tools: impl IntoIterator<Item = ToolDiscoveryResult>,
98) -> Vec<(String, Vec<ToolDiscoveryResult>)> {
99    let mut grouped: Vec<(String, Vec<ToolDiscoveryResult>)> = Vec::new();
100
101    for tool in tools {
102        let provider = tool.provider.clone();
103        if let Some((_, provider_tools)) =
104            grouped.iter_mut().find(|(existing_provider, _)| *existing_provider == provider)
105        {
106            provider_tools.push(tool);
107        } else {
108            grouped.push((provider, vec![tool]));
109        }
110    }
111
112    grouped
113}
114
115impl ToolDiscovery {
116    /// Create a new tool discovery service.
117    pub fn new(mcp_client: Arc<dyn crate::McpToolExecutor>) -> Self {
118        Self { mcp_client }
119    }
120
121    /// Search for tools by keyword with configurable detail level.
122    ///
123    /// This implements progressive disclosure: agents can search with
124    /// low detail to find relevant tools, then request full schemas
125    /// only for tools they intend to use.
126    ///
127    /// Follows AGENTS.md guidelines: limits results to 5 items with overflow indication.
128    pub async fn search_tools(&self, keyword: &str, detail_level: DetailLevel) -> Result<Vec<ToolDiscoveryResult>> {
129        let tools = self.mcp_client.list_mcp_tools().await?;
130
131        debug!(keyword = keyword, count = tools.len(), "Searching tools for keyword");
132
133        // Normalize the keyword once for the whole scan: scoring is
134        // case-insensitive for every candidate, so doing it per tool would
135        // repeat the identical allocation once per tool.
136        let keyword_lower = keyword.to_lowercase();
137
138        // Score by reference first. Only the truncated survivors below pay for
139        // owned clones of names/descriptions/schemas; cloning every match
140        // up front would discard most of that work at the 5-result cap.
141        let mut scored: Vec<(&McpToolInfo, f32)> = Vec::with_capacity(tools.len() / 4);
142        for tool in &tools {
143            let relevance_score = self.calculate_relevance(tool, &keyword_lower);
144
145            // Filter out tools with no relevance
146            if relevance_score > 0.0 {
147                scored.push((tool, relevance_score));
148            }
149        }
150
151        // Sort by relevance score (highest first). Stable sort preserves the
152        // original discovery order among tied scores, matching the previous
153        // clone-then-sort behavior exactly.
154        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal));
155
156        // Apply AGENTS.md compliance: limit to 5 results with overflow indication
157        let total_results = scored.len();
158        if total_results > 5 {
159            info!(
160                keyword = keyword,
161                matched = total_results,
162                displayed = 5,
163                overflow = total_results - 5,
164                detail_level = detail_level.as_str(),
165                "Tool search completed with overflow"
166            );
167            scored.truncate(5);
168        } else {
169            info!(
170                keyword = keyword,
171                matched = total_results,
172                detail_level = detail_level.as_str(),
173                "Tool search completed"
174            );
175        }
176
177        // Materialize owned results for the survivors only.
178        let mut results = Vec::with_capacity(scored.len());
179        for (tool, relevance_score) in scored {
180            // Only clone schemas when needed (Full detail level)
181            let (input_schema, output_schema) = match detail_level {
182                DetailLevel::Full => (Some(tool.input_schema.clone()), tool.output_schema.clone()),
183                _ => (None, None),
184            };
185
186            results.push(ToolDiscoveryResult {
187                name: tool.name.clone(),
188                provider: tool.provider.clone(),
189                description: tool.description.clone(),
190                relevance_score,
191                input_schema,
192                output_schema,
193            });
194        }
195
196        Ok(results)
197    }
198
199    /// Get detailed information about a specific tool.
200    pub async fn get_tool_detail(&self, tool_name: &str) -> Result<Option<ToolDiscoveryResult>> {
201        let tools = self.mcp_client.list_mcp_tools().await?;
202
203        for tool in tools {
204            if tool.name.eq_ignore_ascii_case(tool_name) {
205                return Ok(Some(ToolDiscoveryResult {
206                    name: tool.name.clone(),
207                    provider: tool.provider.clone(),
208                    description: tool.description.clone(),
209                    relevance_score: 1.0,
210                    input_schema: Some(tool.input_schema),
211                    output_schema: tool.output_schema,
212                }));
213            }
214        }
215
216        Ok(None)
217    }
218
219    /// List all available tools grouped by provider.
220    async fn list_tools_by_provider(&self) -> Result<Vec<(String, Vec<ToolDiscoveryResult>)>> {
221        let tools = self.mcp_client.list_mcp_tools().await?;
222
223        Ok(group_results_by_provider_preserving_order(tools.into_iter().map(|tool| ToolDiscoveryResult {
224            name: tool.name,
225            provider: tool.provider,
226            description: tool.description,
227            relevance_score: 1.0,
228            input_schema: None,
229            output_schema: None,
230        })))
231    }
232
233    /// Calculate relevance score for a tool against an already-normalized keyword.
234    ///
235    /// Uses fuzzy matching on name and description to score relevance.
236    /// `keyword_lower` must be pre-normalized with `str::to_lowercase`: callers
237    /// scan many tools with the same keyword, so normalization is hoisted out
238    /// of this per-tool routine. Each tool's name and description are lowered
239    /// once and reused across the containment and fuzzy checks.
240    fn calculate_relevance(&self, tool: &McpToolInfo, keyword_lower: &str) -> f32 {
241        // Exact name match: highest score
242        if tool.name.eq_ignore_ascii_case(keyword_lower) {
243            return 1.0;
244        }
245
246        let name_lower = tool.name.to_lowercase();
247
248        // Name contains keyword: high score
249        if name_lower.contains(keyword_lower) {
250            return 0.8;
251        }
252
253        let description_lower = tool.description.to_lowercase();
254
255        // Description contains keyword: medium-high score
256        if description_lower.contains(keyword_lower) {
257            return 0.6;
258        }
259
260        // Calculate fuzzy match score for partial matches
261        let name_fuzzy = self.fuzzy_score(&name_lower, keyword_lower);
262        if name_fuzzy > 0.3 {
263            return 0.5 * name_fuzzy;
264        }
265
266        // Fuzzy fallback for partial description matches
267        let desc_fuzzy = self.fuzzy_score(&description_lower, keyword_lower);
268        if desc_fuzzy > 0.2 {
269            return 0.3 * desc_fuzzy;
270        }
271
272        0.0
273    }
274
275    /// Sørensen-Dice bigram similarity score (0.0 to 1.0).
276    ///
277    /// Uses the battle-tested [`strsim`](https://docs.rs/strsim) implementation.
278    /// Handles partial and fuzzy matches more accurately than simple subsequence
279    /// matching for keywords in tool names and descriptions.
280    #[expect(
281        clippy::cast_possible_truncation,
282        reason = "Sørensen-Dice is normalized to the [0, 1] range, so the f32 score remains bounded."
283    )]
284    fn fuzzy_score(&self, haystack: &str, needle: &str) -> f32 {
285        if needle.is_empty() {
286            return 1.0;
287        }
288        if haystack.is_empty() {
289            return 0.0;
290        }
291        strsim::sorensen_dice(haystack, needle) as f32
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use serde_json::json;
299
300    fn mock_tool(provider: &str, name: &str, description: &str) -> McpToolInfo {
301        McpToolInfo {
302            name: name.to_string(),
303            description: description.to_string(),
304            provider: provider.to_string(),
305            input_schema: json!({}),
306            output_schema: None,
307            ui: None,
308            visibility: crate::types::McpToolVisibility::default(),
309        }
310    }
311
312    #[test]
313    fn fuzzy_score_exact_match() {
314        let discovery = ToolDiscovery::new(Arc::new(MockMcpClient::default()));
315        assert!((discovery.fuzzy_score("read_file", "read_file") - 1.0).abs() < f32::EPSILON);
316    }
317
318    #[test]
319    fn fuzzy_score_partial_match() {
320        // Sørensen-Dice for "read_file" vs "read": 3 shared bigrams / 11 total = 0.55
321        let discovery = ToolDiscovery::new(Arc::new(MockMcpClient::default()));
322        let score = discovery.fuzzy_score("read_file", "read");
323        assert!(score > 0.5 && score <= 1.0, "expected >0.5, got {score}");
324    }
325
326    #[test]
327    fn fuzzy_score_no_match() {
328        let discovery = ToolDiscovery::new(Arc::new(MockMcpClient::default()));
329        assert!(discovery.fuzzy_score("read_file", "xyz").abs() < f32::EPSILON);
330    }
331
332    #[test]
333    fn full_detail_json_includes_output_schema_only_when_advertised() {
334        let with_schema = ToolDiscoveryResult {
335            name: "ask".to_string(),
336            provider: "deepwiki".to_string(),
337            description: "Ask.".to_string(),
338            relevance_score: 1.0,
339            input_schema: Some(json!({"type": "object"})),
340            output_schema: Some(json!({"type": "object"})),
341        };
342        assert_eq!(with_schema.to_json(DetailLevel::Full)["output_schema"], json!({"type": "object"}));
343
344        let without_schema = ToolDiscoveryResult { output_schema: None, ..with_schema.clone() };
345        let full = without_schema.to_json(DetailLevel::Full);
346        assert!(full.get("output_schema").is_none(), "absent schema must stay absent");
347        assert!(
348            with_schema
349                .to_json(DetailLevel::NameAndDescription)
350                .get("output_schema")
351                .is_none(),
352            "compact levels must not carry schemas"
353        );
354    }
355
356    #[tokio::test]
357    async fn list_tools_by_provider_preserves_first_seen_provider_and_tool_order() {
358        let discovery = ToolDiscovery::new(Arc::new(MockMcpClient {
359            tools: vec![
360                mock_tool("gmail", "send_email", "Send an email."),
361                mock_tool("calendar", "create_event", "Create a calendar event."),
362                mock_tool("gmail", "read_email", "Read an email."),
363                mock_tool("docs", "search", "Search docs."),
364                mock_tool("calendar", "list_events", "List calendar events."),
365            ],
366        }));
367
368        let grouped = discovery.list_tools_by_provider().await.expect("grouped tools");
369
370        let providers = grouped.iter().map(|(provider, _)| provider.as_str()).collect::<Vec<_>>();
371        assert_eq!(providers, vec!["gmail", "calendar", "docs"]);
372
373        let tool_names = grouped
374            .into_iter()
375            .map(|(_, tools)| tools.into_iter().map(|tool| tool.name).collect::<Vec<_>>())
376            .collect::<Vec<_>>();
377        assert_eq!(
378            tool_names,
379            vec![
380                vec!["send_email".to_string(), "read_email".to_string()],
381                vec!["create_event".to_string(), "list_events".to_string()],
382                vec!["search".to_string()],
383            ]
384        );
385    }
386
387    // Mock for testing
388    #[derive(Default)]
389    struct MockMcpClient {
390        tools: Vec<McpToolInfo>,
391    }
392
393    #[tokio::test]
394    async fn search_tools_keyword_normalization_is_case_insensitive_and_stable() {
395        // Hoisting `keyword.to_lowercase()` out of the per-tool scoring loop
396        // must not change results: mixed-case queries are equivalent to their
397        // lowercase form, and uppercase tool text still matches.
398        let discovery = ToolDiscovery::new(Arc::new(MockMcpClient {
399            tools: vec![
400                mock_tool("prov", "ReadMail", "Read incoming MAIL."),
401                mock_tool("prov", "send_mail", "Send a message."),
402                mock_tool("prov", "calendar", "Show the calendar."),
403            ],
404        }));
405
406        fn keyed(results: Vec<ToolDiscoveryResult>) -> Vec<(String, f32)> {
407            results
408                .into_iter()
409                .map(|result| (result.name, result.relevance_score))
410                .collect()
411        }
412
413        let lowercase = keyed(discovery.search_tools("mail", DetailLevel::Full).await.expect("search tools"));
414        assert_eq!(lowercase.first().map(|(name, _)| name.as_str()), Some("ReadMail"));
415        assert_eq!(keyed(discovery.search_tools("MAIL", DetailLevel::Full).await.expect("search tools")), lowercase);
416        assert_eq!(keyed(discovery.search_tools("MaIl", DetailLevel::Full).await.expect("search tools")), lowercase);
417    }
418
419    #[tokio::test]
420    async fn search_tools_keeps_highest_scores_despite_late_position_and_ties() {
421        // Arrange: 8 tools scored through deterministic tiers only
422        // (exact name = 1.0, name-contains = 0.8, description-contains = 0.6).
423        // The best matches sit last, so keeping the first 5 would fail; the
424        // 0.8 three-way tie checks stable discovery order; the lone 0.6 must
425        // be truncated away. Fillers (`calendar`, `docs`) share at most one
426        // bigram with "mail" (Dice <= 0.2), staying below every tier above.
427        let discovery = ToolDiscovery::new(Arc::new(MockMcpClient {
428            tools: vec![
429                mock_tool("prov", "calendar", "Show the calendar."),
430                mock_tool("prov", "docs", "Search the docs."),
431                mock_tool("prov", "forward_mail", "Forward a message."),
432                mock_tool("prov", "send_mail", "Send a message."),
433                mock_tool("prov", "mail", "Mail things."),
434                mock_tool("prov", "read_mail", "Read a message."),
435                mock_tool("prov", "delete_mail", "Delete a message."),
436                mock_tool("prov", "archive", "Archive old mail threads."),
437            ],
438        }));
439
440        // Act.
441        let results = discovery.search_tools("mail", DetailLevel::Full).await.expect("search tools");
442
443        // Assert: truncation survivors in score order, ties in discovery order.
444        let names = results.iter().map(|result| result.name.as_str()).collect::<Vec<_>>();
445        assert_eq!(names, vec!["mail", "forward_mail", "send_mail", "read_mail", "delete_mail"]);
446        let scores = results.iter().map(|result| result.relevance_score).collect::<Vec<_>>();
447        assert_eq!(scores, vec![1.0, 0.8, 0.8, 0.8, 0.8]);
448        assert!(results.iter().all(|result| result.input_schema.is_some()));
449
450        // Compact levels keep the same survivors without cloning schemas.
451        let compact = discovery
452            .search_tools("mail", DetailLevel::NameAndDescription)
453            .await
454            .expect("compact search");
455        let compact_names = compact.iter().map(|result| result.name.as_str()).collect::<Vec<_>>();
456        assert_eq!(compact_names, names);
457        assert!(
458            compact
459                .iter()
460                .all(|result| result.input_schema.is_none() && result.output_schema.is_none())
461        );
462    }
463
464    #[async_trait::async_trait]
465    impl crate::McpToolExecutor for MockMcpClient {
466        async fn execute_mcp_tool(&self, _tool_name: &str, _args: &Value) -> Result<Value> {
467            Ok(Value::Null)
468        }
469
470        async fn list_mcp_tools(&self) -> Result<Vec<McpToolInfo>> {
471            Ok(self.tools.clone())
472        }
473
474        async fn has_mcp_tool(&self, _tool_name: &str) -> Result<bool> {
475            Ok(false)
476        }
477
478        fn get_status(&self) -> crate::McpClientStatus {
479            crate::McpClientStatus {
480                enabled: true,
481                provider_count: 0,
482                active_connections: 0,
483                configured_providers: vec![],
484            }
485        }
486    }
487}