mcp-vol 0.1.0

Zero-LLM, deterministic MCP tool linter (24 rules), static Rust/TS/Python scanner, multi-server composer, RFC 6902 patcher, and pre-indexed BM25 eval harness for rmcp and AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::model::{round4, Catalog, ToolSpec};
use crate::schema::collect_schema_params;
use crate::text::{char_trigrams, jaccard_sets, tokenize_semantic, tokenize_stemmed};

/// Single ranked candidate returned by a [`Ranker`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RankedTool {
    /// Ranked tool name.
    pub tool_name: String,
    /// Relevance score assigned by the ranker (higher is better).
    pub score: f32,
}

/// Pluggable tool-selection ranker used by [`crate::EvalSuite`].
///
/// Implement this trait to benchmark custom BM25 indices (such as `rmcp`'s upcoming
/// `ToolSearchServer`), local embeddings, or LLM routers against the same test suite.
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not implement `mcp_vol::Ranker`",
    label = "expected a tool-selection ranker implementing `mcp_vol::Ranker`",
    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>`"
)]
pub trait Ranker: Send + Sync {
    /// Ranks tools in `catalog` for `query` and returns up to `top_k` candidates sorted best-first.
    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool>;
}

/// Zero-dependency, field-weighted Okapi BM25 ranker tuned for MCP tool metadata.
///
/// Mirrors how large-catalog MCP tool search indexes rank tools over name, title,
/// description, and parameter metadata.
#[derive(Debug, Clone, Copy)]
pub struct Bm25Ranker {
    /// Term-frequency saturation parameter (default `1.5`).
    pub k1: f32,
    /// Document length normalization factor (default `0.75`).
    pub b: f32,
    /// Weight multiplier for tokens appearing in the tool name (default `3.0`).
    pub name_weight: f32,
    /// Weight multiplier for tokens appearing in the tool title (default `2.0`).
    pub title_weight: f32,
    /// Weight multiplier for tokens appearing in the tool description (default `1.5`).
    pub description_weight: f32,
    /// Weight multiplier for tokens appearing in parameter names & schema descriptions (default `1.0`).
    pub parameter_weight: f32,
}

impl Default for Bm25Ranker {
    fn default() -> Self {
        Self {
            k1: 1.5,
            b: 0.75,
            name_weight: 3.0,
            title_weight: 2.0,
            description_weight: 1.5,
            parameter_weight: 1.0,
        }
    }
}

impl Bm25Ranker {
    fn index_tool(&self, tool: &ToolSpec) -> (BTreeMap<String, f32>, f32) {
        let mut tf: BTreeMap<String, f32> = BTreeMap::new();

        add_weighted_terms(&mut tf, &tool.name, self.name_weight, true);
        if let Some(title) = &tool.title {
            add_weighted_terms(&mut tf, title, self.title_weight, true);
        }
        if let Some(desc) = &tool.description {
            add_weighted_terms(&mut tf, desc, self.description_weight, true);
        }
        for param in collect_schema_params(&tool.input_schema) {
            add_weighted_terms(&mut tf, &param.name, self.parameter_weight, false);
            if let Some(pdesc) = param.schema.get("description").and_then(Value::as_str) {
                add_weighted_terms(&mut tf, pdesc, self.parameter_weight * 0.75, false);
            }
        }

        let doc_len: f32 = tf.values().sum();
        (tf, doc_len)
    }
}

impl Ranker for Bm25Ranker {
    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
        let tools = catalog.tools();
        if tools.is_empty() || top_k == 0 {
            return Vec::new();
        }

        let mut query_terms: Vec<String> = tokenize_stemmed(query);
        for sem in tokenize_semantic(query) {
            if !query_terms.contains(&sem) {
                query_terms.push(sem);
            }
        }
        if query_terms.is_empty() {
            return Vec::new();
        }

        let indexed: Vec<(BTreeMap<String, f32>, f32)> =
            tools.iter().map(|t| self.index_tool(t)).collect();
        let n = tools.len() as f32;
        let avg_dl = (indexed.iter().map(|(_, len)| *len).sum::<f32>() / n).max(1.0);

        let unique_query: BTreeSet<&str> = query_terms.iter().map(String::as_str).collect();
        let mut df_map: BTreeMap<&str, usize> = BTreeMap::new();
        for &term in &unique_query {
            let df = indexed
                .iter()
                .filter(|(tf, _)| tf.contains_key(term))
                .count();
            df_map.insert(term, df);
        }

        let mut scored: Vec<RankedTool> = tools
            .iter()
            .zip(indexed.iter())
            .map(|(tool, (tf, dl))| {
                let mut score = 0.0_f32;
                for &term in &unique_query {
                    let freq = tf.get(term).copied().unwrap_or(0.0);
                    if freq <= 0.0 {
                        continue;
                    }
                    let df = df_map.get(term).copied().unwrap_or(0) as f32;
                    let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
                    let denom = freq + self.k1 * (1.0 - self.b + self.b * (dl / avg_dl));
                    score += idf * ((freq * (self.k1 + 1.0)) / denom);
                }
                RankedTool {
                    tool_name: tool.name.clone(),
                    score: round4(score),
                }
            })
            .filter(|r| r.score > 0.0)
            .collect();

        scored.sort_by(|a, b| {
            b.score
                .total_cmp(&a.score)
                .then_with(|| a.tool_name.cmp(&b.tool_name))
        });
        scored.truncate(top_k);
        scored
    }
}

/// Zero-dependency semantic TF-IDF cosine + character-trigram ranker.
///
/// Complements Okapi BM25 by normalizing aggressively for document length (preventing long
/// verbose descriptions from drowning out concise tools) and capturing morphological/synonym
/// similarity.
#[derive(Debug, Clone, Copy)]
pub struct TfIdfRanker {
    /// Blend weight on character-trigram overlap against tool name + title (`0.0..=1.0`, default `0.20`).
    pub trigram_weight: f32,
}

impl Default for TfIdfRanker {
    fn default() -> Self {
        Self {
            trigram_weight: 0.20,
        }
    }
}

impl Ranker for TfIdfRanker {
    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
        let tools = catalog.tools();
        if tools.is_empty() || top_k == 0 {
            return Vec::new();
        }

        let query_tokens = tokenize_semantic(query);
        if query_tokens.is_empty() {
            return Vec::new();
        }
        let query_trigrams = char_trigrams(query);

        let mut doc_bags: Vec<BTreeMap<String, f32>> = Vec::with_capacity(tools.len());
        let mut df: BTreeMap<String, usize> = BTreeMap::new();

        for tool in tools {
            let mut bag: BTreeMap<String, f32> = BTreeMap::new();
            for tok in tokenize_semantic(&tool.name) {
                *bag.entry(tok).or_insert(0.0) += 3.0;
            }
            if let Some(title) = &tool.title {
                for tok in tokenize_semantic(title) {
                    *bag.entry(tok).or_insert(0.0) += 2.0;
                }
            }
            if let Some(desc) = &tool.description {
                for tok in tokenize_semantic(desc) {
                    *bag.entry(tok).or_insert(0.0) += 1.0;
                }
            }
            for param in collect_schema_params(&tool.input_schema) {
                for tok in tokenize_semantic(&param.name) {
                    *bag.entry(tok).or_insert(0.0) += 0.75;
                }
            }
            for term in bag.keys() {
                *df.entry(term.clone()).or_insert(0) += 1;
            }
            doc_bags.push(bag);
        }

        let n = tools.len() as f32;
        let idf = |term: &str| -> f32 {
            let d = df.get(term).copied().unwrap_or(0) as f32;
            ((n + 1.0) / (d + 1.0)).ln() + 1.0
        };

        // Build query TF-IDF vector.
        let mut q_tf: BTreeMap<String, f32> = BTreeMap::new();
        for tok in query_tokens {
            *q_tf.entry(tok).or_insert(0.0) += 1.0;
        }
        let mut q_vec: BTreeMap<String, f32> = BTreeMap::new();
        let mut q_norm_sq = 0.0_f32;
        for (term, tf) in q_tf {
            let w = (1.0 + tf.ln()) * idf(&term);
            q_norm_sq += w * w;
            q_vec.insert(term, w);
        }
        let q_norm = q_norm_sq.sqrt();
        if q_norm == 0.0 {
            return Vec::new();
        }

        let mut scored: Vec<RankedTool> = tools
            .iter()
            .zip(doc_bags.iter())
            .map(|(tool, bag)| {
                let mut dot = 0.0_f32;
                let mut d_norm_sq = 0.0_f32;
                for (term, &tf) in bag {
                    let w = (1.0 + tf.ln()) * idf(term);
                    d_norm_sq += w * w;
                    if let Some(&qw) = q_vec.get(term) {
                        dot += w * qw;
                    }
                }
                let cosine = if d_norm_sq > 0.0 {
                    (dot / (q_norm * d_norm_sq.sqrt())).clamp(0.0, 1.0)
                } else {
                    0.0
                };
                let name_label = match &tool.title {
                    Some(t) => format!("{} {t}", tool.name),
                    None => tool.name.clone(),
                };
                let tri = jaccard_sets(&query_trigrams, &char_trigrams(&name_label));
                let score = (1.0 - self.trigram_weight) * cosine + self.trigram_weight * tri;
                RankedTool {
                    tool_name: tool.name.clone(),
                    score: round4(score),
                }
            })
            .filter(|r| r.score > 0.0)
            .collect();

        scored.sort_by(|a, b| {
            b.score
                .total_cmp(&a.score)
                .then_with(|| a.tool_name.cmp(&b.tool_name))
        });
        scored.truncate(top_k);
        scored
    }
}

/// Zero-dependency Reciprocal Rank Fusion (RRF) ranker combining [`Bm25Ranker`] and [`TfIdfRanker`].
///
/// Often outperforms pure BM25 on paraphrased natural-language queries while preserving exact
/// keyword precision and remaining 100% deterministic with zero external models.
#[derive(Debug, Clone, Copy)]
pub struct HybridRanker {
    /// Okapi BM25 leg.
    pub bm25: Bm25Ranker,
    /// Semantic TF-IDF + trigram leg.
    pub tfidf: TfIdfRanker,
    /// RRF smoothing constant (default `60.0`).
    pub rrf_k: f32,
}

impl Default for HybridRanker {
    fn default() -> Self {
        Self {
            bm25: Bm25Ranker::default(),
            tfidf: TfIdfRanker::default(),
            rrf_k: 60.0,
        }
    }
}

impl Ranker for HybridRanker {
    fn rank(&self, query: &str, catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
        if catalog.is_empty() || top_k == 0 {
            return Vec::new();
        }
        let pool_k = catalog.len();
        let bm25_ranked = self.bm25.rank(query, catalog, pool_k);
        let tfidf_ranked = self.tfidf.rank(query, catalog, pool_k);

        let mut fused: BTreeMap<String, f32> = BTreeMap::new();
        for (idx, item) in bm25_ranked.into_iter().enumerate() {
            *fused.entry(item.tool_name).or_insert(0.0) += 1.0 / (self.rrf_k + (idx as f32) + 1.0);
        }
        for (idx, item) in tfidf_ranked.into_iter().enumerate() {
            *fused.entry(item.tool_name).or_insert(0.0) += 1.0 / (self.rrf_k + (idx as f32) + 1.0);
        }

        let mut scored: Vec<RankedTool> = fused
            .into_iter()
            .map(|(tool_name, score)| RankedTool {
                tool_name,
                score: round4(score),
            })
            .collect();

        scored.sort_by(|a, b| {
            b.score
                .total_cmp(&a.score)
                .then_with(|| a.tool_name.cmp(&b.tool_name))
        });
        scored.truncate(top_k);
        scored
    }
}

/// Precomputed inverted Okapi BM25 index for sub-millisecond tool search at scale (1,000+ tools).
///
/// Build once via [`Bm25Index::build`], then serve live `tools/search` queries via
/// [`Bm25Index::search`] or pass directly to [`crate::EvalSuite::run`] (implements [`Ranker`]).
///
/// ```
/// use mcp_vol::prelude::*;
///
/// let catalog = Catalog::from_mcp_json(
///     r#"{"tools":[
///       {"name":"read_file","description":"Reads a single UTF-8 file from disk.","inputSchema":{"type":"object"}},
///       {"name":"list_branches","description":"Lists git branches in a repository.","inputSchema":{"type":"object"}}
///     ]}"#
/// ).unwrap();
/// let index = Bm25Index::build(&catalog);
/// let hits = index.search("list git branches", 1);
/// assert_eq!(hits[0].tool_name, "list_branches");
/// ```
#[derive(Debug, Clone)]
pub struct Bm25Index {
    doc_names: Vec<String>,
    /// Precomputed BM25 term contributions `(doc_id, weight)` per canonicalized term.
    postings: BTreeMap<String, Vec<(u32, f32)>>,
}

