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 tokens
219                .iter()
220                .any(|candidate| candidate.starts_with(token) || token.starts_with(candidate))
221            {
222                score += weight * 2;
223                matched[index] = true;
224            } else if value.contains(token) {
225                score += weight;
226                matched[index] = true;
227            }
228        }
229    }
230    let matched_count = matched.iter().filter(|matched| **matched).count();
231    if matched_count == 0 {
232        return None;
233    }
234    let coverage = matched_count as f32 / query_tokens.len() as f32;
235    if coverage < if query_tokens.len() <= 2 { 1.0 } else { 0.6 } && !phrase {
236        return None;
237    }
238    Some(
239        score
240            + if matched_count == query_tokens.len() {
241                25
242            } else {
243                10
244            },
245    )
246}
247
248fn normalize(value: &str) -> String {
249    let mut result = String::new();
250    let mut previous_lower = false;
251    for ch in value.chars() {
252        if ch.is_ascii_uppercase() && previous_lower {
253            result.push(' ');
254        }
255        if ch.is_ascii_alphanumeric() {
256            result.push(ch.to_ascii_lowercase());
257            previous_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
258        } else {
259            result.push(' ');
260            previous_lower = false;
261        }
262    }
263    result.split_whitespace().collect::<Vec<_>>().join(" ")
264}
265
266fn tokenize(value: &str) -> Vec<String> {
267    normalize(value)
268        .split_whitespace()
269        .map(str::to_string)
270        .collect()
271}
272
273#[cfg(test)]
274mod tests {
275    use serde_json::json;
276
277    use crate::{ConnectorTool, ToolAnnotations};
278
279    use super::*;
280
281    #[test]
282    fn ranks_exact_method_matches_first() {
283        let connectors = [ConnectorDescription {
284            name: "github".to_string(),
285            instructions: None,
286            tools: vec![ConnectorTool {
287                name: "listIssues".to_string(),
288                description: Some("List repository issues".to_string()),
289                input_schema: json!({"type": "object"}),
290                output_schema: None,
291                instructions: None,
292                examples: Vec::new(),
293                annotations: ToolAnnotations::default(),
294                policy: crate::ToolPolicy::default(),
295            }],
296        }];
297        let result = search("list issues", &connectors, &[]);
298        assert_eq!(result.results[0].path, "github.listIssues");
299        assert!(result.results[0].types.contains("listIssues"));
300    }
301}