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

use serde::{Deserialize, Serialize};

use crate::collision::analyze_collisions;
use crate::model::{
    round2, round4, AuditDiff, AuditReport, AuditSummary, Catalog, Dimension, Finding, Severity,
    Tier, ToolScore, SCHEMA_VERSION,
};
use crate::rules::evaluate_rules;

fn default_collision_threshold() -> f32 {
    0.72
}
fn default_sibling_threshold() -> f32 {
    0.50
}
fn default_shadow_threshold() -> f32 {
    0.30
}
fn default_max_tool_tokens() -> usize {
    250
}
fn default_max_catalog_tokens() -> usize {
    15_000
}
fn default_fail_on() -> Option<Severity> {
    Some(Severity::Error)
}
fn default_input_price_per_million() -> f32 {
    3.00
}
fn default_cached_price_per_million() -> f32 {
    0.30
}

/// Configuration governing rule thresholds, token cost pricing, and pass/fail gates for [`Auditor`].
///
/// Deserializes cleanly from partial JSON configuration files (e.g., `.mcp-vol.json`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditConfig {
    /// Pairwise composite similarity threshold that emits a `VOL014` collision error.
    #[serde(default = "default_collision_threshold")]
    pub collision_threshold: f32,
    /// Lower pairwise similarity threshold requiring sibling disambiguation (`VOL005`).
    #[serde(default = "default_sibling_threshold")]
    pub sibling_disambiguation_threshold: f32,
    /// Minimum similarity required alongside schema-cost asymmetry to flag shadowing (`VOL015`).
    #[serde(default = "default_shadow_threshold")]
    pub shadow_similarity_threshold: f32,
    /// Maximum recommended tokens for a single tool description (`VOL012`).
    #[serde(default = "default_max_tool_tokens")]
    pub max_tool_tokens: usize,
    /// Maximum recommended tokens for the entire serialized catalog (`VOL012`).
    #[serde(default = "default_max_catalog_tokens")]
    pub max_catalog_tokens: usize,
    /// Minimum severity that causes [`AuditReport::passed`] to become `false`.
    /// Set to `None` to never fail on findings.
    #[serde(default = "default_fail_on")]
    pub fail_on: Option<Severity>,
    /// Rule codes to suppress (e.g., `["VOL013"]`).
    #[serde(default)]
    pub disabled_rules: Vec<String>,
    /// Assumed LLM uncached input price in USD per 1M tokens (default `3.00`, Sonnet-class rate).
    #[serde(default = "default_input_price_per_million")]
    pub input_price_per_million_usd: f32,
    /// Assumed LLM prompt-cached read price in USD per 1M tokens (default `0.30`, 10% read rate).
    #[serde(default = "default_cached_price_per_million")]
    pub cached_price_per_million_usd: f32,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            collision_threshold: default_collision_threshold(),
            sibling_disambiguation_threshold: default_sibling_threshold(),
            shadow_similarity_threshold: default_shadow_threshold(),
            max_tool_tokens: default_max_tool_tokens(),
            max_catalog_tokens: default_max_catalog_tokens(),
            fail_on: default_fail_on(),
            disabled_rules: Vec::new(),
            input_price_per_million_usd: default_input_price_per_million(),
            cached_price_per_million_usd: default_cached_price_per_million(),
        }
    }
}

impl AuditConfig {
    /// Sets the `VOL014` pairwise collision similarity threshold (`0.0..=1.0`).
    #[must_use]
    pub fn with_collision_threshold(mut self, threshold: f32) -> Self {
        self.collision_threshold = threshold;
        self
    }

    /// Sets the `VOL005` sibling disambiguation similarity threshold (`0.0..=1.0`).
    #[must_use]
    pub fn with_sibling_disambiguation_threshold(mut self, threshold: f32) -> Self {
        self.sibling_disambiguation_threshold = threshold;
        self
    }

    /// Sets the per-tool description token budget for `VOL012`.
    #[must_use]
    pub fn with_max_tool_tokens(mut self, max_tokens: usize) -> Self {
        self.max_tool_tokens = max_tokens;
        self
    }

    /// Sets the catalog-wide serialized token budget for `VOL012`.
    #[must_use]
    pub fn with_max_catalog_tokens(mut self, max_tokens: usize) -> Self {
        self.max_catalog_tokens = max_tokens;
        self
    }

    /// Sets the minimum severity level that fails the audit gate.
    #[must_use]
    pub fn with_fail_on(mut self, severity: Option<Severity>) -> Self {
        self.fail_on = severity;
        self
    }

    /// Suppresses a specific rule ID (e.g. `"VOL013"`).
    #[must_use]
    pub fn disable_rule(mut self, code: impl Into<String>) -> Self {
        self.disabled_rules.push(code.into());
        self
    }

    /// Overrides the USD per 1M input token rate used for cost estimates (cached rate defaults to 10%).
    #[must_use]
    pub fn with_input_price_per_million(mut self, usd_per_million: f32) -> Self {
        self.input_price_per_million_usd = usd_per_million;
        self.cached_price_per_million_usd = usd_per_million * 0.10;
        self
    }
}

