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
use std::collections::{BTreeMap, BTreeSet};

use crate::model::{round4, Catalog, CollisionPair, ToolSpec};
use crate::text::{
    char_trigrams, infer_polarity, jaccard_sets, tokenize_raw, tokenize_semantic, ActionPolarity,
};

/// Result of running pairwise collision and shadowed-tool analysis over a [`Catalog`].
#[derive(Debug, Clone)]
pub(crate) struct CollisionAnalysis {
    /// All pairs with meaningful similarity (for sibling disambiguation & reporting).
    pub(crate) pairs: Vec<CollisionPair>,
}

/// Computes catalog-scoped TF-IDF cosine, name similarity, parameter overlap, and TDQS
/// shadowed-tool risk for every unique pair `(i, j)` in the catalog.
pub(crate) fn analyze_collisions(
    catalog: &Catalog,
    min_report_threshold: f32,
    shadow_similarity_threshold: f32,
) -> CollisionAnalysis {
    let tools = catalog.tools();
    let n = tools.len();
    if n < 2 {
        return CollisionAnalysis { pairs: Vec::new() };
    }

    // Build per-tool semantic token bags and document frequencies for catalog-scoped TF-IDF.
    let mut doc_term_counts: Vec<BTreeMap<String, usize>> = Vec::with_capacity(n);
    let mut doc_freq: BTreeMap<String, usize> = BTreeMap::new();
    let mut name_tokens: Vec<BTreeSet<String>> = Vec::with_capacity(n);
    let mut name_trigrams: Vec<BTreeSet<String>> = Vec::with_capacity(n);
    let mut param_sets: Vec<BTreeSet<String>> = Vec::with_capacity(n);
    let mut costs: Vec<usize> = Vec::with_capacity(n);
    let mut polarities: Vec<ActionPolarity> = Vec::with_capacity(n);

    for tool in tools {
        let mut bag = BTreeMap::new();
        for tok in tokenize_semantic(&tool.name) {
            *bag.entry(tok).or_insert(0) += 2;
        }
        if let Some(title) = &tool.title {
            for tok in tokenize_semantic(title) {
                *bag.entry(tok).or_insert(0) += 1;
            }
        }
        if let Some(desc) = &tool.description {
            for tok in tokenize_semantic(desc) {
                *bag.entry(tok).or_insert(0) += 1;
            }
        }
        for term in bag.keys() {
            *doc_freq.entry(term.clone()).or_insert(0) += 1;
        }
        doc_term_counts.push(bag);

        let nt: BTreeSet<String> = tokenize_semantic(&tool.name).into_iter().collect();
        name_tokens.push(nt);
        name_trigrams.push(char_trigrams(&tool.name));
        param_sets.push(
            tool.parameter_names()
                .into_iter()
                .map(|p| tokenize_raw(p).join("_"))
                .collect(),
        );
        costs.push(tool.invocation_cost());
        let ro = tool.annotations.as_ref().and_then(|a| a.read_only_hint);
        polarities.push(infer_polarity(&tool.name, ro));
    }

    // Smooth IDF: log((N + 1) / (df + 1)) + 1.0
    let idf: BTreeMap<String, f32> = doc_freq
        .iter()
        .map(|(term, &df)| {
            let val = (((n as f32) + 1.0) / ((df as f32) + 1.0)).ln() + 1.0;
            (term.clone(), val)
        })
        .collect();

    // Build TF-IDF vectors and norms.
    let tfidf_vecs: Vec<(BTreeMap<String, f32>, f32)> = doc_term_counts
        .iter()
        .map(|counts| {
            let mut vec = BTreeMap::new();
            let mut norm_sq = 0.0_f32;
            for (term, &tf) in counts {
                let w = (1.0 + (tf as f32).ln()) * idf.get(term).copied().unwrap_or(1.0);
                norm_sq += w * w;
                vec.insert(term.clone(), w);
            }
            (vec, norm_sq.sqrt())
        })
        .collect();

    let mut pairs = Vec::new();
    for i in 0..n {
        for j in (i + 1)..n {
            let a = &tools[i];
            let b = &tools[j];

            // Exact duplicate name gets 1.0 immediately.
            let exact_dup = a.name == b.name;

            let name_tok_sim = jaccard_sets(&name_tokens[i], &name_tokens[j]);
            let name_tri_sim = jaccard_sets(&name_trigrams[i], &name_trigrams[j]);
            let name_sim = if exact_dup {
                1.0
            } else {
                0.70 * name_tok_sim + 0.30 * name_tri_sim
            };

            let desc_sim = cosine_similarity(&tfidf_vecs[i], &tfidf_vecs[j]);
            let param_sim = jaccard_sets(&param_sets[i], &param_sets[j]);

            let mut composite = if exact_dup {
                1.0
            } else if param_sets[i].is_empty() && param_sets[j].is_empty() {
                0.45 * name_sim + 0.55 * desc_sim
            } else {
                0.35 * name_sim + 0.50 * desc_sim + 0.15 * param_sim
            };

            let opposite_polarity = matches!(
                (polarities[i], polarities[j]),
                (ActionPolarity::Read, ActionPolarity::Write)
                    | (ActionPolarity::Write, ActionPolarity::Read)
            );
            let create_vs_delete = (name_tokens[i].contains("create")
                && name_tokens[j].contains("delete"))
                || (name_tokens[i].contains("delete") && name_tokens[j].contains("create"));

            // Dampen opposite-polarity pairs (e.g. `get_issue` vs `delete_issue`) unless exact dup.
            if !exact_dup && opposite_polarity {
                composite *= 0.65;
            }

            let intent_sim = (0.40 * name_sim + 0.60 * desc_sim).max(composite);

            // TDQS deterministic shadowing prefilter: expensive >= 2 * cheap && expensive - cheap >= 4
            let (shadowing_risk, cheaper_tool, expensive_tool) =
                if opposite_polarity || create_vs_delete {
                    (false, None, None)
                } else {
                    detect_shadowing(
                        a,
                        costs[i],
                        b,
                        costs[j],
                        intent_sim,
                        shadow_similarity_threshold,
                    )
                };

            if composite >= min_report_threshold || shadowing_risk || exact_dup {
                let shared_terms = top_shared_terms(&doc_term_counts[i], &doc_term_counts[j], &idf);
                let (tool_a, tool_b) = if a.name <= b.name {
                    (a.name.clone(), b.name.clone())
                } else {
                    (b.name.clone(), a.name.clone())
                };
                pairs.push(CollisionPair {
                    tool_a,
                    tool_b,
                    score: round4(composite.clamp(0.0, 1.0)),
                    name_similarity: round4(name_sim.clamp(0.0, 1.0)),
                    description_similarity: round4(desc_sim.clamp(0.0, 1.0)),
                    param_overlap: round4(param_sim.clamp(0.0, 1.0)),
                    shared_terms,
                    shadowing_risk,
                    cheaper_tool,
                    expensive_tool,
                });
            }
        }
    }

    // Deterministic descending sort by similarity score, then tool names.
    pairs.sort_by(|x, y| {
        y.score
            .total_cmp(&x.score)
            .then_with(|| x.tool_a.cmp(&y.tool_a))
            .then_with(|| x.tool_b.cmp(&y.tool_b))
    });

    CollisionAnalysis { pairs }
}

