Skip to main content

mcp_vol/
model.rs

1use std::collections::BTreeMap;
2use std::fmt;
3
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value};
6
7use crate::error::{Error, Result};
8use crate::schema::{collect_schema_params, has_description, schema_is_container};
9use crate::text::estimate_tokens;
10
11/// Current JSON report schema version emitted by `mcp-vol`.
12pub const SCHEMA_VERSION: &str = "0.1.0";
13
14/// Behavioral hints matching MCP `ToolAnnotations`.
15#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub struct ToolHints {
18    /// Optional human-readable display title from annotations.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub title: Option<String>,
21    /// If `true`, the tool does not modify its environment.
22    #[serde(
23        default,
24        alias = "read_only_hint",
25        alias = "read_only",
26        skip_serializing_if = "Option::is_none"
27    )]
28    pub read_only_hint: Option<bool>,
29    /// If `true`, the tool may perform destructive updates.
30    #[serde(
31        default,
32        alias = "destructive_hint",
33        alias = "destructive",
34        skip_serializing_if = "Option::is_none"
35    )]
36    pub destructive_hint: Option<bool>,
37    /// If `true`, repeated calls with identical arguments have no extra effect.
38    #[serde(
39        default,
40        alias = "idempotent_hint",
41        alias = "idempotent",
42        skip_serializing_if = "Option::is_none"
43    )]
44    pub idempotent_hint: Option<bool>,
45    /// If `true`, the tool interacts with an open world of external entities.
46    #[serde(
47        default,
48        alias = "open_world_hint",
49        alias = "open_world",
50        skip_serializing_if = "Option::is_none"
51    )]
52    pub open_world_hint: Option<bool>,
53}
54
55impl ToolHints {
56    /// Returns `true` if at least one behavioral hint boolean is explicitly declared.
57    pub fn has_any_behavior_hint(&self) -> bool {
58        self.read_only_hint.is_some()
59            || self.destructive_hint.is_some()
60            || self.idempotent_hint.is_some()
61            || self.open_world_hint.is_some()
62    }
63}
64
65/// Source file coordinates populated by static source scanners (`mcp-vol scan`).
66#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
67pub struct SourceLocation {
68    /// Relative or absolute path to the source file declaring the tool.
69    pub file: String,
70    /// 1-based line number of the tool declaration.
71    pub line: usize,
72    /// 1-based column number of the tool declaration.
73    pub column: usize,
74}
75
76/// Canonical, SDK-agnostic representation of an MCP tool definition.
77///
78/// Deserializes seamlessly from MCP `tools/list` JSON (camelCase or snake_case)
79/// and converts directly from `&rmcp::model::Tool` when the `rmcp` feature is enabled.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase")]
82pub struct ToolSpec {
83    /// Unique tool identifier exposed to the model.
84    pub name: String,
85    /// Optional human-readable display title.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub title: Option<String>,
88    /// Natural-language description read by AI agents during tool selection.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub description: Option<String>,
91    /// JSON Schema object describing input parameters.
92    #[serde(default, alias = "input_schema")]
93    pub input_schema: Map<String, Value>,
94    /// Optional JSON Schema object describing structured output.
95    #[serde(
96        default,
97        alias = "output_schema",
98        skip_serializing_if = "Option::is_none"
99    )]
100    pub output_schema: Option<Map<String, Value>>,
101    /// Optional MCP behavioral annotations.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub annotations: Option<ToolHints>,
104    /// Optional static source file location populated by [`crate::scan_path`] / `mcp-vol scan`.
105    #[serde(
106        default,
107        alias = "source_location",
108        skip_serializing_if = "Option::is_none"
109    )]
110    pub source_location: Option<SourceLocation>,
111    /// Optional origin MCP server identifier populated during multi-server composition.
112    #[serde(
113        default,
114        alias = "source_server",
115        skip_serializing_if = "Option::is_none"
116    )]
117    pub source_server: Option<String>,
118}
119
120impl ToolSpec {
121    /// Creates a new `ToolSpec` with a name, optional description, and JSON Schema object.
122    #[must_use]
123    pub fn new(
124        name: impl Into<String>,
125        description: Option<impl Into<String>>,
126        input_schema: Map<String, Value>,
127    ) -> Self {
128        Self {
129            name: name.into(),
130            title: None,
131            description: description.map(Into::into),
132            input_schema,
133            output_schema: None,
134            annotations: None,
135            source_location: None,
136            source_server: None,
137        }
138    }
139
140    /// Attaches a human-readable title.
141    #[must_use]
142    pub fn with_title(mut self, title: impl Into<String>) -> Self {
143        self.title = Some(title.into());
144        self
145    }
146
147    /// Attaches behavioral annotations.
148    #[must_use]
149    pub fn with_annotations(mut self, annotations: ToolHints) -> Self {
150        self.annotations = Some(annotations);
151        self
152    }
153
154    /// Attaches an output JSON Schema.
155    #[must_use]
156    pub fn with_output_schema(mut self, output_schema: Map<String, Value>) -> Self {
157        self.output_schema = Some(output_schema);
158        self
159    }
160
161    /// Attaches static source file coordinates for SARIF `physicalLocation` emission.
162    #[must_use]
163    pub fn with_source_location(mut self, location: SourceLocation) -> Self {
164        self.source_location = Some(location);
165        self
166    }
167
168    /// Tags this tool with the name of the MCP server that provides it.
169    #[must_use]
170    pub fn with_source_server(mut self, server: impl Into<String>) -> Self {
171        self.source_server = Some(server.into());
172        self
173    }
174
175    /// Returns the top-level `properties` object map from `input_schema`, if present.
176    pub fn schema_properties(&self) -> Option<&Map<String, Value>> {
177        self.input_schema.get("properties")?.as_object()
178    }
179
180    /// Returns the list of top-level parameter names declared in `input_schema.properties`.
181    pub fn parameter_names(&self) -> Vec<&str> {
182        self.schema_properties()
183            .map(|props| props.keys().map(String::as_str).collect())
184            .unwrap_or_default()
185    }
186
187    /// Returns the list of top-level required parameter names declared in `input_schema.required`.
188    pub fn required_parameters(&self) -> Vec<&str> {
189        self.input_schema
190            .get("required")
191            .and_then(Value::as_array)
192            .map(|arr| arr.iter().filter_map(Value::as_str).collect())
193            .unwrap_or_default()
194    }
195
196    /// Fraction of all schema properties (including nested objects and resolved `$ref`s)
197    /// that declare a non-empty `description` string (`0.0..=1.0`).
198    /// Returns `1.0` when the tool takes zero parameters.
199    pub fn schema_description_coverage(&self) -> f32 {
200        let params = collect_schema_params(&self.input_schema);
201        if params.is_empty() {
202            return 1.0;
203        }
204        let documented = params.iter().filter(|p| has_description(p.schema)).count();
205        documented as f32 / params.len() as f32
206    }
207
208    /// Deterministic invocation complexity cost used for TDQS-style shadowed-tool detection.
209    ///
210    /// Weighted by required arguments (2 pts), optional arguments (1 pt),
211    /// nested object/array arguments (+1 pt), and enum/pattern constraints (+1 pt).
212    pub fn invocation_cost(&self) -> usize {
213        let params = collect_schema_params(&self.input_schema);
214        let mut cost = 0usize;
215        for param in params {
216            if param.is_required {
217                cost += 2;
218            } else {
219                cost += 1;
220            }
221            if schema_is_container(param.schema) {
222                cost += 1;
223            }
224            if param.schema.get("enum").is_some()
225                || param.schema.get("pattern").is_some()
226                || param.schema.get("oneOf").is_some()
227                || param.schema.get("anyOf").is_some()
228            {
229                cost += 1;
230            }
231        }
232        cost
233    }
234
235    /// Estimated token count of the description prose alone.
236    pub fn estimated_description_tokens(&self) -> usize {
237        self.description
238            .as_deref()
239            .map(estimate_tokens)
240            .unwrap_or(0)
241    }
242
243    fn wire_json_string(&self) -> String {
244        #[derive(Serialize)]
245        #[serde(rename_all = "camelCase")]
246        struct WireTool<'a> {
247            name: &'a str,
248            #[serde(skip_serializing_if = "Option::is_none")]
249            title: &'a Option<String>,
250            #[serde(skip_serializing_if = "Option::is_none")]
251            description: &'a Option<String>,
252            input_schema: &'a Map<String, Value>,
253            #[serde(skip_serializing_if = "Option::is_none")]
254            output_schema: &'a Option<Map<String, Value>>,
255            #[serde(skip_serializing_if = "Option::is_none")]
256            annotations: &'a Option<ToolHints>,
257        }
258        let wire = WireTool {
259            name: &self.name,
260            title: &self.title,
261            description: &self.description,
262            input_schema: &self.input_schema,
263            output_schema: &self.output_schema,
264            annotations: &self.annotations,
265        };
266        serde_json::to_string(&wire).unwrap_or_default()
267    }
268
269    /// Estimated token count of the full serialized wire MCP tool payload sent in an LLM context window.
270    /// Excludes non-wire metadata (`source_location`, `source_server`).
271    pub fn estimated_total_tokens(&self) -> usize {
272        estimate_tokens(&self.wire_json_string())
273    }
274
275    /// Stable FNV-1a 64-bit hex fingerprint of the canonical wire MCP tool definition.
276    /// Used by `diff_reports` to flag prompt-cache-busting schema mutations without false positives
277    /// from line-number shifts.
278    pub fn fingerprint(&self) -> String {
279        let canonical = self.wire_json_string();
280        let mut hash: u64 = 0xcbf29ce484222325;
281        for byte in canonical.as_bytes() {
282            hash ^= u64::from(*byte);
283            hash = hash.wrapping_mul(0x100000001b3);
284        }
285        format!("{hash:016x}")
286    }
287}
288
289/// Collection of MCP tools audited or evaluated together as a single catalog.
290#[derive(Debug, Clone, Default)]
291pub struct Catalog {
292    tools: Vec<ToolSpec>,
293}
294
295impl Catalog {
296    /// Builds a catalog from any iterator of [`ToolSpec`].
297    #[must_use]
298    pub fn new(tools: impl IntoIterator<Item = ToolSpec>) -> Self {
299        Self {
300            tools: tools.into_iter().collect(),
301        }
302    }
303
304    /// Parses a catalog from standard MCP JSON shapes:
305    /// - JSON-RPC 2.0 `tools/list` response (`{"jsonrpc":"2.0","result":{"tools":[...]}}`)
306    /// - MCP `ListToolsResult` object (`{"tools":[...]}`)
307    /// - Raw JSON array of tool definitions (`[...]`)
308    pub fn from_mcp_json(json: &str) -> Result<Self> {
309        let value: Value = serde_json::from_str(json)?;
310        let tools_val = if value.is_array() {
311            value
312        } else if let Some(tools) = value.get("tools") {
313            tools.clone()
314        } else if let Some(tools) = value.get("result").and_then(|r| r.get("tools")) {
315            tools.clone()
316        } else {
317            return Err(Error::InvalidCatalogFormat(
318                "expected a JSON array of tools, an object with a `tools` array, or a JSON-RPC `result.tools` envelope".to_string(),
319            ));
320        };
321
322        let tools: Vec<ToolSpec> = serde_json::from_value(tools_val)?;
323        Ok(Self { tools })
324    }
325
326    /// Returns a slice of all tools in the catalog.
327    pub fn tools(&self) -> &[ToolSpec] {
328        &self.tools
329    }
330
331    /// Number of tools in the catalog.
332    pub fn len(&self) -> usize {
333        self.tools.len()
334    }
335
336    /// Returns `true` if the catalog contains no tools.
337    pub fn is_empty(&self) -> bool {
338        self.tools.is_empty()
339    }
340
341    /// Looks up the first tool with the given exact name.
342    pub fn get(&self, name: &str) -> Option<&ToolSpec> {
343        self.tools.iter().find(|t| t.name == name)
344    }
345
346    /// Returns a cloned catalog where every tool is tagged with `source_server`.
347    #[must_use]
348    pub fn with_source_server(&self, server: impl Into<String>) -> Self {
349        let srv = server.into();
350        let tools = self
351            .tools
352            .iter()
353            .cloned()
354            .map(|mut t| {
355                t.source_server = Some(srv.clone());
356                t
357            })
358            .collect();
359        Self { tools }
360    }
361
362    /// Returns a cloned catalog where every tool name is prefixed with `prefix` (unless it
363    /// already starts with `prefix`), automatically appending `_` when `prefix` does not end
364    /// with `_`, `-`, or `.`. Useful for eliminating cross-server name collisions.
365    #[must_use]
366    pub fn with_namespace_prefix(&self, prefix: &str) -> Self {
367        let normalized = if prefix.is_empty()
368            || prefix.ends_with('_')
369            || prefix.ends_with('-')
370            || prefix.ends_with('.')
371        {
372            prefix.to_string()
373        } else {
374            format!("{prefix}_")
375        };
376        let tools = self
377            .tools
378            .iter()
379            .cloned()
380            .map(|mut t| {
381                if !normalized.is_empty() && !t.name.starts_with(&normalized) {
382                    t.name = format!("{normalized}{}", t.name);
383                }
384                t
385            })
386            .collect();
387        Self { tools }
388    }
389
390    /// Total estimated context-window tokens consumed by serializing all tools in this catalog.
391    pub fn estimated_total_tokens(&self) -> usize {
392        self.tools
393            .iter()
394            .map(ToolSpec::estimated_total_tokens)
395            .sum()
396    }
397
398    /// Serializes the catalog in standard MCP `ListToolsResult` JSON shape (`{"tools":[...]}`).
399    pub fn to_mcp_json(&self) -> Result<String> {
400        let wrapper = serde_json::json!({ "tools": self.tools });
401        Ok(serde_json::to_string_pretty(&wrapper)?)
402    }
403
404    /// Serializes the catalog as minified single-line MCP `ListToolsResult` JSON.
405    pub fn to_mcp_json_compact(&self) -> Result<String> {
406        let wrapper = serde_json::json!({ "tools": self.tools });
407        Ok(serde_json::to_string(&wrapper)?)
408    }
409}
410
411/// Six research-backed quality dimensions aligned with arXiv 2602.14878 and Glama TDQS.
412#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
413#[serde(rename_all = "snake_case")]
414pub enum Dimension {
415    /// How clearly the tool states its concrete action, target resource, and return value.
416    PurposeClarity,
417    /// Whether the description guides when to call (and when not to call) the tool.
418    UsageGuidelines,
419    /// Whether annotations and prose honestly disclose side effects, safety, and limits.
420    BehavioralTransparency,
421    /// Whether parameters are semantically named, documented, and constrained.
422    ParameterSemantics,
423    /// Information density and adherence to token budgets without duplicating schemas.
424    Conciseness,
425    /// Catalog-level disambiguation, collision avoidance, and shadowing resilience.
426    ContextualCompleteness,
427}
428
429impl Dimension {
430    /// All six dimensions in canonical display order.
431    pub const ALL: [Dimension; 6] = [
432        Dimension::PurposeClarity,
433        Dimension::UsageGuidelines,
434        Dimension::BehavioralTransparency,
435        Dimension::ParameterSemantics,
436        Dimension::Conciseness,
437        Dimension::ContextualCompleteness,
438    ];
439
440    /// Machine-readable snake_case identifier.
441    pub const fn as_str(self) -> &'static str {
442        match self {
443            Dimension::PurposeClarity => "purpose_clarity",
444            Dimension::UsageGuidelines => "usage_guidelines",
445            Dimension::BehavioralTransparency => "behavioral_transparency",
446            Dimension::ParameterSemantics => "parameter_semantics",
447            Dimension::Conciseness => "conciseness",
448            Dimension::ContextualCompleteness => "contextual_completeness",
449        }
450    }
451
452    /// Weight used when rolling up the 6 dimension scores into a single 1.0–5.0 overall score.
453    pub const fn weight(self) -> f32 {
454        match self {
455            Dimension::PurposeClarity => 0.25,
456            Dimension::UsageGuidelines => 0.20,
457            Dimension::BehavioralTransparency => 0.15,
458            Dimension::ParameterSemantics => 0.20,
459            Dimension::Conciseness => 0.10,
460            Dimension::ContextualCompleteness => 0.10,
461        }
462    }
463}
464
465impl fmt::Display for Dimension {
466    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467        f.write_str(self.as_str())
468    }
469}
470
471/// Severity level of an audit finding, ordered `Info < Warn < Error`.
472#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
473#[serde(rename_all = "lowercase")]
474pub enum Severity {
475    /// Informational improvement suggestion.
476    Info,
477    /// Quality defect likely to degrade selection accuracy or token efficiency.
478    Warn,
479    /// Critical specification defect or collision that directly causes agent failures.
480    Error,
481}
482
483impl Severity {
484    /// Canonical lowercase label.
485    pub const fn as_str(self) -> &'static str {
486        match self {
487            Severity::Info => "info",
488            Severity::Warn => "warn",
489            Severity::Error => "error",
490        }
491    }
492}
493
494impl fmt::Display for Severity {
495    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496        f.write_str(self.as_str())
497    }
498}
499
500/// Letter grade tier derived from the 1.0–5.0 overall quality score.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
502pub enum Tier {
503    /// 4.50 – 5.00
504    A,
505    /// 3.50 – 4.49
506    B,
507    /// 2.50 – 3.49
508    C,
509    /// 1.80 – 2.49
510    D,
511    /// Below 1.80
512    F,
513}
514
515impl Tier {
516    /// Converts a 1.0–5.0 score to a letter grade tier.
517    pub fn from_score(score: f32) -> Self {
518        if score >= 4.5 {
519            Tier::A
520        } else if score >= 3.5 {
521            Tier::B
522        } else if score >= 2.5 {
523            Tier::C
524        } else if score >= 1.8 {
525            Tier::D
526        } else {
527            Tier::F
528        }
529    }
530}
531
532impl fmt::Display for Tier {
533    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
534        fmt::Debug::fmt(self, f)
535    }
536}
537
538/// Static documentation metadata for a built-in `VOL001`–`VOL024` rule.
539#[derive(Debug, Clone, Serialize, Deserialize)]
540pub struct RuleMeta {
541    /// Stable rule code (e.g., `"VOL001"`).
542    pub code: String,
543    /// Kebab-case rule identifier (e.g., `"missing-description"`).
544    pub slug: String,
545    /// Dimension scored by this rule.
546    pub dimension: Dimension,
547    /// Default severity level.
548    pub default_severity: Severity,
549    /// Concise human/agent explanation of what the rule checks.
550    pub summary: String,
551    /// Default remediation guidance.
552    pub remediation: String,
553}
554
555/// A single actionable diagnostic finding emitted by [`crate::Auditor`].
556#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
557pub struct Finding {
558    /// Stable rule ID (`VOL001`–`VOL024`).
559    pub code: String,
560    /// Kebab-case rule slug.
561    pub slug: String,
562    /// Diagnostic severity.
563    pub severity: Severity,
564    /// Affected quality dimension.
565    pub dimension: Dimension,
566    /// Name of the primary tool (or `"<catalog>"` for catalog-wide findings).
567    pub tool: String,
568    /// Related sibling tool name for pairwise rules (`VOL005`, `VOL014`, `VOL015`).
569    #[serde(skip_serializing_if = "Option::is_none")]
570    pub related_tool: Option<String>,
571    /// RFC 6901 JSON Pointer locating the offending field within the tool catalog.
572    pub json_pointer: String,
573    /// Concise factual description of the defect.
574    pub message: String,
575    /// Structured evidence fields (scores, matched terms, offending parameters).
576    pub evidence: Value,
577    /// Actionable fix instruction designed for AI coding agents and maintainers.
578    pub fix_hint: String,
579    /// Optional static source coordinates propagated from [`ToolSpec::source_location`].
580    #[serde(default, skip_serializing_if = "Option::is_none")]
581    pub source_location: Option<SourceLocation>,
582    /// Optional origin MCP server name propagated from [`ToolSpec::source_server`].
583    #[serde(default, skip_serializing_if = "Option::is_none")]
584    pub source_server: Option<String>,
585}
586
587/// Pairwise similarity and shadowing entry between two tools in the same catalog.
588#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
589pub struct CollisionPair {
590    /// Lexicographically first tool name.
591    pub tool_a: String,
592    /// Lexicographically second tool name.
593    pub tool_b: String,
594    /// Composite similarity score in `0.0..=1.0`.
595    pub score: f32,
596    /// Canonicalized name token + trigram similarity in `0.0..=1.0`.
597    pub name_similarity: f32,
598    /// Catalog-scoped TF-IDF cosine similarity of prose in `0.0..=1.0`.
599    pub description_similarity: f32,
600    /// Jaccard overlap of input parameter names in `0.0..=1.0`.
601    pub param_overlap: f32,
602    /// Top shared semantic terms driving the overlap.
603    pub shared_terms: Vec<String>,
604    /// True if one tool's lighter schema can shadow the other tool's heavier schema.
605    pub shadowing_risk: bool,
606    /// Cheaper sibling tool when `shadowing_risk` is `true`.
607    #[serde(skip_serializing_if = "Option::is_none")]
608    pub cheaper_tool: Option<String>,
609    /// Heavier shadowed sibling tool when `shadowing_risk` is `true`.
610    #[serde(skip_serializing_if = "Option::is_none")]
611    pub expensive_tool: Option<String>,
612}
613
614/// Per-tool quality score breakdown.
615#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
616pub struct ToolScore {
617    /// Tool name.
618    pub tool: String,
619    /// Weighted 1.0–5.0 quality score for this tool.
620    pub overall: f32,
621    /// Letter grade tier for this tool.
622    pub tier: Tier,
623    /// Estimated total serialized tokens for this tool.
624    pub estimated_tokens: usize,
625    /// Deterministic invocation complexity cost.
626    pub invocation_cost: usize,
627    /// Per-dimension 1.0–5.0 scores.
628    pub dimension_scores: BTreeMap<Dimension, f32>,
629    /// Count of `Error` findings on this tool.
630    pub error_count: usize,
631    /// Count of `Warn` findings on this tool.
632    pub warning_count: usize,
633    /// Count of `Info` findings on this tool.
634    pub info_count: usize,
635}
636
637/// Top-level summary metrics of an [`AuditReport`].
638#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
639pub struct AuditSummary {
640    /// `true` when no findings meet or exceed the configured `fail_on` severity.
641    pub passed: bool,
642    /// Total number of audited tools.
643    pub tool_count: usize,
644    /// Total estimated context-window tokens for the catalog.
645    pub estimated_catalog_tokens: usize,
646    /// Estimated uncached LLM input cost per turn for loading this tool catalog (USD).
647    #[serde(default)]
648    pub estimated_cost_per_turn_usd: f32,
649    /// Estimated uncached LLM input cost across a 200-turn agent session (USD).
650    #[serde(default)]
651    pub estimated_200_turn_session_usd: f32,
652    /// Estimated prompt-cached LLM input cost across a 200-turn session (1 cold + 199 cached reads, USD).
653    #[serde(default)]
654    pub estimated_200_turn_cached_usd: f32,
655    /// Catalog-level weighted quality score (`1.0..=5.0`).
656    pub overall_score: f32,
657    /// Lowest per-tool overall score in the catalog (`1.0..=5.0`).
658    pub worst_tool_score: f32,
659    /// Catalog letter grade tier.
660    pub tier: Tier,
661    /// Total `Error` findings.
662    pub error_count: usize,
663    /// Total `Warn` findings.
664    pub warning_count: usize,
665    /// Total `Info` findings.
666    pub info_count: usize,
667    /// Number of pairs exceeding the collision threshold.
668    pub collision_count: usize,
669    /// Number of pairs flagged with shadowing risk.
670    pub shadowing_count: usize,
671}
672
673/// Prioritized per-tool repair entry inside a [`RepairPlan`].
674#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
675pub struct ToolRepairItem {
676    /// Tool name (or `"<catalog>"`).
677    pub tool: String,
678    /// Current per-tool score (`1.0..=5.0`).
679    pub current_score: f32,
680    /// Current tier.
681    pub tier: Tier,
682    /// Estimated total serialized tokens for this tool.
683    pub estimated_tokens: usize,
684    /// Ordered findings affecting this tool, highest severity first.
685    pub findings: Vec<Finding>,
686}
687
688/// Compact, worst-tool-first repair roadmap designed for AI coding agents.
689#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
690pub struct RepairPlan {
691    /// Report schema version.
692    pub schema_version: String,
693    /// Current catalog overall score.
694    pub current_overall_score: f32,
695    /// Current catalog tier.
696    pub current_tier: Tier,
697    /// Number of tools requiring edits.
698    pub tools_to_fix: usize,
699    /// Total findings across all repair items.
700    pub total_findings: usize,
701    /// Repair items sorted worst-tool-first so fixing top items yields the biggest score lift.
702    pub items: Vec<ToolRepairItem>,
703}
704
705impl RepairPlan {
706    /// Serializes this repair plan as pretty-printed JSON.
707    pub fn to_json_pretty(&self) -> Result<String> {
708        Ok(serde_json::to_string_pretty(self)?)
709    }
710
711    /// Formats a token-efficient Markdown checklist ready to paste into an AI coding agent.
712    pub fn to_markdown(&self) -> String {
713        let mut out = String::new();
714        out.push_str(&format!(
715            "## `mcp-vol` Prioritized Repair Plan (Current: {:.2}/5.00, Tier {})\n\n",
716            self.current_overall_score, self.current_tier
717        ));
718        if self.items.is_empty() {
719            out.push_str("All tools passed with zero findings. No edits required.\n");
720            return out;
721        }
722        out.push_str(&format!(
723            "Fix these **{} tool(s)** in order (worst-scoring first for maximum TDQS/catalog impact):\n\n",
724            self.tools_to_fix
725        ));
726        for (idx, item) in self.items.iter().enumerate() {
727            out.push_str(&format!(
728                "### {}. `{}` — Score {:.2}/5.00 (Tier {}, ~{} tokens)\n",
729                idx + 1,
730                item.tool,
731                item.current_score,
732                item.tier,
733                item.estimated_tokens
734            ));
735            for f in &item.findings {
736                out.push_str(&format!(
737                    "- **[{} {}]** (`{}`): {}\n  - **Fix:** {}\n",
738                    f.severity.as_str().to_uppercase(),
739                    f.code,
740                    f.json_pointer,
741                    f.message,
742                    f.fix_hint
743                ));
744            }
745            out.push('\n');
746        }
747        out
748    }
749}
750
751/// Complete deterministic audit report returned by [`crate::Auditor::audit`].
752#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
753pub struct AuditReport {
754    /// Schema version for forward-compatible machine parsing.
755    pub schema_version: String,
756    /// High-level summary counters and gate status.
757    pub summary: AuditSummary,
758    /// Catalog-level mean score (`1.0..=5.0`) for each of the 6 dimensions.
759    pub dimension_scores: BTreeMap<Dimension, f32>,
760    /// Per-tool score breakdown sorted by tool name.
761    pub tool_scores: Vec<ToolScore>,
762    /// Actionable findings sorted deterministically by severity (desc), code, and tool.
763    pub findings: Vec<Finding>,
764    /// High-similarity and shadowed tool pairs sorted descending by similarity score.
765    pub collisions: Vec<CollisionPair>,
766    /// Stable per-tool fingerprints for prompt-cache drift detection in [`AuditDiff`].
767    #[serde(default)]
768    pub tool_fingerprints: BTreeMap<String, String>,
769}
770
771impl AuditReport {
772    /// Returns `true` if the catalog passed the configured severity gate.
773    pub fn passed(&self) -> bool {
774        self.summary.passed
775    }
776
777    /// Serializes this report as pretty-printed canonical JSON.
778    pub fn to_json_pretty(&self) -> Result<String> {
779        Ok(serde_json::to_string_pretty(self)?)
780    }
781
782    /// Serializes this report as minified single-line JSON to conserve AI agent context tokens.
783    pub fn to_json_compact(&self) -> Result<String> {
784        Ok(serde_json::to_string(self)?)
785    }
786
787    /// Returns a cloned report retaining at most `max_findings` highest-severity findings,
788    /// preserving exact `summary` totals so AI agents stay inside strict token budgets.
789    #[must_use]
790    pub fn with_max_findings(&self, max_findings: usize) -> Self {
791        let mut cloned = self.clone();
792        cloned.findings.truncate(max_findings);
793        cloned
794    }
795
796    /// Generates a worst-tool-first [`RepairPlan`] grouped by tool for AI coding agents.
797    pub fn to_repair_plan(&self) -> RepairPlan {
798        let mut grouped: BTreeMap<String, Vec<Finding>> = BTreeMap::new();
799        for f in &self.findings {
800            grouped.entry(f.tool.clone()).or_default().push(f.clone());
801        }
802
803        let score_map: BTreeMap<&str, &ToolScore> = self
804            .tool_scores
805            .iter()
806            .map(|ts| (ts.tool.as_str(), ts))
807            .collect();
808
809        let mut items: Vec<ToolRepairItem> = grouped
810            .into_iter()
811            .map(|(tool, findings)| {
812                let (current_score, tier, estimated_tokens) = match score_map.get(tool.as_str()) {
813                    Some(ts) => (ts.overall, ts.tier, ts.estimated_tokens),
814                    None => (
815                        self.summary.overall_score,
816                        self.summary.tier,
817                        self.summary.estimated_catalog_tokens,
818                    ),
819                };
820                ToolRepairItem {
821                    tool,
822                    current_score,
823                    tier,
824                    estimated_tokens,
825                    findings,
826                }
827            })
828            .collect();
829
830        items.sort_by(|a, b| {
831            a.current_score
832                .total_cmp(&b.current_score)
833                .then_with(|| b.findings.len().cmp(&a.findings.len()))
834                .then_with(|| a.tool.cmp(&b.tool))
835        });
836
837        RepairPlan {
838            schema_version: self.schema_version.clone(),
839            current_overall_score: self.summary.overall_score,
840            current_tier: self.summary.tier,
841            tools_to_fix: items.len(),
842            total_findings: self.findings.len(),
843            items,
844        }
845    }
846
847    /// Formats a concise human-readable terminal summary.
848    pub fn to_text(&self) -> String {
849        let mut out = String::new();
850        out.push_str(&format!(
851            "mcp-vol audit: {} | score {:.2}/5.00 (Tier {}) | worst tool {:.2} | {} tools | ~{} tokens (~${:.2}/200-turn uncached, ~${:.2} cached)\n",
852            if self.summary.passed { "PASS" } else { "FAIL" },
853            self.summary.overall_score,
854            self.summary.tier,
855            self.summary.worst_tool_score,
856            self.summary.tool_count,
857            self.summary.estimated_catalog_tokens,
858            self.summary.estimated_200_turn_session_usd,
859            self.summary.estimated_200_turn_cached_usd,
860        ));
861        out.push_str(&format!(
862            "findings: {} error, {} warn, {} info | collisions: {} | shadowing risks: {}\n",
863            self.summary.error_count,
864            self.summary.warning_count,
865            self.summary.info_count,
866            self.summary.collision_count,
867            self.summary.shadowing_count,
868        ));
869        if !self.findings.is_empty() {
870            out.push('\n');
871            for f in &self.findings {
872                let mut target = match &f.related_tool {
873                    Some(rel) => format!("{} <-> {}", f.tool, rel),
874                    None => f.tool.clone(),
875                };
876                if let Some(srv) = &f.source_server {
877                    target = format!("[{srv}] {target}");
878                }
879                if let Some(loc) = &f.source_location {
880                    target.push_str(&format!(" ({}:{})", loc.file, loc.line));
881                }
882                out.push_str(&format!(
883                    "[{}] {} ({}) {}\n  {}\n  fix: {}\n",
884                    f.severity.as_str().to_uppercase(),
885                    f.code,
886                    f.slug,
887                    target,
888                    f.message,
889                    f.fix_hint
890                ));
891            }
892        }
893        out
894    }
895
896    /// Formats a GitHub-Flavored Markdown summary suitable for Pull Request comments.
897    pub fn to_markdown(&self) -> String {
898        let status = if self.summary.passed { "PASS" } else { "FAIL" };
899        let mut out = String::new();
900        out.push_str(&format!(
901            "### `mcp-vol` Audit Report — **{status}** (Score **{:.2}/5.00**, Tier **{}**)\n\n",
902            self.summary.overall_score, self.summary.tier
903        ));
904        out.push_str("| Tools | Worst Tool | Est. Tokens | Est. 200-Turn Cost (Uncached / Cached) | Errors | Warnings | Collisions | Shadowing |\n");
905        out.push_str("|---:|---:|---:|---:|---:|---:|---:|---:|\n");
906        out.push_str(&format!(
907            "| {} | {:.2} | ~{} | ${:.2} / ${:.2} | {} | {} | {} | {} |\n\n",
908            self.summary.tool_count,
909            self.summary.worst_tool_score,
910            self.summary.estimated_catalog_tokens,
911            self.summary.estimated_200_turn_session_usd,
912            self.summary.estimated_200_turn_cached_usd,
913            self.summary.error_count,
914            self.summary.warning_count,
915            self.summary.collision_count,
916            self.summary.shadowing_count,
917        ));
918
919        out.push_str("#### Dimension Scores\n\n| Dimension | Score |\n|---|---:|\n");
920        for dim in Dimension::ALL {
921            let s = self.dimension_scores.get(&dim).copied().unwrap_or(5.0);
922            out.push_str(&format!("| `{}` | {:.2} / 5.00 |\n", dim.as_str(), s));
923        }
924
925        if !self.findings.is_empty() {
926            out.push_str("\n#### Findings\n\n| Severity | Code | Tool | Issue | Fix Hint |\n|---|---|---|---|---|\n");
927            for f in self.findings.iter().take(50) {
928                let mut target = match &f.related_tool {
929                    Some(rel) => format!("`{}` ↔ `{}`", f.tool, rel),
930                    None => format!("`{}`", f.tool),
931                };
932                if let Some(loc) = &f.source_location {
933                    target.push_str(&format!(" (`{}:{}`)", loc.file, loc.line));
934                }
935                out.push_str(&format!(
936                    "| `{}` | `{}` | {} | {} | {} |\n",
937                    f.severity.as_str().to_uppercase(),
938                    f.code,
939                    target,
940                    f.message.replace('|', "\\|"),
941                    f.fix_hint.replace('|', "\\|")
942                ));
943            }
944            if self.findings.len() > 50 {
945                out.push_str(&format!(
946                    "\n*Showing first 50 of {} findings. Run `mcp-vol check --format json` for the full list.*\n",
947                    self.findings.len()
948                ));
949            }
950        }
951        out
952    }
953}
954
955/// Regression and prompt-cache volatility diff between two [`AuditReport`] snapshots.
956#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
957pub struct AuditDiff {
958    /// Schema version.
959    pub schema_version: String,
960    /// Change in overall catalog score (`current - baseline`).
961    pub score_delta: f32,
962    /// Change in estimated catalog tokens (`current - baseline`).
963    pub token_delta: i64,
964    /// Change in estimated 200-turn uncached session cost (USD).
965    #[serde(default)]
966    pub session_cost_delta_usd: f32,
967    /// Change in error finding count.
968    pub error_delta: i64,
969    /// Change in warning finding count.
970    pub warning_delta: i64,
971    /// Findings present in `current` that were not in `baseline`.
972    pub new_findings: Vec<Finding>,
973    /// Findings present in `baseline` that were fixed in `current`.
974    pub resolved_findings: Vec<Finding>,
975    /// Tools added since baseline.
976    pub added_tools: Vec<String>,
977    /// Tools removed since baseline.
978    pub removed_tools: Vec<String>,
979    /// Tools whose serialized schema or description changed since baseline.
980    pub modified_tools: Vec<String>,
981    /// `true` if any tool was added, removed, or modified (invalidating LLM prompt cache).
982    pub cache_busting_change: bool,
983    /// `true` if score dropped, error count increased, or new errors appeared.
984    pub regressed: bool,
985}
986
987impl AuditDiff {
988    /// Serializes this diff as pretty-printed JSON.
989    pub fn to_json_pretty(&self) -> Result<String> {
990        Ok(serde_json::to_string_pretty(self)?)
991    }
992
993    /// Formats a concise human-readable diff summary.
994    pub fn to_text(&self) -> String {
995        let mut out = String::new();
996        out.push_str(&format!(
997            "mcp-vol diff: {} | score {:+.2} | tokens {:+} (${:+.2}/200-turn) | errors {:+} | warnings {:+}\n",
998            if self.regressed { "REGRESSED" } else { "OK" },
999            self.score_delta,
1000            self.token_delta,
1001            self.session_cost_delta_usd,
1002            self.error_delta,
1003            self.warning_delta,
1004        ));
1005        out.push_str(&format!(
1006            "prompt cache impact: {} (added: {}, removed: {}, modified: {})\n",
1007            if self.cache_busting_change {
1008                "CACHE INVALIDATED"
1009            } else {
1010                "STABLE"
1011            },
1012            self.added_tools.len(),
1013            self.removed_tools.len(),
1014            self.modified_tools.len(),
1015        ));
1016        out.push_str(&format!(
1017            "findings: +{} new, -{} resolved\n",
1018            self.new_findings.len(),
1019            self.resolved_findings.len(),
1020        ));
1021        out
1022    }
1023
1024    /// Formats a GitHub-Flavored Markdown diff summary for Pull Request comments.
1025    pub fn to_markdown(&self) -> String {
1026        let status = if self.regressed { "REGRESSED" } else { "OK" };
1027        let cache = if self.cache_busting_change {
1028            "INVALIDATED"
1029        } else {
1030            "STABLE"
1031        };
1032        let mut out = String::new();
1033        out.push_str(&format!("### `mcp-vol` Diff — **{status}**\n\n"));
1034        out.push_str("| Score Delta | Token Delta | 200-Turn Cost Delta | New / Resolved Findings | Prompt Cache |\n");
1035        out.push_str("|---:|---:|---:|---:|:---:|\n");
1036        out.push_str(&format!(
1037            "| `{:+.2}` | `{:+}` | `${:+.2}` | `+{}` / `-{}` | **{}** |\n",
1038            self.score_delta,
1039            self.token_delta,
1040            self.session_cost_delta_usd,
1041            self.new_findings.len(),
1042            self.resolved_findings.len(),
1043            cache,
1044        ));
1045        out
1046    }
1047}
1048
1049/// Rounds a floating-point metric to 2 decimal places for stable JSON snapshots.
1050pub(crate) fn round2(v: f32) -> f32 {
1051    (v * 100.0).round() / 100.0
1052}
1053
1054/// Rounds a floating-point metric to 4 decimal places for similarity and ranking scores.
1055pub(crate) fn round4(v: f32) -> f32 {
1056    (v * 10_000.0).round() / 10_000.0
1057}