Skip to main content

mcp_vol/
ranker.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::model::{round4, Catalog, ToolSpec};
7use crate::schema::collect_schema_params;
8use crate::text::{char_trigrams, jaccard_sets, tokenize_semantic, tokenize_stemmed};
9
10/// Single ranked candidate returned by a [`Ranker`].
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct RankedTool {
13    /// Ranked tool name.
14    pub tool_name: String,
15    /// Relevance score assigned by the ranker (higher is better).
16    pub score: f32,
17}
18
19/// Pluggable tool-selection ranker used by [`crate::EvalSuite`].
20///
21/// Implement this trait to benchmark custom BM25 indices (such as `rmcp`'s upcoming
22/// `ToolSearchServer`), local embeddings, or LLM routers against the same test suite.
23#[diagnostic::on_unimplemented(
24    message = "`{Self}` does not implement `mcp_vol::Ranker`",
25    label = "expected a tool-selection ranker implementing `mcp_vol::Ranker`",
26    note = "use a built-in ranker (`&mcp_vol::Bm25Ranker::default()`, `&mcp_vol::TfIdfRanker::default()`, `&mcp_vol::HybridRanker::default()`) or implement `fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool>`"
27)]
28pub trait Ranker: Send + Sync {
29    /// Ranks tools in `catalog` for `query` and returns up to `top_k` candidates sorted best-first.
30    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool>;
31}
32
33/// Zero-dependency, field-weighted Okapi BM25 ranker tuned for MCP tool metadata.
34///
35/// Mirrors how large-catalog MCP tool search indexes rank tools over name, title,
36/// description, and parameter metadata.
37#[derive(Debug, Clone, Copy)]
38pub struct Bm25Ranker {
39    /// Term-frequency saturation parameter (default `1.5`).
40    pub k1: f32,
41    /// Document length normalization factor (default `0.75`).
42    pub b: f32,
43    /// Weight multiplier for tokens appearing in the tool name (default `3.0`).
44    pub name_weight: f32,
45    /// Weight multiplier for tokens appearing in the tool title (default `2.0`).
46    pub title_weight: f32,
47    /// Weight multiplier for tokens appearing in the tool description (default `1.5`).
48    pub description_weight: f32,
49    /// Weight multiplier for tokens appearing in parameter names & schema descriptions (default `1.0`).
50    pub parameter_weight: f32,
51}
52
53impl Default for Bm25Ranker {
54    fn default() -> Self {
55        Self {
56            k1: 1.5,
57            b: 0.75,
58            name_weight: 3.0,
59            title_weight: 2.0,
60            description_weight: 1.5,
61            parameter_weight: 1.0,
62        }
63    }
64}
65
66impl Bm25Ranker {
67    fn index_tool(&self, tool: &ToolSpec) -> (BTreeMap<String, f32>, f32) {
68        let mut tf: BTreeMap<String, f32> = BTreeMap::new();
69
70        add_weighted_terms(&mut tf, &tool.name, self.name_weight, true);
71        if let Some(title) = &tool.title {
72            add_weighted_terms(&mut tf, title, self.title_weight, true);
73        }
74        if let Some(desc) = &tool.description {
75            add_weighted_terms(&mut tf, desc, self.description_weight, true);
76        }
77        for param in collect_schema_params(&tool.input_schema) {
78            add_weighted_terms(&mut tf, &param.name, self.parameter_weight, false);
79            if let Some(pdesc) = param.schema.get("description").and_then(Value::as_str) {
80                add_weighted_terms(&mut tf, pdesc, self.parameter_weight * 0.75, false);
81            }
82        }
83
84        let doc_len: f32 = tf.values().sum();
85        (tf, doc_len)
86    }
87}
88
89impl Ranker for Bm25Ranker {
90    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
91        let tools = catalog.tools();
92        if tools.is_empty() || top_k == 0 {
93            return Vec::new();
94        }
95
96        let mut query_terms: Vec<String> = tokenize_stemmed(query);
97        for sem in tokenize_semantic(query) {
98            if !query_terms.contains(&sem) {
99                query_terms.push(sem);
100            }
101        }
102        if query_terms.is_empty() {
103            return Vec::new();
104        }
105
106        let indexed: Vec<(BTreeMap<String, f32>, f32)> =
107            tools.iter().map(|t| self.index_tool(t)).collect();
108        let n = tools.len() as f32;
109        let avg_dl = (indexed.iter().map(|(_, len)| *len).sum::<f32>() / n).max(1.0);
110
111        let unique_query: BTreeSet<&str> = query_terms.iter().map(String::as_str).collect();
112        let mut df_map: BTreeMap<&str, usize> = BTreeMap::new();
113        for &term in &unique_query {
114            let df = indexed
115                .iter()
116                .filter(|(tf, _)| tf.contains_key(term))
117                .count();
118            df_map.insert(term, df);
119        }
120
121        let mut scored: Vec<RankedTool> = tools
122            .iter()
123            .zip(indexed.iter())
124            .map(|(tool, (tf, dl))| {
125                let mut score = 0.0_f32;
126                for &term in &unique_query {
127                    let freq = tf.get(term).copied().unwrap_or(0.0);
128                    if freq <= 0.0 {
129                        continue;
130                    }
131                    let df = df_map.get(term).copied().unwrap_or(0) as f32;
132                    let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
133                    let denom = freq + self.k1 * (1.0 - self.b + self.b * (dl / avg_dl));
134                    score += idf * ((freq * (self.k1 + 1.0)) / denom);
135                }
136                RankedTool {
137                    tool_name: tool.name.clone(),
138                    score: round4(score),
139                }
140            })
141            .filter(|r| r.score > 0.0)
142            .collect();
143
144        scored.sort_by(|a, b| {
145            b.score
146                .total_cmp(&a.score)
147                .then_with(|| a.tool_name.cmp(&b.tool_name))
148        });
149        scored.truncate(top_k);
150        scored
151    }
152}
153
154/// Zero-dependency semantic TF-IDF cosine + character-trigram ranker.
155///
156/// Complements Okapi BM25 by normalizing aggressively for document length (preventing long
157/// verbose descriptions from drowning out concise tools) and capturing morphological/synonym
158/// similarity.
159#[derive(Debug, Clone, Copy)]
160pub struct TfIdfRanker {
161    /// Blend weight on character-trigram overlap against tool name + title (`0.0..=1.0`, default `0.20`).
162    pub trigram_weight: f32,
163}
164
165impl Default for TfIdfRanker {
166    fn default() -> Self {
167        Self {
168            trigram_weight: 0.20,
169        }
170    }
171}
172
173impl Ranker for TfIdfRanker {
174    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
175        let tools = catalog.tools();
176        if tools.is_empty() || top_k == 0 {
177            return Vec::new();
178        }
179
180        let query_tokens = tokenize_semantic(query);
181        if query_tokens.is_empty() {
182            return Vec::new();
183        }
184        let query_trigrams = char_trigrams(query);
185
186        let mut doc_bags: Vec<BTreeMap<String, f32>> = Vec::with_capacity(tools.len());
187        let mut df: BTreeMap<String, usize> = BTreeMap::new();
188
189        for tool in tools {
190            let mut bag: BTreeMap<String, f32> = BTreeMap::new();
191            for tok in tokenize_semantic(&tool.name) {
192                *bag.entry(tok).or_insert(0.0) += 3.0;
193            }
194            if let Some(title) = &tool.title {
195                for tok in tokenize_semantic(title) {
196                    *bag.entry(tok).or_insert(0.0) += 2.0;
197                }
198            }
199            if let Some(desc) = &tool.description {
200                for tok in tokenize_semantic(desc) {
201                    *bag.entry(tok).or_insert(0.0) += 1.0;
202                }
203            }
204            for param in collect_schema_params(&tool.input_schema) {
205                for tok in tokenize_semantic(&param.name) {
206                    *bag.entry(tok).or_insert(0.0) += 0.75;
207                }
208            }
209            for term in bag.keys() {
210                *df.entry(term.clone()).or_insert(0) += 1;
211            }
212            doc_bags.push(bag);
213        }
214
215        let n = tools.len() as f32;
216        let idf = |term: &str| -> f32 {
217            let d = df.get(term).copied().unwrap_or(0) as f32;
218            ((n + 1.0) / (d + 1.0)).ln() + 1.0
219        };
220
221        // Build query TF-IDF vector.
222        let mut q_tf: BTreeMap<String, f32> = BTreeMap::new();
223        for tok in query_tokens {
224            *q_tf.entry(tok).or_insert(0.0) += 1.0;
225        }
226        let mut q_vec: BTreeMap<String, f32> = BTreeMap::new();
227        let mut q_norm_sq = 0.0_f32;
228        for (term, tf) in q_tf {
229            let w = (1.0 + tf.ln()) * idf(&term);
230            q_norm_sq += w * w;
231            q_vec.insert(term, w);
232        }
233        let q_norm = q_norm_sq.sqrt();
234        if q_norm == 0.0 {
235            return Vec::new();
236        }
237
238        let mut scored: Vec<RankedTool> = tools
239            .iter()
240            .zip(doc_bags.iter())
241            .map(|(tool, bag)| {
242                let mut dot = 0.0_f32;
243                let mut d_norm_sq = 0.0_f32;
244                for (term, &tf) in bag {
245                    let w = (1.0 + tf.ln()) * idf(term);
246                    d_norm_sq += w * w;
247                    if let Some(&qw) = q_vec.get(term) {
248                        dot += w * qw;
249                    }
250                }
251                let cosine = if d_norm_sq > 0.0 {
252                    (dot / (q_norm * d_norm_sq.sqrt())).clamp(0.0, 1.0)
253                } else {
254                    0.0
255                };
256                let name_label = match &tool.title {
257                    Some(t) => format!("{} {t}", tool.name),
258                    None => tool.name.clone(),
259                };
260                let tri = jaccard_sets(&query_trigrams, &char_trigrams(&name_label));
261                let score = (1.0 - self.trigram_weight) * cosine + self.trigram_weight * tri;
262                RankedTool {
263                    tool_name: tool.name.clone(),
264                    score: round4(score),
265                }
266            })
267            .filter(|r| r.score > 0.0)
268            .collect();
269
270        scored.sort_by(|a, b| {
271            b.score
272                .total_cmp(&a.score)
273                .then_with(|| a.tool_name.cmp(&b.tool_name))
274        });
275        scored.truncate(top_k);
276        scored
277    }
278}
279
280/// Zero-dependency Reciprocal Rank Fusion (RRF) ranker combining [`Bm25Ranker`] and [`TfIdfRanker`].
281///
282/// Often outperforms pure BM25 on paraphrased natural-language queries while preserving exact
283/// keyword precision and remaining 100% deterministic with zero external models.
284#[derive(Debug, Clone, Copy)]
285pub struct HybridRanker {
286    /// Okapi BM25 leg.
287    pub bm25: Bm25Ranker,
288    /// Semantic TF-IDF + trigram leg.
289    pub tfidf: TfIdfRanker,
290    /// RRF smoothing constant (default `60.0`).
291    pub rrf_k: f32,
292}
293
294impl Default for HybridRanker {
295    fn default() -> Self {
296        Self {
297            bm25: Bm25Ranker::default(),
298            tfidf: TfIdfRanker::default(),
299            rrf_k: 60.0,
300        }
301    }
302}
303
304impl Ranker for HybridRanker {
305    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
306        if catalog.is_empty() || top_k == 0 {
307            return Vec::new();
308        }
309        let pool_k = catalog.len();
310        let bm25_ranked = self.bm25.rank(query, catalog, pool_k);
311        let tfidf_ranked = self.tfidf.rank(query, catalog, pool_k);
312
313        let mut fused: BTreeMap<String, f32> = BTreeMap::new();
314        for (idx, item) in bm25_ranked.into_iter().enumerate() {
315            *fused.entry(item.tool_name).or_insert(0.0) += 1.0 / (self.rrf_k + (idx as f32) + 1.0);
316        }
317        for (idx, item) in tfidf_ranked.into_iter().enumerate() {
318            *fused.entry(item.tool_name).or_insert(0.0) += 1.0 / (self.rrf_k + (idx as f32) + 1.0);
319        }
320
321        let mut scored: Vec<RankedTool> = fused
322            .into_iter()
323            .map(|(tool_name, score)| RankedTool {
324                tool_name,
325                score: round4(score),
326            })
327            .collect();
328
329        scored.sort_by(|a, b| {
330            b.score
331                .total_cmp(&a.score)
332                .then_with(|| a.tool_name.cmp(&b.tool_name))
333        });
334        scored.truncate(top_k);
335        scored
336    }
337}
338
339/// Precomputed inverted Okapi BM25 index for sub-millisecond tool search at scale (1,000+ tools).
340///
341/// Build once via [`Bm25Index::build`], then serve live `tools/search` queries via
342/// [`Bm25Index::search`] or pass directly to [`crate::EvalSuite::run`] (implements [`Ranker`]).
343///
344/// ```
345/// use mcp_vol::prelude::*;
346///
347/// let catalog = Catalog::from_mcp_json(
348///     r#"{"tools":[
349///       {"name":"read_file","description":"Reads a single UTF-8 file from disk.","inputSchema":{"type":"object"}},
350///       {"name":"list_branches","description":"Lists git branches in a repository.","inputSchema":{"type":"object"}}
351///     ]}"#
352/// ).unwrap();
353/// let index = Bm25Index::build(&catalog);
354/// let hits = index.search("list git branches", 1);
355/// assert_eq!(hits[0].tool_name, "list_branches");
356/// ```
357#[derive(Debug, Clone)]
358pub struct Bm25Index {
359    doc_names: Vec<String>,
360    /// Precomputed BM25 term contributions `(doc_id, weight)` per canonicalized term.
361    postings: BTreeMap<String, Vec<(u32, f32)>>,
362}
363
364impl Bm25Index {
365    /// Builds a precomputed BM25 inverted index with default field weights.
366    #[must_use]
367    pub fn build(catalog: &Catalog) -> Self {
368        Self::build_with_params(catalog, Bm25Ranker::default())
369    }
370
371    /// Builds a precomputed BM25 inverted index with custom [`Bm25Ranker`] weights.
372    #[must_use]
373    pub fn build_with_params(catalog: &Catalog, params: Bm25Ranker) -> Self {
374        let tools = catalog.tools();
375        let mut doc_names = Vec::with_capacity(tools.len());
376        let mut doc_lengths = Vec::with_capacity(tools.len());
377        let mut raw_postings: BTreeMap<String, Vec<(u32, f32)>> = BTreeMap::new();
378
379        for (doc_id, tool) in tools.iter().enumerate() {
380            let (tf, dl) = params.index_tool(tool);
381            doc_names.push(tool.name.clone());
382            doc_lengths.push(dl);
383            for (term, freq) in tf {
384                if freq > 0.0 {
385                    raw_postings
386                        .entry(term)
387                        .or_default()
388                        .push((doc_id as u32, freq));
389                }
390            }
391        }
392
393        let n = tools.len() as f32;
394        let avg_dl = if tools.is_empty() {
395            1.0
396        } else {
397            (doc_lengths.iter().sum::<f32>() / n).max(1.0)
398        };
399
400        let mut postings: BTreeMap<String, Vec<(u32, f32)>> = BTreeMap::new();
401        for (term, list) in raw_postings {
402            let df = list.len() as f32;
403            let term_idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
404            let weighted: Vec<(u32, f32)> = list
405                .into_iter()
406                .map(|(doc_id, freq)| {
407                    let dl = doc_lengths[doc_id as usize];
408                    let denom = freq + params.k1 * (1.0 - params.b + params.b * (dl / avg_dl));
409                    let weight = term_idf * ((freq * (params.k1 + 1.0)) / denom);
410                    (doc_id, weight)
411                })
412                .collect();
413            postings.insert(term, weighted);
414        }
415
416        Self {
417            doc_names,
418            postings,
419        }
420    }
421
422    /// Number of indexed tools.
423    pub fn len(&self) -> usize {
424        self.doc_names.len()
425    }
426
427    /// Returns `true` if no tools are indexed.
428    pub fn is_empty(&self) -> bool {
429        self.doc_names.is_empty()
430    }
431
432    /// Number of unique indexed terms in the inverted index.
433    pub fn vocabulary_size(&self) -> usize {
434        self.postings.len()
435    }
436
437    /// Queries the precomputed inverted index in `O(|query| * postings)` time and returns up to
438    /// `top_k` tools sorted descending by BM25 score.
439    #[must_use]
440    pub fn search(&self, query: &str, top_k: usize) -> Vec<RankedTool> {
441        if self.doc_names.is_empty() || top_k == 0 {
442            return Vec::new();
443        }
444        let unique_query = unique_query_terms(query);
445        if unique_query.is_empty() {
446            return Vec::new();
447        }
448
449        let mut scores = vec![0.0_f32; self.doc_names.len()];
450        let mut touched: Vec<u32> = Vec::new();
451
452        for term in &unique_query {
453            let Some(list) = self.postings.get(term) else {
454                continue;
455            };
456            for &(doc_id, weight) in list {
457                let idx = doc_id as usize;
458                if scores[idx] == 0.0 && weight > 0.0 {
459                    touched.push(doc_id);
460                }
461                scores[idx] += weight;
462            }
463        }
464
465        let mut candidates: Vec<(u32, f32)> = touched
466            .into_iter()
467            .filter_map(|doc_id| {
468                let s = scores[doc_id as usize];
469                (s > 0.0).then_some((doc_id, round4(s)))
470            })
471            .collect();
472
473        let cmp = |a: &(u32, f32), b: &(u32, f32)| {
474            b.1.total_cmp(&a.1)
475                .then_with(|| self.doc_names[a.0 as usize].cmp(&self.doc_names[b.0 as usize]))
476        };
477
478        if candidates.len() > top_k {
479            candidates.select_nth_unstable_by(top_k, cmp);
480            candidates.truncate(top_k);
481        }
482        candidates.sort_by(cmp);
483
484        candidates
485            .into_iter()
486            .map(|(doc_id, score)| RankedTool {
487                tool_name: self.doc_names[doc_id as usize].clone(),
488                score,
489            })
490            .collect()
491    }
492}
493
494impl Ranker for Bm25Index {
495    fn rank(&self, query: &str, _catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
496        self.search(query, top_k)
497    }
498}
499
500/// Per-term BM25 score contribution returned by [`explain_query`].
501#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
502pub struct TermContribution {
503    /// Canonicalized / stemmed query term.
504    pub term: String,
505    /// Inverse document frequency of this term across the catalog.
506    pub idf: f32,
507    /// Weighted term frequency within the candidate tool.
508    pub weighted_tf: f32,
509    /// BM25 score contribution from this term.
510    pub contribution: f32,
511    /// Metadata fields where this term matched (`name`, `title`, `description`, `parameters`).
512    pub matched_fields: Vec<String>,
513}
514
515/// Term-by-term ranking explanation for one candidate tool.
516#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
517pub struct ToolExplanation {
518    /// Candidate tool name.
519    pub tool_name: String,
520    /// Total BM25 relevance score.
521    pub score: f32,
522    /// Terms contributing positively to this candidate's score (sorted descending by contribution).
523    pub term_contributions: Vec<TermContribution>,
524    /// Query terms absent from this tool's metadata.
525    pub missing_query_terms: Vec<String>,
526}
527
528/// Full explainable routing diagnostic returned by [`explain_query`].
529#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
530pub struct QueryExplanation {
531    /// Raw input query string.
532    pub query: String,
533    /// Normalized query terms used for BM25 scoring.
534    pub query_terms: Vec<String>,
535    /// Query terms that matched zero tools in the entire catalog (vocabulary gaps).
536    pub unmatched_catalog_terms: Vec<String>,
537    /// Top-`k` ranked candidate tools with per-term & per-field score attribution.
538    pub candidates: Vec<ToolExplanation>,
539}
540
541impl QueryExplanation {
542    /// Formats a concise human/agent-readable breakdown of why tools ranked in this order.
543    pub fn to_text(&self) -> String {
544        let mut out = format!(
545            "mcp-vol explain: query=\"{}\" | terms=[{}]\n",
546            self.query,
547            self.query_terms.join(", ")
548        );
549        if !self.unmatched_catalog_terms.is_empty() {
550            out.push_str(&format!(
551                "unmatched catalog terms (0 tools): [{}]\n",
552                self.unmatched_catalog_terms.join(", ")
553            ));
554        }
555        for (idx, c) in self.candidates.iter().enumerate() {
556            let contribs: Vec<String> = c
557                .term_contributions
558                .iter()
559                .map(|t| {
560                    format!(
561                        "{}(+{:.3} via {})",
562                        t.term,
563                        t.contribution,
564                        t.matched_fields.join("/")
565                    )
566                })
567                .collect();
568            out.push_str(&format!(
569                "  #{}. {} (score={:.4}) — {}\n",
570                idx + 1,
571                c.tool_name,
572                c.score,
573                contribs.join(", ")
574            ));
575        }
576        out
577    }
578}
579
580/// Explains exactly why Okapi BM25 ranked the top-`k` tools for `query`, attributing score
581/// contributions to individual query terms and tool metadata fields (`name`, `title`,
582/// `description`, `parameters`).
583#[must_use]
584pub fn explain_query(
585    catalog: &Catalog,
586    query: &str,
587    params: Bm25Ranker,
588    top_k: usize,
589) -> QueryExplanation {
590    let query_terms = unique_query_terms(query);
591    let tools = catalog.tools();
592    if tools.is_empty() || query_terms.is_empty() || top_k == 0 {
593        return QueryExplanation {
594            query: query.to_string(),
595            query_terms: query_terms.clone(),
596            unmatched_catalog_terms: query_terms,
597            candidates: Vec::new(),
598        };
599    }
600
601    let indexed: Vec<(BTreeMap<String, f32>, f32)> =
602        tools.iter().map(|t| params.index_tool(t)).collect();
603    let n = tools.len() as f32;
604    let avg_dl = (indexed.iter().map(|(_, dl)| *dl).sum::<f32>() / n).max(1.0);
605
606    let mut df_map: BTreeMap<&str, usize> = BTreeMap::new();
607    let mut unmatched_catalog_terms = Vec::new();
608    for term in &query_terms {
609        let df = indexed
610            .iter()
611            .filter(|(tf, _)| tf.contains_key(term.as_str()))
612            .count();
613        df_map.insert(term.as_str(), df);
614        if df == 0 {
615            unmatched_catalog_terms.push(term.clone());
616        }
617    }
618
619    let mut candidates: Vec<ToolExplanation> = tools
620        .iter()
621        .zip(indexed.iter())
622        .filter_map(|(tool, (tf, dl))| {
623            let mut total = 0.0_f32;
624            let mut term_contributions = Vec::new();
625            let mut missing_query_terms = Vec::new();
626
627            let name_terms = field_term_set(&tool.name, true);
628            let title_terms = tool
629                .title
630                .as_deref()
631                .map(|t| field_term_set(t, true))
632                .unwrap_or_default();
633            let desc_terms = tool
634                .description
635                .as_deref()
636                .map(|d| field_term_set(d, true))
637                .unwrap_or_default();
638            let mut param_terms = BTreeSet::new();
639            for p in collect_schema_params(&tool.input_schema) {
640                param_terms.extend(field_term_set(&p.name, false));
641                if let Some(pd) = p.schema.get("description").and_then(Value::as_str) {
642                    param_terms.extend(field_term_set(pd, false));
643                }
644            }
645
646            for term in &query_terms {
647                let freq = tf.get(term.as_str()).copied().unwrap_or(0.0);
648                if freq <= 0.0 {
649                    missing_query_terms.push(term.clone());
650                    continue;
651                }
652                let df = df_map.get(term.as_str()).copied().unwrap_or(0) as f32;
653                let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
654                let denom = freq + params.k1 * (1.0 - params.b + params.b * (dl / avg_dl));
655                let contrib = idf * ((freq * (params.k1 + 1.0)) / denom);
656                total += contrib;
657
658                let mut matched_fields = Vec::new();
659                if name_terms.contains(term) {
660                    matched_fields.push("name".into());
661                }
662                if title_terms.contains(term) {
663                    matched_fields.push("title".into());
664                }
665                if desc_terms.contains(term) {
666                    matched_fields.push("description".into());
667                }
668                if param_terms.contains(term) {
669                    matched_fields.push("parameters".into());
670                }
671
672                term_contributions.push(TermContribution {
673                    term: term.clone(),
674                    idf: round4(idf),
675                    weighted_tf: round4(freq),
676                    contribution: round4(contrib),
677                    matched_fields,
678                });
679            }
680
681            if total <= 0.0 {
682                return None;
683            }
684            term_contributions.sort_by(|a, b| {
685                b.contribution
686                    .total_cmp(&a.contribution)
687                    .then_with(|| a.term.cmp(&b.term))
688            });
689            Some(ToolExplanation {
690                tool_name: tool.name.clone(),
691                score: round4(total),
692                term_contributions,
693                missing_query_terms,
694            })
695        })
696        .collect();
697
698    candidates.sort_by(|a, b| {
699        b.score
700            .total_cmp(&a.score)
701            .then_with(|| a.tool_name.cmp(&b.tool_name))
702    });
703    candidates.truncate(top_k);
704
705    QueryExplanation {
706        query: query.to_string(),
707        query_terms,
708        unmatched_catalog_terms,
709        candidates,
710    }
711}
712
713fn unique_query_terms(query: &str) -> Vec<String> {
714    let mut terms: BTreeSet<String> = tokenize_stemmed(query).into_iter().collect();
715    for sem in tokenize_semantic(query) {
716        terms.insert(sem);
717    }
718    terms.into_iter().collect()
719}
720
721fn field_term_set(text: &str, include_canonical: bool) -> BTreeSet<String> {
722    let mut set: BTreeSet<String> = tokenize_stemmed(text).into_iter().collect();
723    if include_canonical {
724        set.extend(tokenize_semantic(text));
725    }
726    set
727}
728
729fn add_weighted_terms(
730    tf: &mut BTreeMap<String, f32>,
731    text: &str,
732    weight: f32,
733    include_canonical: bool,
734) {
735    let stemmed = tokenize_stemmed(text);
736    for tok in &stemmed {
737        *tf.entry(tok.clone()).or_insert(0.0) += weight;
738    }
739    if include_canonical {
740        for sem in tokenize_semantic(text) {
741            if !stemmed.contains(&sem) {
742                *tf.entry(sem).or_insert(0.0) += weight * 0.75;
743            }
744        }
745    }
746}