/// Deterministic, zero-LLM auditor for MCP tool catalogs.
#[derive(Debug, Clone, Default)]
pub struct Auditor {
    config: AuditConfig,
}

impl Auditor {
    /// Creates an auditor with custom configuration.
    #[must_use]
    pub fn new(config: AuditConfig) -> Self {
        Self { config }
    }

    /// Returns a reference to the active configuration.
    pub fn config(&self) -> &AuditConfig {
        &self.config
    }

    /// Runs all enabled `VOL001`–`VOL024` rules, pairwise collision analysis, shadowed-tool
    /// detection, token cost estimation, and TDQS-aligned 1.0–5.0 dimension scoring on `catalog`.
    #[must_use]
    pub fn audit(&self, catalog: &Catalog) -> AuditReport {
        let report_floor = self
            .config
            .sibling_disambiguation_threshold
            .min(self.config.collision_threshold);

        let collision_analysis = analyze_collisions(
            catalog,
            report_floor,
            self.config.shadow_similarity_threshold,
        );

        let mut findings = evaluate_rules(catalog, &collision_analysis.pairs, &self.config);
        for finding in &mut findings {
            if let Some(tool) = catalog.get(&finding.tool) {
                if finding.source_location.is_none() {
                    finding.source_location = tool.source_location.clone();
                }
                if finding.source_server.is_none() {
                    finding.source_server = tool.source_server.clone();
                }
            }
        }

        let mut tool_scores = Vec::with_capacity(catalog.len());
        let mut tool_fingerprints = BTreeMap::new();

        for tool in catalog.tools() {
            tool_fingerprints.insert(tool.name.clone(), tool.fingerprint());

            let mut dims: BTreeMap<Dimension, f32> =
                Dimension::ALL.into_iter().map(|d| (d, 5.0_f32)).collect();
            let mut errors = 0usize;
            let mut warnings = 0usize;
            let mut infos = 0usize;
            let mut hard_cap_purpose = false;
            let mut hard_cap_behavior = false;

            for f in &findings {
                let affects_tool = f.tool == tool.name
                    || (f.code == "VOL014"
                        && f.related_tool.as_deref() == Some(tool.name.as_str()));
                if !affects_tool {
                    continue;
                }
                let penalty = match f.severity {
                    Severity::Error => {
                        errors += 1;
                        2.5
                    }
                    Severity::Warn => {
                        warnings += 1;
                        1.5
                    }
                    Severity::Info => {
                        infos += 1;
                        0.5
                    }
                };
                if let Some(score) = dims.get_mut(&f.dimension) {
                    *score = (*score - penalty).clamp(1.0, 5.0);
                }
                if f.code == "VOL001" {
                    hard_cap_purpose = true;
                }
                if f.code == "VOL006" || f.code == "VOL019" {
                    hard_cap_behavior = true;
                }
            }

            if hard_cap_purpose {
                dims.insert(Dimension::PurposeClarity, 1.0);
            }
            if hard_cap_behavior {
                dims.insert(Dimension::BehavioralTransparency, 1.0);
            }

            let overall = round2(
                dims.iter()
                    .map(|(d, &s)| d.weight() * s)
                    .sum::<f32>()
                    .clamp(1.0, 5.0),
            );
            let rounded_dims: BTreeMap<Dimension, f32> =
                dims.into_iter().map(|(d, s)| (d, round2(s))).collect();

            tool_scores.push(ToolScore {
                tool: tool.name.clone(),
                overall,
                tier: Tier::from_score(overall),
                estimated_tokens: tool.estimated_total_tokens(),
                invocation_cost: tool.invocation_cost(),
                dimension_scores: rounded_dims,
                error_count: errors,
                warning_count: warnings,
                info_count: infos,
            });
        }

        tool_scores.sort_by(|a, b| a.tool.cmp(&b.tool));

        let mut catalog_dims = BTreeMap::new();
        for dim in Dimension::ALL {
            let mean = if tool_scores.is_empty() {
                5.0
            } else {
                let sum: f32 = tool_scores
                    .iter()
                    .map(|ts| ts.dimension_scores.get(&dim).copied().unwrap_or(5.0))
                    .sum();
                sum / tool_scores.len() as f32
            };
            catalog_dims.insert(dim, round2(mean));
        }

        // Apply catalog-level penalties if `<catalog>` triggered VOL012 or VOL017.
        for f in &findings {
            if f.tool == "<catalog>" {
                let pen = match f.severity {
                    Severity::Error => 2.5,
                    Severity::Warn => 1.5,
                    Severity::Info => 0.5,
                };
                if let Some(score) = catalog_dims.get_mut(&f.dimension) {
                    *score = round2((*score - pen).clamp(1.0, 5.0));
                }
            }
        }

        let weighted_mean = catalog_dims
            .iter()
            .map(|(d, &s)| d.weight() * s)
            .sum::<f32>()
            .clamp(1.0, 5.0);
        let worst_tool_score = tool_scores
            .iter()
            .map(|t| t.overall)
            .fold(5.0_f32, f32::min);
        // TDQS-aligned rollup: 70% weighted dimension mean + 30% worst-tool anchor.
        let overall_score =
            round2((0.70 * weighted_mean + 0.30 * worst_tool_score).clamp(1.0, 5.0));

        let error_count = findings
            .iter()
            .filter(|f| f.severity == Severity::Error)
            .count();
        let warning_count = findings
            .iter()
            .filter(|f| f.severity == Severity::Warn)
            .count();
        let info_count = findings
            .iter()
            .filter(|f| f.severity == Severity::Info)
            .count();
        let collision_count = collision_analysis
            .pairs
            .iter()
            .filter(|p| p.tool_a == p.tool_b || p.score >= self.config.collision_threshold)
            .count();
        let shadowing_count = collision_analysis
            .pairs
            .iter()
            .filter(|p| p.shadowing_risk)
            .count();

        let estimated_catalog_tokens = catalog.estimated_total_tokens();
        let tokens_m = (estimated_catalog_tokens as f32) / 1_000_000.0;
        let cost_per_turn = tokens_m * self.config.input_price_per_million_usd;
        let session_uncached = cost_per_turn * 200.0;
        let session_cached =
            cost_per_turn + (tokens_m * self.config.cached_price_per_million_usd * 199.0);

        let passed = match self.config.fail_on {
            None => true,
            Some(min_sev) => !findings.iter().any(|f| f.severity >= min_sev),
        };

        AuditReport {
            schema_version: SCHEMA_VERSION.into(),
            summary: AuditSummary {
                passed,
                tool_count: catalog.len(),
                estimated_catalog_tokens,
                estimated_cost_per_turn_usd: round4(cost_per_turn),
                estimated_200_turn_session_usd: round2(session_uncached),
                estimated_200_turn_cached_usd: round2(session_cached),
                overall_score,
                worst_tool_score: round2(worst_tool_score),
                tier: Tier::from_score(overall_score),
                error_count,
                warning_count,
                info_count,
                collision_count,
                shadowing_count,
            },
            dimension_scores: catalog_dims,
            tool_scores,
            findings,
            collisions: collision_analysis.pairs,
            tool_fingerprints,
        }
    }
}