impl Bm25Index {
    /// Builds a precomputed BM25 inverted index with default field weights.
    #[must_use]
    pub fn build(catalog: &Catalog) -> Self {
        Self::build_with_params(catalog, Bm25Ranker::default())
    }

    /// Builds a precomputed BM25 inverted index with custom [`Bm25Ranker`] weights.
    #[must_use]
    pub fn build_with_params(catalog: &Catalog, params: Bm25Ranker) -> Self {
        let tools = catalog.tools();
        let mut doc_names = Vec::with_capacity(tools.len());
        let mut doc_lengths = Vec::with_capacity(tools.len());
        let mut raw_postings: BTreeMap<String, Vec<(u32, f32)>> = BTreeMap::new();

        for (doc_id, tool) in tools.iter().enumerate() {
            let (tf, dl) = params.index_tool(tool);
            doc_names.push(tool.name.clone());
            doc_lengths.push(dl);
            for (term, freq) in tf {
                if freq > 0.0 {
                    raw_postings
                        .entry(term)
                        .or_default()
                        .push((doc_id as u32, freq));
                }
            }
        }

        let n = tools.len() as f32;
        let avg_dl = if tools.is_empty() {
            1.0
        } else {
            (doc_lengths.iter().sum::<f32>() / n).max(1.0)
        };

        let mut postings: BTreeMap<String, Vec<(u32, f32)>> = BTreeMap::new();
        for (term, list) in raw_postings {
            let df = list.len() as f32;
            let term_idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
            let weighted: Vec<(u32, f32)> = list
                .into_iter()
                .map(|(doc_id, freq)| {
                    let dl = doc_lengths[doc_id as usize];
                    let denom = freq + params.k1 * (1.0 - params.b + params.b * (dl / avg_dl));
                    let weight = term_idf * ((freq * (params.k1 + 1.0)) / denom);
                    (doc_id, weight)
                })
                .collect();
            postings.insert(term, weighted);
        }

        Self {
            doc_names,
            postings,
        }
    }

