Skip to main content

multicast_codemode/
search.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{ConnectorDescription, Snippet, generate_types};
4
5const LIMIT: usize = 50;
6
7/// One ranked connector method or snippet match.
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9pub struct SearchResult {
10    /// Address used with describe or run.
11    pub path: String,
12    /// Connector namespace, or `snippet`.
13    pub connector: String,
14    /// Connector method or snippet name.
15    pub method: String,
16    /// Human-readable description.
17    pub description: Option<String>,
18    /// TypeScript declarations or snippet source needed to use the match.
19    pub types: String,
20    /// Whether invocation pauses for approval.
21    pub requires_approval: bool,
22    /// Match kind.
23    pub kind: String,
24    /// Weighted relevance score.
25    pub score: u32,
26}
27
28/// Bounded ranked search response.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct SearchOutput {
31    /// Ranked matches.
32    pub results: Vec<SearchResult>,
33    /// Total matches before limiting.
34    pub total: usize,
35    /// Whether matches were omitted.
36    pub truncated: bool,
37}
38
39/// Documentation for one connector, method, or snippet.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct DescribeOutput {
42    /// Resolved path.
43    pub path: String,
44    /// Human-readable description.
45    pub description: Option<String>,
46    /// Whether invocation pauses for approval.
47    pub requires_approval: bool,
48    /// TypeScript declarations or snippet source.
49    pub types: String,
50    /// Target kind.
51    pub kind: String,
52}
53
54/// Searches connector methods and saved snippets with weighted token matching.
55pub fn search(
56    query: &str,
57    connectors: &[ConnectorDescription],
58    snippets: &[Snippet],
59) -> SearchOutput {
60    let normalized = normalize(query);
61    let tokens = tokenize(query);
62    let mut results = Vec::new();
63    for connector in connectors {
64        for tool in &connector.tools {
65            let path = format!("{}.{}", connector.name, tool.name);
66            if let Some(score) = score(
67                &normalized,
68                &tokens,
69                [
70                    (&path, 12),
71                    (&connector.name, 8),
72                    (&tool.name, 10),
73                    (tool.description.as_deref().unwrap_or_default(), 5),
74                ],
75            ) {
76                results.push(SearchResult {
77                    path,
78                    connector: connector.name.clone(),
79                    method: tool.name.clone(),
80                    description: tool.description.clone(),
81                    types: {
82                        let mut single = connector.clone();
83                        single.instructions = None;
84                        single.tools = vec![tool.clone()];
85                        generate_types(&single)
86                    },
87                    requires_approval: tool.policy.requires_approval,
88                    kind: "method".to_string(),
89                    score,
90                });
91            }
92        }
93    }
94    for snippet in snippets {
95        if let Some(score) = score(
96            &normalized,
97            &tokens,
98            [
99                (&snippet.name, 12),
100                ("snippet", 8),
101                (&snippet.name, 10),
102                (&snippet.description, 5),
103            ],
104        ) {
105            results.push(SearchResult {
106                path: snippet.name.clone(),
107                connector: "snippet".to_string(),
108                method: snippet.name.clone(),
109                description: Some(snippet.description.clone()),
110                types: snippet.code.clone(),
111                requires_approval: false,
112                kind: "snippet".to_string(),
113                score,
114            });
115        }
116    }
117    results.extend(crate::workflow_api::matches(query));
118    results.sort_by(|left, right| {
119        right
120            .score
121            .cmp(&left.score)
122            .then_with(|| left.path.cmp(&right.path))
123    });
124    let total = results.len();
125    results.truncate(LIMIT);
126    SearchOutput {
127        results,
128        total,
129        truncated: total > LIMIT,
130    }
131}
132
133/// Describes one connector, method, or saved snippet.
134pub fn describe(
135    target: &str,
136    connectors: &[ConnectorDescription],
137    snippets: &[Snippet],
138) -> DescribeOutput {
139    if let Some(description) = crate::workflow_api::description(target) {
140        return description;
141    }
142    if let Some(snippet) = snippets.iter().find(|snippet| snippet.name == target) {
143        return DescribeOutput {
144            path: target.to_string(),
145            description: Some(snippet.description.clone()),
146            requires_approval: false,
147            types: format!("{}\n\n```ts\n{}\n```", snippet.description, snippet.code),
148            kind: "snippet".to_string(),
149        };
150    }
151    let (connector_name, method_name) = target
152        .split_once('.')
153        .map(|(connector, method)| (Some(connector), method))
154        .unwrap_or((None, target));
155    if connector_name.is_none()
156        && let Some(connector) = connectors.iter().find(|connector| connector.name == target)
157    {
158        return DescribeOutput {
159            path: target.to_string(),
160            description: connector.instructions.clone(),
161            requires_approval: false,
162            types: generate_types(connector),
163            kind: "connector".to_string(),
164        };
165    }
166    for connector in connectors
167        .iter()
168        .filter(|connector| connector_name.is_none_or(|name| connector.name == name))
169    {
170        if let Some(tool) = connector.tools.iter().find(|tool| tool.name == method_name) {
171            let mut single = connector.clone();
172            single.instructions = None;
173            single.tools = vec![tool.clone()];
174            return DescribeOutput {
175                path: format!("{}.{}", connector.name, tool.name),
176                description: tool.description.clone(),
177                requires_approval: tool.policy.requires_approval,
178                types: generate_types(&single),
179                kind: "method".to_string(),
180            };
181        }
182    }
183    DescribeOutput {
184        path: target.to_string(),
185        description: None,
186        requires_approval: false,
187        types: format!("\"{target}\" not found."),
188        kind: "method".to_string(),
189    }
190}
191
192fn score<const COUNT: usize>(
193    query: &str,
194    query_tokens: &[String],
195    fields: [(&str, u32); COUNT],
196) -> Option<u32> {
197    if query.is_empty() || query_tokens.is_empty() {
198        return None;
199    }
200    let mut score = 0;
201    let mut matched = vec![false; query_tokens.len()];
202    let mut phrase = false;
203    for (value, weight) in fields {
204        let value = normalize(value);
205        let tokens = tokenize(&value);
206        if value == query {
207            score += weight * 14;
208        } else if value.starts_with(query) {
209            score += weight * 9;
210        } else if value.contains(query) {
211            score += weight * 6;
212            phrase = true;
213        }
214        for (index, token) in query_tokens.iter().enumerate() {
215            if tokens.contains(token) {
216                score += weight * 4;
217                matched[index] = true;
218            } else if token.len() > 1
219                && tokens.iter().any(|candidate| {
220                    candidate.len() > 1
221                        && (candidate.starts_with(token) || token.starts_with(candidate))
222                })
223            {
224                // A one-letter word ("I" in "I'm", "a") matches only itself; as a prefix it
225                // would match every word starting with that letter.
226                score += weight * 2;
227                matched[index] = true;
228            } else if token.len() > 1 && value.contains(token) {
229                score += weight;
230                matched[index] = true;
231            }
232        }
233    }
234    let matched_count = matched.iter().filter(|matched| **matched).count();
235    if matched_count == 0 {
236        return None;
237    }
238    let coverage = matched_count as f32 / query_tokens.len() as f32;
239    if coverage < if query_tokens.len() <= 2 { 1.0 } else { 0.6 } && !phrase {
240        return None;
241    }
242    Some(
243        score
244            + if matched_count == query_tokens.len() {
245                FULL_COVERAGE_BONUS + FULL_COVERAGE_PER_WORD * query_tokens.len() as u32
246            } else {
247                10
248            },
249    )
250}
251
252/// A tool that answers every word of the question outranks one that only shares a strong word
253/// in its name; the bonus grows with the question, since covering more words is rarer.
254const FULL_COVERAGE_BONUS: u32 = 25;
255const FULL_COVERAGE_PER_WORD: u32 = 15;
256
257fn normalize(value: &str) -> String {
258    let mut result = String::new();
259    let mut previous_lower = false;
260    for ch in value.chars() {
261        if ch.is_ascii_uppercase() && previous_lower {
262            result.push(' ');
263        }
264        if ch.is_ascii_alphanumeric() {
265            result.push(ch.to_ascii_lowercase());
266            previous_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
267        } else {
268            result.push(' ');
269            previous_lower = false;
270        }
271    }
272    result.split_whitespace().collect::<Vec<_>>().join(" ")
273}
274
275fn tokenize(value: &str) -> Vec<String> {
276    normalize(value)
277        .split_whitespace()
278        .map(str::to_string)
279        .collect()
280}
281
282#[cfg(test)]
283mod tests {
284    use serde_json::json;
285
286    use crate::{ConnectorTool, ToolAnnotations};
287
288    use super::*;
289
290    fn tool(name: &str, description: &str) -> ConnectorTool {
291        ConnectorTool {
292            name: name.to_string(),
293            description: Some(description.to_string()),
294            input_schema: json!({"type": "object"}),
295            output_schema: None,
296            instructions: None,
297            examples: Vec::new(),
298            annotations: ToolAnnotations::default(),
299            policy: crate::ToolPolicy::default(),
300        }
301    }
302
303    fn ranked(query: &str, tools: Vec<ConnectorTool>) -> Vec<String> {
304        let connectors = [ConnectorDescription {
305            name: "game".to_string(),
306            instructions: None,
307            tools,
308        }];
309        search(query, &connectors, &[])
310            .results
311            .into_iter()
312            .map(|result| result.method)
313            .collect()
314    }
315
316    #[test]
317    fn one_letter_words_match_only_themselves() {
318        let tools = vec![
319            tool("mapItem", "Where an item comes from: mobs that drop it"),
320            tool("flee", "Escape when I'm losing a fight"),
321        ];
322        // "I'm" splits into "i" and "m"; they must not match "item" and "map".
323        let losing = ranked("I'm losing", tools.clone());
324        assert_eq!(losing[0], "flee");
325        assert!(!losing.contains(&"mapItem".to_string()), "{losing:?}");
326        // A one-letter word still matches the same one-letter word.
327        let letters = ranked("i m", tools);
328        assert_eq!(letters[0], "flee");
329        assert!(!letters.contains(&"mapItem".to_string()), "{letters:?}");
330        // Nor does a one-letter word match inside a longer word by substring.
331        let item = ranked("a item", vec![tool("mapItem", "Where things come from")]);
332        assert!(!item.contains(&"mapItem".to_string()), "{item:?}");
333        // A one-letter word in a tool's text is not a prefix of a longer question word.
334        let lore = ranked("losing", vec![tool("lore", "Read chapter L of the story")]);
335        assert!(!lore.contains(&"lore".to_string()), "{lore:?}");
336    }
337
338    #[test]
339    fn a_tool_covering_every_question_word_outranks_a_name_match() {
340        let tools = vec![
341            tool(
342                "levelGuide",
343                "Leveling facts: the spell a chain teaches at 10",
344            ),
345            tool(
346                "classHelp",
347                "What spells do I learn at each level, like the level 10 quest",
348            ),
349        ];
350        assert_eq!(ranked("what spells at level 10", tools)[0], "classHelp");
351    }
352
353    #[test]
354    fn ranks_exact_method_matches_first() {
355        let connectors = [ConnectorDescription {
356            name: "github".to_string(),
357            instructions: None,
358            tools: vec![ConnectorTool {
359                name: "listIssues".to_string(),
360                description: Some("List repository issues".to_string()),
361                input_schema: json!({"type": "object"}),
362                output_schema: None,
363                instructions: None,
364                examples: Vec::new(),
365                annotations: ToolAnnotations::default(),
366                policy: crate::ToolPolicy::default(),
367            }],
368        }];
369        let result = search("list issues", &connectors, &[]);
370        assert_eq!(result.results[0].path, "github.listIssues");
371        assert!(result.results[0].types.contains("listIssues"));
372    }
373}