/// Compares a baseline [`AuditReport`] against a newer report to detect quality regressions
/// and LLM prompt-cache-busting schema mutations.
#[must_use]
pub fn diff_reports(baseline: &AuditReport, current: &AuditReport) -> AuditDiff {
    let key = |f: &Finding| {
        (
            f.code.clone(),
            f.tool.clone(),
            f.related_tool.clone(),
            f.json_pointer.clone(),
        )
    };

    let base_keys: BTreeSet<_> = baseline.findings.iter().map(key).collect();
    let curr_keys: BTreeSet<_> = current.findings.iter().map(key).collect();

    let new_findings: Vec<Finding> = current
        .findings
        .iter()
        .filter(|f| !base_keys.contains(&key(f)))
        .cloned()
        .collect();
    let resolved_findings: Vec<Finding> = baseline
        .findings
        .iter()
        .filter(|f| !curr_keys.contains(&key(f)))
        .cloned()
        .collect();

    let mut added_tools = Vec::new();
    let mut removed_tools = Vec::new();
    let mut modified_tools = Vec::new();

    for (name, fp) in &current.tool_fingerprints {
        match baseline.tool_fingerprints.get(name) {
            None => added_tools.push(name.clone()),
            Some(old_fp) if old_fp != fp => modified_tools.push(name.clone()),
            Some(_) => {}
        }
    }
    for name in baseline.tool_fingerprints.keys() {
        if !current.tool_fingerprints.contains_key(name) {
            removed_tools.push(name.clone());
        }
    }

    added_tools.sort();
    removed_tools.sort();
    modified_tools.sort();

    let score_delta = round2(current.summary.overall_score - baseline.summary.overall_score);
    let token_delta = current.summary.estimated_catalog_tokens as i64
        - baseline.summary.estimated_catalog_tokens as i64;
    let session_cost_delta_usd = round2(
        current.summary.estimated_200_turn_session_usd
            - baseline.summary.estimated_200_turn_session_usd,
    );
    let error_delta = current.summary.error_count as i64 - baseline.summary.error_count as i64;
    let warning_delta =
        current.summary.warning_count as i64 - baseline.summary.warning_count as i64;
    let cache_busting_change =
        !added_tools.is_empty() || !removed_tools.is_empty() || !modified_tools.is_empty();
    let has_new_error = new_findings.iter().any(|f| f.severity == Severity::Error);
    let regressed = score_delta < -0.001 || error_delta > 0 || has_new_error;

    AuditDiff {
        schema_version: SCHEMA_VERSION.into(),
        score_delta,
        token_delta,
        session_cost_delta_usd,
        error_delta,
        warning_delta,
        new_findings,
        resolved_findings,
        added_tools,
        removed_tools,
        modified_tools,
        cache_busting_change,
        regressed,
    }
}