    /// Number of indexed tools.
    pub fn len(&self) -> usize {
        self.doc_names.len()
    }

    /// Returns `true` if no tools are indexed.
    pub fn is_empty(&self) -> bool {
        self.doc_names.is_empty()
    }

    /// Number of unique indexed terms in the inverted index.
    pub fn vocabulary_size(&self) -> usize {
        self.postings.len()
    }

    /// Queries the precomputed inverted index in `O(|query| * postings)` time and returns up to
    /// `top_k` tools sorted descending by BM25 score.
    #[must_use]
    pub fn search(&self, query: &str, top_k: usize) -> Vec<RankedTool> {
        if self.doc_names.is_empty() || top_k == 0 {
            return Vec::new();
        }
        let unique_query = unique_query_terms(query);
        if unique_query.is_empty() {
            return Vec::new();
        }

        let mut scores = vec![0.0_f32; self.doc_names.len()];
        let mut touched: Vec<u32> = Vec::new();

        for term in &unique_query {
            let Some(list) = self.postings.get(term) else {
                continue;
            };
            for &(doc_id, weight) in list {
                let idx = doc_id as usize;
                if scores[idx] == 0.0 && weight > 0.0 {
                    touched.push(doc_id);
                }
                scores[idx] += weight;
            }
        }

        let mut candidates: Vec<(u32, f32)> = touched
            .into_iter()
            .filter_map(|doc_id| {
                let s = scores[doc_id as usize];
                (s > 0.0).then_some((doc_id, round4(s)))
            })
            .collect();

        let cmp = |a: &(u32, f32), b: &(u32, f32)| {
            b.1.total_cmp(&a.1)
                .then_with(|| self.doc_names[a.0 as usize].cmp(&self.doc_names[b.0 as usize]))
        };

        if candidates.len() > top_k {
            candidates.select_nth_unstable_by(top_k, cmp);
            candidates.truncate(top_k);
        }
        candidates.sort_by(cmp);

        candidates
            .into_iter()
            .map(|(doc_id, score)| RankedTool {
                tool_name: self.doc_names[doc_id as usize].clone(),
                score,
            })
            .collect()
    }
}

