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
11pub const SCHEMA_VERSION: &str = "0.1.0";
13
14#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub struct ToolHints {
18 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub title: Option<String>,
21 #[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 #[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 #[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 #[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 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
67pub struct SourceLocation {
68 pub file: String,
70 pub line: usize,
72 pub column: usize,
74}
75
76#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase")]
82pub struct ToolSpec {
83 pub name: String,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub title: Option<String>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub description: Option<String>,
91 #[serde(default, alias = "input_schema")]
93 pub input_schema: Map<String, Value>,
94 #[serde(
96 default,
97 alias = "output_schema",
98 skip_serializing_if = "Option::is_none"
99 )]
100 pub output_schema: Option<Map<String, Value>>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub annotations: Option<ToolHints>,
104 #[serde(
106 default,
107 alias = "source_location",
108 skip_serializing_if = "Option::is_none"
109 )]
110 pub source_location: Option<SourceLocation>,
111 #[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 #[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 #[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 #[must_use]
149 pub fn with_annotations(mut self, annotations: ToolHints) -> Self {
150 self.annotations = Some(annotations);
151 self
152 }
153
154 #[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 #[must_use]
163 pub fn with_source_location(mut self, location: SourceLocation) -> Self {
164 self.source_location = Some(location);
165 self
166 }
167
168 #[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 pub fn schema_properties(&self) -> Option<&Map<String, Value>> {
177 self.input_schema.get("properties")?.as_object()
178 }
179
180 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 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 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 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 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 pub fn estimated_total_tokens(&self) -> usize {
272 estimate_tokens(&self.wire_json_string())
273 }
274
275 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#[derive(Debug, Clone, Default)]
291pub struct Catalog {
292 tools: Vec<ToolSpec>,
293}
294
295impl Catalog {
296 #[must_use]
298 pub fn new(tools: impl IntoIterator<Item = ToolSpec>) -> Self {
299 Self {
300 tools: tools.into_iter().collect(),
301 }
302 }
303
304 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 pub fn tools(&self) -> &[ToolSpec] {
328 &self.tools
329 }
330
331 pub fn len(&self) -> usize {
333 self.tools.len()
334 }
335
336 pub fn is_empty(&self) -> bool {
338 self.tools.is_empty()
339 }
340
341 pub fn get(&self, name: &str) -> Option<&ToolSpec> {
343 self.tools.iter().find(|t| t.name == name)
344 }
345
346 #[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 #[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 pub fn estimated_total_tokens(&self) -> usize {
392 self.tools
393 .iter()
394 .map(ToolSpec::estimated_total_tokens)
395 .sum()
396 }
397
398 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
413#[serde(rename_all = "snake_case")]
414pub enum Dimension {
415 PurposeClarity,
417 UsageGuidelines,
419 BehavioralTransparency,
421 ParameterSemantics,
423 Conciseness,
425 ContextualCompleteness,
427}
428
429impl Dimension {
430 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
473#[serde(rename_all = "lowercase")]
474pub enum Severity {
475 Info,
477 Warn,
479 Error,
481}
482
483impl Severity {
484 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
502pub enum Tier {
503 A,
505 B,
507 C,
509 D,
511 F,
513}
514
515impl Tier {
516 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#[derive(Debug, Clone, Serialize, Deserialize)]
540pub struct RuleMeta {
541 pub code: String,
543 pub slug: String,
545 pub dimension: Dimension,
547 pub default_severity: Severity,
549 pub summary: String,
551 pub remediation: String,
553}
554
555#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
557pub struct Finding {
558 pub code: String,
560 pub slug: String,
562 pub severity: Severity,
564 pub dimension: Dimension,
566 pub tool: String,
568 #[serde(skip_serializing_if = "Option::is_none")]
570 pub related_tool: Option<String>,
571 pub json_pointer: String,
573 pub message: String,
575 pub evidence: Value,
577 pub fix_hint: String,
579 #[serde(default, skip_serializing_if = "Option::is_none")]
581 pub source_location: Option<SourceLocation>,
582 #[serde(default, skip_serializing_if = "Option::is_none")]
584 pub source_server: Option<String>,
585}
586
587#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
589pub struct CollisionPair {
590 pub tool_a: String,
592 pub tool_b: String,
594 pub score: f32,
596 pub name_similarity: f32,
598 pub description_similarity: f32,
600 pub param_overlap: f32,
602 pub shared_terms: Vec<String>,
604 pub shadowing_risk: bool,
606 #[serde(skip_serializing_if = "Option::is_none")]
608 pub cheaper_tool: Option<String>,
609 #[serde(skip_serializing_if = "Option::is_none")]
611 pub expensive_tool: Option<String>,
612}
613
614#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
616pub struct ToolScore {
617 pub tool: String,
619 pub overall: f32,
621 pub tier: Tier,
623 pub estimated_tokens: usize,
625 pub invocation_cost: usize,
627 pub dimension_scores: BTreeMap<Dimension, f32>,
629 pub error_count: usize,
631 pub warning_count: usize,
633 pub info_count: usize,
635}
636
637#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
639pub struct AuditSummary {
640 pub passed: bool,
642 pub tool_count: usize,
644 pub estimated_catalog_tokens: usize,
646 #[serde(default)]
648 pub estimated_cost_per_turn_usd: f32,
649 #[serde(default)]
651 pub estimated_200_turn_session_usd: f32,
652 #[serde(default)]
654 pub estimated_200_turn_cached_usd: f32,
655 pub overall_score: f32,
657 pub worst_tool_score: f32,
659 pub tier: Tier,
661 pub error_count: usize,
663 pub warning_count: usize,
665 pub info_count: usize,
667 pub collision_count: usize,
669 pub shadowing_count: usize,
671}
672
673#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
675pub struct ToolRepairItem {
676 pub tool: String,
678 pub current_score: f32,
680 pub tier: Tier,
682 pub estimated_tokens: usize,
684 pub findings: Vec<Finding>,
686}
687
688#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
690pub struct RepairPlan {
691 pub schema_version: String,
693 pub current_overall_score: f32,
695 pub current_tier: Tier,
697 pub tools_to_fix: usize,
699 pub total_findings: usize,
701 pub items: Vec<ToolRepairItem>,
703}
704
705impl RepairPlan {
706 pub fn to_json_pretty(&self) -> Result<String> {
708 Ok(serde_json::to_string_pretty(self)?)
709 }
710
711 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
753pub struct AuditReport {
754 pub schema_version: String,
756 pub summary: AuditSummary,
758 pub dimension_scores: BTreeMap<Dimension, f32>,
760 pub tool_scores: Vec<ToolScore>,
762 pub findings: Vec<Finding>,
764 pub collisions: Vec<CollisionPair>,
766 #[serde(default)]
768 pub tool_fingerprints: BTreeMap<String, String>,
769}
770
771impl AuditReport {
772 pub fn passed(&self) -> bool {
774 self.summary.passed
775 }
776
777 pub fn to_json_pretty(&self) -> Result<String> {
779 Ok(serde_json::to_string_pretty(self)?)
780 }
781
782 pub fn to_json_compact(&self) -> Result<String> {
784 Ok(serde_json::to_string(self)?)
785 }
786
787 #[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 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 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
957pub struct AuditDiff {
958 pub schema_version: String,
960 pub score_delta: f32,
962 pub token_delta: i64,
964 #[serde(default)]
966 pub session_cost_delta_usd: f32,
967 pub error_delta: i64,
969 pub warning_delta: i64,
971 pub new_findings: Vec<Finding>,
973 pub resolved_findings: Vec<Finding>,
975 pub added_tools: Vec<String>,
977 pub removed_tools: Vec<String>,
979 pub modified_tools: Vec<String>,
981 pub cache_busting_change: bool,
983 pub regressed: bool,
985}
986
987impl AuditDiff {
988 pub fn to_json_pretty(&self) -> Result<String> {
990 Ok(serde_json::to_string_pretty(self)?)
991 }
992
993 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 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
1049pub(crate) fn round2(v: f32) -> f32 {
1051 (v * 100.0).round() / 100.0
1052}
1053
1054pub(crate) fn round4(v: f32) -> f32 {
1056 (v * 10_000.0).round() / 10_000.0
1057}