Skip to main content

mcp_vol/
auditor.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use serde::{Deserialize, Serialize};
4
5use crate::collision::analyze_collisions;
6use crate::model::{
7    round2, round4, AuditDiff, AuditReport, AuditSummary, Catalog, Dimension, Finding, Severity,
8    Tier, ToolScore, SCHEMA_VERSION,
9};
10use crate::rules::evaluate_rules;
11
12fn default_collision_threshold() -> f32 {
13    0.72
14}
15fn default_sibling_threshold() -> f32 {
16    0.50
17}
18fn default_shadow_threshold() -> f32 {
19    0.30
20}
21fn default_max_tool_tokens() -> usize {
22    250
23}
24fn default_max_catalog_tokens() -> usize {
25    15_000
26}
27fn default_fail_on() -> Option<Severity> {
28    Some(Severity::Error)
29}
30fn default_input_price_per_million() -> f32 {
31    3.00
32}
33fn default_cached_price_per_million() -> f32 {
34    0.30
35}
36
37/// Configuration governing rule thresholds, token cost pricing, and pass/fail gates for [`Auditor`].
38///
39/// Deserializes cleanly from partial JSON configuration files (e.g., `.mcp-vol.json`).
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct AuditConfig {
42    /// Pairwise composite similarity threshold that emits a `VOL014` collision error.
43    #[serde(default = "default_collision_threshold")]
44    pub collision_threshold: f32,
45    /// Lower pairwise similarity threshold requiring sibling disambiguation (`VOL005`).
46    #[serde(default = "default_sibling_threshold")]
47    pub sibling_disambiguation_threshold: f32,
48    /// Minimum similarity required alongside schema-cost asymmetry to flag shadowing (`VOL015`).
49    #[serde(default = "default_shadow_threshold")]
50    pub shadow_similarity_threshold: f32,
51    /// Maximum recommended tokens for a single tool description (`VOL012`).
52    #[serde(default = "default_max_tool_tokens")]
53    pub max_tool_tokens: usize,
54    /// Maximum recommended tokens for the entire serialized catalog (`VOL012`).
55    #[serde(default = "default_max_catalog_tokens")]
56    pub max_catalog_tokens: usize,
57    /// Minimum severity that causes [`AuditReport::passed`] to become `false`.
58    /// Set to `None` to never fail on findings.
59    #[serde(default = "default_fail_on")]
60    pub fail_on: Option<Severity>,
61    /// Rule codes to suppress (e.g., `["VOL013"]`).
62    #[serde(default)]
63    pub disabled_rules: Vec<String>,
64    /// Assumed LLM uncached input price in USD per 1M tokens (default `3.00`, Sonnet-class rate).
65    #[serde(default = "default_input_price_per_million")]
66    pub input_price_per_million_usd: f32,
67    /// Assumed LLM prompt-cached read price in USD per 1M tokens (default `0.30`, 10% read rate).
68    #[serde(default = "default_cached_price_per_million")]
69    pub cached_price_per_million_usd: f32,
70}
71
72impl Default for AuditConfig {
73    fn default() -> Self {
74        Self {
75            collision_threshold: default_collision_threshold(),
76            sibling_disambiguation_threshold: default_sibling_threshold(),
77            shadow_similarity_threshold: default_shadow_threshold(),
78            max_tool_tokens: default_max_tool_tokens(),
79            max_catalog_tokens: default_max_catalog_tokens(),
80            fail_on: default_fail_on(),
81            disabled_rules: Vec::new(),
82            input_price_per_million_usd: default_input_price_per_million(),
83            cached_price_per_million_usd: default_cached_price_per_million(),
84        }
85    }
86}
87
88impl AuditConfig {
89    /// Sets the `VOL014` pairwise collision similarity threshold (`0.0..=1.0`).
90    #[must_use]
91    pub fn with_collision_threshold(mut self, threshold: f32) -> Self {
92        self.collision_threshold = threshold;
93        self
94    }
95
96    /// Sets the `VOL005` sibling disambiguation similarity threshold (`0.0..=1.0`).
97    #[must_use]
98    pub fn with_sibling_disambiguation_threshold(mut self, threshold: f32) -> Self {
99        self.sibling_disambiguation_threshold = threshold;
100        self
101    }
102
103    /// Sets the per-tool description token budget for `VOL012`.
104    #[must_use]
105    pub fn with_max_tool_tokens(mut self, max_tokens: usize) -> Self {
106        self.max_tool_tokens = max_tokens;
107        self
108    }
109
110    /// Sets the catalog-wide serialized token budget for `VOL012`.
111    #[must_use]
112    pub fn with_max_catalog_tokens(mut self, max_tokens: usize) -> Self {
113        self.max_catalog_tokens = max_tokens;
114        self
115    }
116
117    /// Sets the minimum severity level that fails the audit gate.
118    #[must_use]
119    pub fn with_fail_on(mut self, severity: Option<Severity>) -> Self {
120        self.fail_on = severity;
121        self
122    }
123
124    /// Suppresses a specific rule ID (e.g. `"VOL013"`).
125    #[must_use]
126    pub fn disable_rule(mut self, code: impl Into<String>) -> Self {
127        self.disabled_rules.push(code.into());
128        self
129    }
130
131    /// Overrides the USD per 1M input token rate used for cost estimates (cached rate defaults to 10%).
132    #[must_use]
133    pub fn with_input_price_per_million(mut self, usd_per_million: f32) -> Self {
134        self.input_price_per_million_usd = usd_per_million;
135        self.cached_price_per_million_usd = usd_per_million * 0.10;
136        self
137    }
138}
139
140/// Deterministic, zero-LLM auditor for MCP tool catalogs.
141#[derive(Debug, Clone, Default)]
142pub struct Auditor {
143    config: AuditConfig,
144}
145
146impl Auditor {
147    /// Creates an auditor with custom configuration.
148    #[must_use]
149    pub fn new(config: AuditConfig) -> Self {
150        Self { config }
151    }
152
153    /// Returns a reference to the active configuration.
154    pub fn config(&self) -> &AuditConfig {
155        &self.config
156    }
157
158    /// Runs all enabled `VOL001`–`VOL024` rules, pairwise collision analysis, shadowed-tool
159    /// detection, token cost estimation, and TDQS-aligned 1.0–5.0 dimension scoring on `catalog`.
160    #[must_use]
161    pub fn audit(&self, catalog: &Catalog) -> AuditReport {
162        let report_floor = self
163            .config
164            .sibling_disambiguation_threshold
165            .min(self.config.collision_threshold);
166
167        let collision_analysis = analyze_collisions(
168            catalog,
169            report_floor,
170            self.config.shadow_similarity_threshold,
171        );
172
173        let mut findings = evaluate_rules(catalog, &collision_analysis.pairs, &self.config);
174        for finding in &mut findings {
175            if let Some(tool) = catalog.get(&finding.tool) {
176                if finding.source_location.is_none() {
177                    finding.source_location = tool.source_location.clone();
178                }
179                if finding.source_server.is_none() {
180                    finding.source_server = tool.source_server.clone();
181                }
182            }
183        }
184
185        let mut tool_scores = Vec::with_capacity(catalog.len());
186        let mut tool_fingerprints = BTreeMap::new();
187
188        for tool in catalog.tools() {
189            tool_fingerprints.insert(tool.name.clone(), tool.fingerprint());
190
191            let mut dims: BTreeMap<Dimension, f32> =
192                Dimension::ALL.into_iter().map(|d| (d, 5.0_f32)).collect();
193            let mut errors = 0usize;
194            let mut warnings = 0usize;
195            let mut infos = 0usize;
196            let mut hard_cap_purpose = false;
197            let mut hard_cap_behavior = false;
198
199            for f in &findings {
200                let affects_tool = f.tool == tool.name
201                    || (f.code == "VOL014"
202                        && f.related_tool.as_deref() == Some(tool.name.as_str()));
203                if !affects_tool {
204                    continue;
205                }
206                let penalty = match f.severity {
207                    Severity::Error => {
208                        errors += 1;
209                        2.5
210                    }
211                    Severity::Warn => {
212                        warnings += 1;
213                        1.5
214                    }
215                    Severity::Info => {
216                        infos += 1;
217                        0.5
218                    }
219                };
220                if let Some(score) = dims.get_mut(&f.dimension) {
221                    *score = (*score - penalty).clamp(1.0, 5.0);
222                }
223                if f.code == "VOL001" {
224                    hard_cap_purpose = true;
225                }
226                if f.code == "VOL006" || f.code == "VOL019" {
227                    hard_cap_behavior = true;
228                }
229            }
230
231            if hard_cap_purpose {
232                dims.insert(Dimension::PurposeClarity, 1.0);
233            }
234            if hard_cap_behavior {
235                dims.insert(Dimension::BehavioralTransparency, 1.0);
236            }
237
238            let overall = round2(
239                dims.iter()
240                    .map(|(d, &s)| d.weight() * s)
241                    .sum::<f32>()
242                    .clamp(1.0, 5.0),
243            );
244            let rounded_dims: BTreeMap<Dimension, f32> =
245                dims.into_iter().map(|(d, s)| (d, round2(s))).collect();
246
247            tool_scores.push(ToolScore {
248                tool: tool.name.clone(),
249                overall,
250                tier: Tier::from_score(overall),
251                estimated_tokens: tool.estimated_total_tokens(),
252                invocation_cost: tool.invocation_cost(),
253                dimension_scores: rounded_dims,
254                error_count: errors,
255                warning_count: warnings,
256                info_count: infos,
257            });
258        }
259
260        tool_scores.sort_by(|a, b| a.tool.cmp(&b.tool));
261
262        let mut catalog_dims = BTreeMap::new();
263        for dim in Dimension::ALL {
264            let mean = if tool_scores.is_empty() {
265                5.0
266            } else {
267                let sum: f32 = tool_scores
268                    .iter()
269                    .map(|ts| ts.dimension_scores.get(&dim).copied().unwrap_or(5.0))
270                    .sum();
271                sum / tool_scores.len() as f32
272            };
273            catalog_dims.insert(dim, round2(mean));
274        }
275
276        // Apply catalog-level penalties if `<catalog>` triggered VOL012 or VOL017.
277        for f in &findings {
278            if f.tool == "<catalog>" {
279                let pen = match f.severity {
280                    Severity::Error => 2.5,
281                    Severity::Warn => 1.5,
282                    Severity::Info => 0.5,
283                };
284                if let Some(score) = catalog_dims.get_mut(&f.dimension) {
285                    *score = round2((*score - pen).clamp(1.0, 5.0));
286                }
287            }
288        }
289
290        let weighted_mean = catalog_dims
291            .iter()
292            .map(|(d, &s)| d.weight() * s)
293            .sum::<f32>()
294            .clamp(1.0, 5.0);
295        let worst_tool_score = tool_scores
296            .iter()
297            .map(|t| t.overall)
298            .fold(5.0_f32, f32::min);
299        // TDQS-aligned rollup: 70% weighted dimension mean + 30% worst-tool anchor.
300        let overall_score =
301            round2((0.70 * weighted_mean + 0.30 * worst_tool_score).clamp(1.0, 5.0));
302
303        let error_count = findings
304            .iter()
305            .filter(|f| f.severity == Severity::Error)
306            .count();
307        let warning_count = findings
308            .iter()
309            .filter(|f| f.severity == Severity::Warn)
310            .count();
311        let info_count = findings
312            .iter()
313            .filter(|f| f.severity == Severity::Info)
314            .count();
315        let collision_count = collision_analysis
316            .pairs
317            .iter()
318            .filter(|p| p.tool_a == p.tool_b || p.score >= self.config.collision_threshold)
319            .count();
320        let shadowing_count = collision_analysis
321            .pairs
322            .iter()
323            .filter(|p| p.shadowing_risk)
324            .count();
325
326        let estimated_catalog_tokens = catalog.estimated_total_tokens();
327        let tokens_m = (estimated_catalog_tokens as f32) / 1_000_000.0;
328        let cost_per_turn = tokens_m * self.config.input_price_per_million_usd;
329        let session_uncached = cost_per_turn * 200.0;
330        let session_cached =
331            cost_per_turn + (tokens_m * self.config.cached_price_per_million_usd * 199.0);
332
333        let passed = match self.config.fail_on {
334            None => true,
335            Some(min_sev) => !findings.iter().any(|f| f.severity >= min_sev),
336        };
337
338        AuditReport {
339            schema_version: SCHEMA_VERSION.into(),
340            summary: AuditSummary {
341                passed,
342                tool_count: catalog.len(),
343                estimated_catalog_tokens,
344                estimated_cost_per_turn_usd: round4(cost_per_turn),
345                estimated_200_turn_session_usd: round2(session_uncached),
346                estimated_200_turn_cached_usd: round2(session_cached),
347                overall_score,
348                worst_tool_score: round2(worst_tool_score),
349                tier: Tier::from_score(overall_score),
350                error_count,
351                warning_count,
352                info_count,
353                collision_count,
354                shadowing_count,
355            },
356            dimension_scores: catalog_dims,
357            tool_scores,
358            findings,
359            collisions: collision_analysis.pairs,
360            tool_fingerprints,
361        }
362    }
363}
364
365/// Compares a baseline [`AuditReport`] against a newer report to detect quality regressions
366/// and LLM prompt-cache-busting schema mutations.
367#[must_use]
368pub fn diff_reports(baseline: &AuditReport, current: &AuditReport) -> AuditDiff {
369    let key = |f: &Finding| {
370        (
371            f.code.clone(),
372            f.tool.clone(),
373            f.related_tool.clone(),
374            f.json_pointer.clone(),
375        )
376    };
377
378    let base_keys: BTreeSet<_> = baseline.findings.iter().map(key).collect();
379    let curr_keys: BTreeSet<_> = current.findings.iter().map(key).collect();
380
381    let new_findings: Vec<Finding> = current
382        .findings
383        .iter()
384        .filter(|f| !base_keys.contains(&key(f)))
385        .cloned()
386        .collect();
387    let resolved_findings: Vec<Finding> = baseline
388        .findings
389        .iter()
390        .filter(|f| !curr_keys.contains(&key(f)))
391        .cloned()
392        .collect();
393
394    let mut added_tools = Vec::new();
395    let mut removed_tools = Vec::new();
396    let mut modified_tools = Vec::new();
397
398    for (name, fp) in &current.tool_fingerprints {
399        match baseline.tool_fingerprints.get(name) {
400            None => added_tools.push(name.clone()),
401            Some(old_fp) if old_fp != fp => modified_tools.push(name.clone()),
402            Some(_) => {}
403        }
404    }
405    for name in baseline.tool_fingerprints.keys() {
406        if !current.tool_fingerprints.contains_key(name) {
407            removed_tools.push(name.clone());
408        }
409    }
410
411    added_tools.sort();
412    removed_tools.sort();
413    modified_tools.sort();
414
415    let score_delta = round2(current.summary.overall_score - baseline.summary.overall_score);
416    let token_delta = current.summary.estimated_catalog_tokens as i64
417        - baseline.summary.estimated_catalog_tokens as i64;
418    let session_cost_delta_usd = round2(
419        current.summary.estimated_200_turn_session_usd
420            - baseline.summary.estimated_200_turn_session_usd,
421    );
422    let error_delta = current.summary.error_count as i64 - baseline.summary.error_count as i64;
423    let warning_delta =
424        current.summary.warning_count as i64 - baseline.summary.warning_count as i64;
425    let cache_busting_change =
426        !added_tools.is_empty() || !removed_tools.is_empty() || !modified_tools.is_empty();
427    let has_new_error = new_findings.iter().any(|f| f.severity == Severity::Error);
428    let regressed = score_delta < -0.001 || error_delta > 0 || has_new_error;
429
430    AuditDiff {
431        schema_version: SCHEMA_VERSION.into(),
432        score_delta,
433        token_delta,
434        session_cost_delta_usd,
435        error_delta,
436        warning_delta,
437        new_findings,
438        resolved_findings,
439        added_tools,
440        removed_tools,
441        modified_tools,
442        cache_busting_change,
443        regressed,
444    }
445}