impl Ranker for Bm25Index {
    fn rank(&self, query: &str, _catalog: &Catalog, top_k: usize) -> Vec<RankedTool> {
        self.search(query, top_k)
    }
}

/// Per-term BM25 score contribution returned by [`explain_query`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TermContribution {
    /// Canonicalized / stemmed query term.
    pub term: String,
    /// Inverse document frequency of this term across the catalog.
    pub idf: f32,
    /// Weighted term frequency within the candidate tool.
    pub weighted_tf: f32,
    /// BM25 score contribution from this term.
    pub contribution: f32,
    /// Metadata fields where this term matched (`name`, `title`, `description`, `parameters`).
    pub matched_fields: Vec<String>,
}

/// Term-by-term ranking explanation for one candidate tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolExplanation {
    /// Candidate tool name.
    pub tool_name: String,
    /// Total BM25 relevance score.
    pub score: f32,
    /// Terms contributing positively to this candidate's score (sorted descending by contribution).
    pub term_contributions: Vec<TermContribution>,
    /// Query terms absent from this tool's metadata.
    pub missing_query_terms: Vec<String>,
}

/// Full explainable routing diagnostic returned by [`explain_query`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QueryExplanation {
    /// Raw input query string.
    pub query: String,
    /// Normalized query terms used for BM25 scoring.
    pub query_terms: Vec<String>,
    /// Query terms that matched zero tools in the entire catalog (vocabulary gaps).
    pub unmatched_catalog_terms: Vec<String>,
    /// Top-`k` ranked candidate tools with per-term & per-field score attribution.
    pub candidates: Vec<ToolExplanation>,
}