fn cosine_similarity(a: &(BTreeMap<String, f32>, f32), b: &(BTreeMap<String, f32>, f32)) -> f32 {
    if a.1 == 0.0 || b.1 == 0.0 {
        return 0.0;
    }
    let mut dot = 0.0_f32;
    for (term, &wa) in &a.0 {
        if let Some(&wb) = b.0.get(term) {
            dot += wa * wb;
        }
    }
    (dot / (a.1 * b.1)).clamp(0.0, 1.0)
}

fn top_shared_terms(
    a: &BTreeMap<String, usize>,
    b: &BTreeMap<String, usize>,
    idf: &BTreeMap<String, f32>,
) -> Vec<String> {
    let mut scored: Vec<(String, f32)> = a
        .keys()
        .filter(|k| b.contains_key(*k))
        .map(|k| (k.clone(), idf.get(k).copied().unwrap_or(1.0)))
        .collect();
    scored.sort_by(|x, y| y.1.total_cmp(&x.1).then_with(|| x.0.cmp(&y.0)));
    scored.into_iter().take(6).map(|(t, _)| t).collect()
}

fn detect_shadowing(
    a: &ToolSpec,
    cost_a: usize,
    b: &ToolSpec,
    cost_b: usize,
    similarity: f32,
    similarity_threshold: f32,
) -> (bool, Option<String>, Option<String>) {
    if similarity < similarity_threshold || a.name == b.name {
        return (false, None, None);
    }
    let (cheap, cheap_cost, expensive, expensive_cost) = if cost_a <= cost_b {
        (a, cost_a, b, cost_b)
    } else {
        (b, cost_b, a, cost_a)
    };

    let asymmetric =
        expensive_cost >= 2 * cheap_cost && expensive_cost.saturating_sub(cheap_cost) >= 4;
    if !asymmetric {
        return (false, None, None);
    }

    // If the cheaper tool explicitly names the heavier tool to direct filtered queries, no risk.
    let cheap_desc_lower = cheap
        .description
        .as_deref()
        .unwrap_or_default()
        .to_lowercase();
    if cheap_desc_lower.contains(&expensive.name.to_lowercase()) {
        return (false, None, None);
    }

    (true, Some(cheap.name.clone()), Some(expensive.name.clone()))
}