impl QueryExplanation {
    /// Formats a concise human/agent-readable breakdown of why tools ranked in this order.
    pub fn to_text(&self) -> String {
        let mut out = format!(
            "mcp-vol explain: query=\"{}\" | terms=[{}]\n",
            self.query,
            self.query_terms.join(", ")
        );
        if !self.unmatched_catalog_terms.is_empty() {
            out.push_str(&format!(
                "unmatched catalog terms (0 tools): [{}]\n",
                self.unmatched_catalog_terms.join(", ")
            ));
        }
        for (idx, c) in self.candidates.iter().enumerate() {
            let contribs: Vec<String> = c
                .term_contributions
                .iter()
                .map(|t| {
                    format!(
                        "{}(+{:.3} via {})",
                        t.term,
                        t.contribution,
                        t.matched_fields.join("/")
                    )
                })
                .collect();
            out.push_str(&format!(
                "  #{}. {} (score={:.4}) — {}\n",
                idx + 1,
                c.tool_name,
                c.score,
                contribs.join(", ")
            ));
        }
        out
    }
}

/// Explains exactly why Okapi BM25 ranked the top-`k` tools for `query`, attributing score
/// contributions to individual query terms and tool metadata fields (`name`, `title`,
/// `description`, `parameters`).
#[must_use]
pub fn explain_query(
    catalog: &Catalog,
    query: &str,
    params: Bm25Ranker,
    top_k: usize,
) -> QueryExplanation {
    let query_terms = unique_query_terms(query);
    let tools = catalog.tools();
    if tools.is_empty() || query_terms.is_empty() || top_k == 0 {
        return QueryExplanation {
            query: query.to_string(),
            query_terms: query_terms.clone(),
            unmatched_catalog_terms: query_terms,
            candidates: Vec::new(),
        };
    }

    let indexed: Vec<(BTreeMap<String, f32>, f32)> =
        tools.iter().map(|t| params.index_tool(t)).collect();
    let n = tools.len() as f32;
    let avg_dl = (indexed.iter().map(|(_, dl)| *dl).sum::<f32>() / n).max(1.0);

    let mut df_map: BTreeMap<&str, usize> = BTreeMap::new();
    let mut unmatched_catalog_terms = Vec::new();
    for term in &query_terms {
        let df = indexed
            .iter()
            .filter(|(tf, _)| tf.contains_key(term.as_str()))
            .count();
        df_map.insert(term.as_str(), df);
        if df == 0 {
            unmatched_catalog_terms.push(term.clone());
        }
    }

    let mut candidates: Vec<ToolExplanation> = tools
        .iter()
        .zip(indexed.iter())
        .filter_map(|(tool, (tf, dl))| {
            let mut total = 0.0_f32;
            let mut term_contributions = Vec::new();
            let mut missing_query_terms = Vec::new();

            let name_terms = field_term_set(&tool.name, true);
            let title_terms = tool
                .title
                .as_deref()
                .map(|t| field_term_set(t, true))
                .unwrap_or_default();
            let desc_terms = tool
                .description
                .as_deref()
                .map(|d| field_term_set(d, true))
                .unwrap_or_default();
            let mut param_terms = BTreeSet::new();
            for p in collect_schema_params(&tool.input_schema) {
                param_terms.extend(field_term_set(&p.name, false));
                if let Some(pd) = p.schema.get("description").and_then(Value::as_str) {
                    param_terms.extend(field_term_set(pd, false));
                }
            }

            for term in &query_terms {
                let freq = tf.get(term.as_str()).copied().unwrap_or(0.0);
                if freq <= 0.0 {
                    missing_query_terms.push(term.clone());
                    continue;
                }
                let df = df_map.get(term.as_str()).copied().unwrap_or(0) as f32;
                let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
                let denom = freq + params.k1 * (1.0 - params.b + params.b * (dl / avg_dl));
                let contrib = idf * ((freq * (params.k1 + 1.0)) / denom);
                total += contrib;

                let mut matched_fields = Vec::new();
                if name_terms.contains(term) {
                    matched_fields.push("name".into());
                }
                if title_terms.contains(term) {
                    matched_fields.push("title".into());
                }
                if desc_terms.contains(term) {
                    matched_fields.push("description".into());
                }
                if param_terms.contains(term) {
                    matched_fields.push("parameters".into());
                }

                term_contributions.push(TermContribution {
                    term: term.clone(),
                    idf: round4(idf),
                    weighted_tf: round4(freq),
                    contribution: round4(contrib),
                    matched_fields,
                });
            }

            if total <= 0.0 {
                return None;
            }
            term_contributions.sort_by(|a, b| {
                b.contribution
                    .total_cmp(&a.contribution)
                    .then_with(|| a.term.cmp(&b.term))
            });
            Some(ToolExplanation {
                tool_name: tool.name.clone(),
                score: round4(total),
                term_contributions,
                missing_query_terms,
            })
        })
        .collect();

    candidates.sort_by(|a, b| {
        b.score
            .total_cmp(&a.score)
            .then_with(|| a.tool_name.cmp(&b.tool_name))
    });
    candidates.truncate(top_k);

    QueryExplanation {
        query: query.to_string(),
        query_terms,
        unmatched_catalog_terms,
        candidates,
    }
}

fn unique_query_terms(query: &str) -> Vec<String> {
    let mut terms: BTreeSet<String> = tokenize_stemmed(query).into_iter().collect();
    for sem in tokenize_semantic(query) {
        terms.insert(sem);
    }
    terms.into_iter().collect()
}

fn field_term_set(text: &str, include_canonical: bool) -> BTreeSet<String> {
    let mut set: BTreeSet<String> = tokenize_stemmed(text).into_iter().collect();
    if include_canonical {
        set.extend(tokenize_semantic(text));
    }
    set
}

fn add_weighted_terms(
    tf: &mut BTreeMap<String, f32>,
    text: &str,
    weight: f32,
    include_canonical: bool,
) {
    let stemmed = tokenize_stemmed(text);
    for tok in &stemmed {
        *tf.entry(tok.clone()).or_insert(0.0) += weight;
    }
    if include_canonical {
        for sem in tokenize_semantic(text) {
            if !stemmed.contains(&sem) {
                *tf.entry(sem).or_insert(0.0) += weight * 0.75;
            }
        }
    }
}