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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::error::{Error, Result};
use crate::schema::{collect_schema_params, has_description, schema_is_container};
use crate::text::estimate_tokens;
/// Current JSON report schema version emitted by `mcp-vol`.
pub const SCHEMA_VERSION: &str = "0.1.0";
/// Behavioral hints matching MCP `ToolAnnotations`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolHints {
/// Optional human-readable display title from annotations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
/// If `true`, the tool does not modify its environment.
#[serde(
default,
alias = "read_only_hint",
alias = "read_only",
skip_serializing_if = "Option::is_none"
)]
pub read_only_hint: Option<bool>,
/// If `true`, the tool may perform destructive updates.
#[serde(
default,
alias = "destructive_hint",
alias = "destructive",
skip_serializing_if = "Option::is_none"
)]
pub destructive_hint: Option<bool>,
/// If `true`, repeated calls with identical arguments have no extra effect.
#[serde(
default,
alias = "idempotent_hint",
alias = "idempotent",
skip_serializing_if = "Option::is_none"
)]
pub idempotent_hint: Option<bool>,
/// If `true`, the tool interacts with an open world of external entities.
#[serde(
default,
alias = "open_world_hint",
alias = "open_world",
skip_serializing_if = "Option::is_none"
)]
pub open_world_hint: Option<bool>,
}
impl ToolHints {
/// Returns `true` if at least one behavioral hint boolean is explicitly declared.
pub fn has_any_behavior_hint(&self) -> bool {
self.read_only_hint.is_some()
|| self.destructive_hint.is_some()
|| self.idempotent_hint.is_some()
|| self.open_world_hint.is_some()
}
}
/// Source file coordinates populated by static source scanners (`mcp-vol scan`).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SourceLocation {
/// Relative or absolute path to the source file declaring the tool.
pub file: String,
/// 1-based line number of the tool declaration.
pub line: usize,
/// 1-based column number of the tool declaration.
pub column: usize,
}
/// Canonical, SDK-agnostic representation of an MCP tool definition.
///
/// Deserializes seamlessly from MCP `tools/list` JSON (camelCase or snake_case)
/// and converts directly from `&rmcp::model::Tool` when the `rmcp` feature is enabled.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolSpec {
/// Unique tool identifier exposed to the model.
pub name: String,
/// Optional human-readable display title.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
/// Natural-language description read by AI agents during tool selection.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// JSON Schema object describing input parameters.
#[serde(default, alias = "input_schema")]
pub input_schema: Map<String, Value>,
/// Optional JSON Schema object describing structured output.
#[serde(
default,
alias = "output_schema",
skip_serializing_if = "Option::is_none"
)]
pub output_schema: Option<Map<String, Value>>,
/// Optional MCP behavioral annotations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub annotations: Option<ToolHints>,
/// Optional static source file location populated by [`crate::scan_path`] / `mcp-vol scan`.
#[serde(
default,
alias = "source_location",
skip_serializing_if = "Option::is_none"
)]
pub source_location: Option<SourceLocation>,
/// Optional origin MCP server identifier populated during multi-server composition.
#[serde(
default,
alias = "source_server",
skip_serializing_if = "Option::is_none"
)]
pub source_server: Option<String>,
}
impl ToolSpec {
/// Creates a new `ToolSpec` with a name, optional description, and JSON Schema object.
#[must_use]
pub fn new(
name: impl Into<String>,
description: Option<impl Into<String>>,
input_schema: Map<String, Value>,
) -> Self {
Self {
name: name.into(),
title: None,
description: description.map(Into::into),
input_schema,
output_schema: None,
annotations: None,
source_location: None,
source_server: None,
}
}
/// Attaches a human-readable title.
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
/// Attaches behavioral annotations.
#[must_use]
pub fn with_annotations(mut self, annotations: ToolHints) -> Self {
self.annotations = Some(annotations);
self
}
/// Attaches an output JSON Schema.
#[must_use]
pub fn with_output_schema(mut self, output_schema: Map<String, Value>) -> Self {
self.output_schema = Some(output_schema);
self
}
/// Attaches static source file coordinates for SARIF `physicalLocation` emission.
#[must_use]
pub fn with_source_location(mut self, location: SourceLocation) -> Self {
self.source_location = Some(location);
self
}
/// Tags this tool with the name of the MCP server that provides it.
#[must_use]
pub fn with_source_server(mut self, server: impl Into<String>) -> Self {
self.source_server = Some(server.into());
self
}
/// Returns the top-level `properties` object map from `input_schema`, if present.
pub fn schema_properties(&self) -> Option<&Map<String, Value>> {
self.input_schema.get("properties")?.as_object()
}
/// Returns the list of top-level parameter names declared in `input_schema.properties`.
pub fn parameter_names(&self) -> Vec<&str> {
self.schema_properties()
.map(|props| props.keys().map(String::as_str).collect())
.unwrap_or_default()
}
/// Returns the list of top-level required parameter names declared in `input_schema.required`.
pub fn required_parameters(&self) -> Vec<&str> {
self.input_schema
.get("required")
.and_then(Value::as_array)
.map(|arr| arr.iter().filter_map(Value::as_str).collect())
.unwrap_or_default()
}
/// Fraction of all schema properties (including nested objects and resolved `$ref`s)
/// that declare a non-empty `description` string (`0.0..=1.0`).
/// Returns `1.0` when the tool takes zero parameters.
pub fn schema_description_coverage(&self) -> f32 {
let params = collect_schema_params(&self.input_schema);
if params.is_empty() {
return 1.0;
}
let documented = params.iter().filter(|p| has_description(p.schema)).count();
documented as f32 / params.len() as f32
}
/// Deterministic invocation complexity cost used for TDQS-style shadowed-tool detection.
///
/// Weighted by required arguments (2 pts), optional arguments (1 pt),
/// nested object/array arguments (+1 pt), and enum/pattern constraints (+1 pt).
pub fn invocation_cost(&self) -> usize {
let params = collect_schema_params(&self.input_schema);
let mut cost = 0usize;
for param in params {
if param.is_required {
cost += 2;
} else {
cost += 1;
}
if schema_is_container(param.schema) {
cost += 1;
}
if param.schema.get("enum").is_some()
|| param.schema.get("pattern").is_some()
|| param.schema.get("oneOf").is_some()
|| param.schema.get("anyOf").is_some()
{
cost += 1;
}
}
cost
}
/// Estimated token count of the description prose alone.
pub fn estimated_description_tokens(&self) -> usize {
self.description
.as_deref()
.map(estimate_tokens)
.unwrap_or(0)
}
fn wire_json_string(&self) -> String {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct WireTool<'a> {
name: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
title: &'a Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
description: &'a Option<String>,
input_schema: &'a Map<String, Value>,
#[serde(skip_serializing_if = "Option::is_none")]
output_schema: &'a Option<Map<String, Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
annotations: &'a Option<ToolHints>,
}
let wire = WireTool {
name: &self.name,
title: &self.title,
description: &self.description,
input_schema: &self.input_schema,
output_schema: &self.output_schema,
annotations: &self.annotations,
};
serde_json::to_string(&wire).unwrap_or_default()
}
/// Estimated token count of the full serialized wire MCP tool payload sent in an LLM context window.
/// Excludes non-wire metadata (`source_location`, `source_server`).
pub fn estimated_total_tokens(&self) -> usize {
estimate_tokens(&self.wire_json_string())
}
/// Stable FNV-1a 64-bit hex fingerprint of the canonical wire MCP tool definition.
/// Used by `diff_reports` to flag prompt-cache-busting schema mutations without false positives
/// from line-number shifts.
pub fn fingerprint(&self) -> String {
let canonical = self.wire_json_string();
let mut hash: u64 = 0xcbf29ce484222325;
for byte in canonical.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
format!("{hash:016x}")
}
}
/// Collection of MCP tools audited or evaluated together as a single catalog.
#[derive(Debug, Clone, Default)]
pub struct Catalog {
tools: Vec<ToolSpec>,
}
impl Catalog {
/// Builds a catalog from any iterator of [`ToolSpec`].
#[must_use]
pub fn new(tools: impl IntoIterator<Item = ToolSpec>) -> Self {
Self {
tools: tools.into_iter().collect(),
}
}
/// Parses a catalog from standard MCP JSON shapes:
/// - JSON-RPC 2.0 `tools/list` response (`{"jsonrpc":"2.0","result":{"tools":[...]}}`)
/// - MCP `ListToolsResult` object (`{"tools":[...]}`)
/// - Raw JSON array of tool definitions (`[...]`)
pub fn from_mcp_json(json: &str) -> Result<Self> {
let value: Value = serde_json::from_str(json)?;
let tools_val = if value.is_array() {
value
} else if let Some(tools) = value.get("tools") {
tools.clone()
} else if let Some(tools) = value.get("result").and_then(|r| r.get("tools")) {
tools.clone()
} else {
return Err(Error::InvalidCatalogFormat(
"expected a JSON array of tools, an object with a `tools` array, or a JSON-RPC `result.tools` envelope".to_string(),
));
};
let tools: Vec<ToolSpec> = serde_json::from_value(tools_val)?;
Ok(Self { tools })
}
/// Returns a slice of all tools in the catalog.
pub fn tools(&self) -> &[ToolSpec] {
&self.tools
}
/// Number of tools in the catalog.
pub fn len(&self) -> usize {
self.tools.len()
}
/// Returns `true` if the catalog contains no tools.
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
/// Looks up the first tool with the given exact name.
pub fn get(&self, name: &str) -> Option<&ToolSpec> {
self.tools.iter().find(|t| t.name == name)
}
/// Returns a cloned catalog where every tool is tagged with `source_server`.
#[must_use]
pub fn with_source_server(&self, server: impl Into<String>) -> Self {
let srv = server.into();
let tools = self
.tools
.iter()
.cloned()
.map(|mut t| {
t.source_server = Some(srv.clone());
t
})
.collect();
Self { tools }
}
/// Returns a cloned catalog where every tool name is prefixed with `prefix` (unless it
/// already starts with `prefix`), automatically appending `_` when `prefix` does not end
/// with `_`, `-`, or `.`. Useful for eliminating cross-server name collisions.
#[must_use]
pub fn with_namespace_prefix(&self, prefix: &str) -> Self {
let normalized = if prefix.is_empty()
|| prefix.ends_with('_')
|| prefix.ends_with('-')
|| prefix.ends_with('.')
{
prefix.to_string()
} else {
format!("{prefix}_")
};
let tools = self
.tools
.iter()
.cloned()
.map(|mut t| {
if !normalized.is_empty() && !t.name.starts_with(&normalized) {
t.name = format!("{normalized}{}", t.name);
}
t
})
.collect();
Self { tools }
}
/// Total estimated context-window tokens consumed by serializing all tools in this catalog.
pub fn estimated_total_tokens(&self) -> usize {
self.tools
.iter()
.map(ToolSpec::estimated_total_tokens)
.sum()
}
/// Serializes the catalog in standard MCP `ListToolsResult` JSON shape (`{"tools":[...]}`).
pub fn to_mcp_json(&self) -> Result<String> {
let wrapper = serde_json::json!({ "tools": self.tools });
Ok(serde_json::to_string_pretty(&wrapper)?)
}
/// Serializes the catalog as minified single-line MCP `ListToolsResult` JSON.
pub fn to_mcp_json_compact(&self) -> Result<String> {
let wrapper = serde_json::json!({ "tools": self.tools });
Ok(serde_json::to_string(&wrapper)?)
}
}
/// Six research-backed quality dimensions aligned with arXiv 2602.14878 and Glama TDQS.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Dimension {
/// How clearly the tool states its concrete action, target resource, and return value.
PurposeClarity,
/// Whether the description guides when to call (and when not to call) the tool.
UsageGuidelines,
/// Whether annotations and prose honestly disclose side effects, safety, and limits.
BehavioralTransparency,
/// Whether parameters are semantically named, documented, and constrained.
ParameterSemantics,
/// Information density and adherence to token budgets without duplicating schemas.
Conciseness,
/// Catalog-level disambiguation, collision avoidance, and shadowing resilience.
ContextualCompleteness,
}
impl Dimension {
/// All six dimensions in canonical display order.
pub const ALL: [Dimension; 6] = [
Dimension::PurposeClarity,
Dimension::UsageGuidelines,
Dimension::BehavioralTransparency,
Dimension::ParameterSemantics,
Dimension::Conciseness,
Dimension::ContextualCompleteness,
];
/// Machine-readable snake_case identifier.
pub const fn as_str(self) -> &'static str {
match self {
Dimension::PurposeClarity => "purpose_clarity",
Dimension::UsageGuidelines => "usage_guidelines",
Dimension::BehavioralTransparency => "behavioral_transparency",
Dimension::ParameterSemantics => "parameter_semantics",
Dimension::Conciseness => "conciseness",
Dimension::ContextualCompleteness => "contextual_completeness",
}
}
/// Weight used when rolling up the 6 dimension scores into a single 1.0–5.0 overall score.
pub const fn weight(self) -> f32 {
match self {
Dimension::PurposeClarity => 0.25,
Dimension::UsageGuidelines => 0.20,
Dimension::BehavioralTransparency => 0.15,
Dimension::ParameterSemantics => 0.20,
Dimension::Conciseness => 0.10,
Dimension::ContextualCompleteness => 0.10,
}
}
}
impl fmt::Display for Dimension {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Severity level of an audit finding, ordered `Info < Warn < Error`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
/// Informational improvement suggestion.
Info,
/// Quality defect likely to degrade selection accuracy or token efficiency.
Warn,
/// Critical specification defect or collision that directly causes agent failures.
Error,
}
impl Severity {
/// Canonical lowercase label.
pub const fn as_str(self) -> &'static str {
match self {
Severity::Info => "info",
Severity::Warn => "warn",
Severity::Error => "error",
}
}
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Letter grade tier derived from the 1.0–5.0 overall quality score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Tier {
/// 4.50 – 5.00
A,
/// 3.50 – 4.49
B,
/// 2.50 – 3.49
C,
/// 1.80 – 2.49
D,
/// Below 1.80
F,
}
impl Tier {
/// Converts a 1.0–5.0 score to a letter grade tier.
pub fn from_score(score: f32) -> Self {
if score >= 4.5 {
Tier::A
} else if score >= 3.5 {
Tier::B
} else if score >= 2.5 {
Tier::C
} else if score >= 1.8 {
Tier::D
} else {
Tier::F
}
}
}
impl fmt::Display for Tier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
/// Static documentation metadata for a built-in `VOL001`–`VOL024` rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleMeta {
/// Stable rule code (e.g., `"VOL001"`).
pub code: String,
/// Kebab-case rule identifier (e.g., `"missing-description"`).
pub slug: String,
/// Dimension scored by this rule.
pub dimension: Dimension,
/// Default severity level.
pub default_severity: Severity,
/// Concise human/agent explanation of what the rule checks.
pub summary: String,
/// Default remediation guidance.
pub remediation: String,
}
/// A single actionable diagnostic finding emitted by [`crate::Auditor`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Finding {
/// Stable rule ID (`VOL001`–`VOL024`).
pub code: String,
/// Kebab-case rule slug.
pub slug: String,
/// Diagnostic severity.
pub severity: Severity,
/// Affected quality dimension.
pub dimension: Dimension,
/// Name of the primary tool (or `"<catalog>"` for catalog-wide findings).
pub tool: String,
/// Related sibling tool name for pairwise rules (`VOL005`, `VOL014`, `VOL015`).
#[serde(skip_serializing_if = "Option::is_none")]
pub related_tool: Option<String>,
/// RFC 6901 JSON Pointer locating the offending field within the tool catalog.
pub json_pointer: String,
/// Concise factual description of the defect.
pub message: String,
/// Structured evidence fields (scores, matched terms, offending parameters).
pub evidence: Value,
/// Actionable fix instruction designed for AI coding agents and maintainers.
pub fix_hint: String,
/// Optional static source coordinates propagated from [`ToolSpec::source_location`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_location: Option<SourceLocation>,
/// Optional origin MCP server name propagated from [`ToolSpec::source_server`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_server: Option<String>,
}
/// Pairwise similarity and shadowing entry between two tools in the same catalog.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CollisionPair {
/// Lexicographically first tool name.
pub tool_a: String,
/// Lexicographically second tool name.
pub tool_b: String,
/// Composite similarity score in `0.0..=1.0`.
pub score: f32,
/// Canonicalized name token + trigram similarity in `0.0..=1.0`.
pub name_similarity: f32,
/// Catalog-scoped TF-IDF cosine similarity of prose in `0.0..=1.0`.
pub description_similarity: f32,
/// Jaccard overlap of input parameter names in `0.0..=1.0`.
pub param_overlap: f32,
/// Top shared semantic terms driving the overlap.
pub shared_terms: Vec<String>,
/// True if one tool's lighter schema can shadow the other tool's heavier schema.
pub shadowing_risk: bool,
/// Cheaper sibling tool when `shadowing_risk` is `true`.
#[serde(skip_serializing_if = "Option::is_none")]
pub cheaper_tool: Option<String>,
/// Heavier shadowed sibling tool when `shadowing_risk` is `true`.
#[serde(skip_serializing_if = "Option::is_none")]
pub expensive_tool: Option<String>,
}
/// Per-tool quality score breakdown.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolScore {
/// Tool name.
pub tool: String,
/// Weighted 1.0–5.0 quality score for this tool.
pub overall: f32,
/// Letter grade tier for this tool.
pub tier: Tier,
/// Estimated total serialized tokens for this tool.
pub estimated_tokens: usize,
/// Deterministic invocation complexity cost.
pub invocation_cost: usize,
/// Per-dimension 1.0–5.0 scores.
pub dimension_scores: BTreeMap<Dimension, f32>,
/// Count of `Error` findings on this tool.
pub error_count: usize,
/// Count of `Warn` findings on this tool.
pub warning_count: usize,
/// Count of `Info` findings on this tool.
pub info_count: usize,
}
/// Top-level summary metrics of an [`AuditReport`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditSummary {
/// `true` when no findings meet or exceed the configured `fail_on` severity.
pub passed: bool,
/// Total number of audited tools.
pub tool_count: usize,
/// Total estimated context-window tokens for the catalog.
pub estimated_catalog_tokens: usize,
/// Estimated uncached LLM input cost per turn for loading this tool catalog (USD).
#[serde(default)]
pub estimated_cost_per_turn_usd: f32,
/// Estimated uncached LLM input cost across a 200-turn agent session (USD).
#[serde(default)]
pub estimated_200_turn_session_usd: f32,
/// Estimated prompt-cached LLM input cost across a 200-turn session (1 cold + 199 cached reads, USD).
#[serde(default)]
pub estimated_200_turn_cached_usd: f32,
/// Catalog-level weighted quality score (`1.0..=5.0`).
pub overall_score: f32,
/// Lowest per-tool overall score in the catalog (`1.0..=5.0`).
pub worst_tool_score: f32,
/// Catalog letter grade tier.
pub tier: Tier,
/// Total `Error` findings.
pub error_count: usize,
/// Total `Warn` findings.
pub warning_count: usize,
/// Total `Info` findings.
pub info_count: usize,
/// Number of pairs exceeding the collision threshold.
pub collision_count: usize,
/// Number of pairs flagged with shadowing risk.
pub shadowing_count: usize,
}
/// Prioritized per-tool repair entry inside a [`RepairPlan`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolRepairItem {
/// Tool name (or `"<catalog>"`).
pub tool: String,
/// Current per-tool score (`1.0..=5.0`).
pub current_score: f32,
/// Current tier.
pub tier: Tier,
/// Estimated total serialized tokens for this tool.
pub estimated_tokens: usize,
/// Ordered findings affecting this tool, highest severity first.
pub findings: Vec<Finding>,
}
/// Compact, worst-tool-first repair roadmap designed for AI coding agents.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RepairPlan {
/// Report schema version.
pub schema_version: String,
/// Current catalog overall score.
pub current_overall_score: f32,
/// Current catalog tier.
pub current_tier: Tier,
/// Number of tools requiring edits.
pub tools_to_fix: usize,
/// Total findings across all repair items.
pub total_findings: usize,
/// Repair items sorted worst-tool-first so fixing top items yields the biggest score lift.
pub items: Vec<ToolRepairItem>,
}
impl RepairPlan {
/// Serializes this repair plan as pretty-printed JSON.
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
/// Formats a token-efficient Markdown checklist ready to paste into an AI coding agent.
pub fn to_markdown(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"## `mcp-vol` Prioritized Repair Plan (Current: {:.2}/5.00, Tier {})\n\n",
self.current_overall_score, self.current_tier
));
if self.items.is_empty() {
out.push_str("All tools passed with zero findings. No edits required.\n");
return out;
}
out.push_str(&format!(
"Fix these **{} tool(s)** in order (worst-scoring first for maximum TDQS/catalog impact):\n\n",
self.tools_to_fix
));
for (idx, item) in self.items.iter().enumerate() {
out.push_str(&format!(
"### {}. `{}` — Score {:.2}/5.00 (Tier {}, ~{} tokens)\n",
idx + 1,
item.tool,
item.current_score,
item.tier,
item.estimated_tokens
));
for f in &item.findings {
out.push_str(&format!(
"- **[{} {}]** (`{}`): {}\n - **Fix:** {}\n",
f.severity.as_str().to_uppercase(),
f.code,
f.json_pointer,
f.message,
f.fix_hint
));
}
out.push('\n');
}
out
}
}
/// Complete deterministic audit report returned by [`crate::Auditor::audit`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditReport {
/// Schema version for forward-compatible machine parsing.
pub schema_version: String,
/// High-level summary counters and gate status.
pub summary: AuditSummary,
/// Catalog-level mean score (`1.0..=5.0`) for each of the 6 dimensions.
pub dimension_scores: BTreeMap<Dimension, f32>,
/// Per-tool score breakdown sorted by tool name.
pub tool_scores: Vec<ToolScore>,
/// Actionable findings sorted deterministically by severity (desc), code, and tool.
pub findings: Vec<Finding>,
/// High-similarity and shadowed tool pairs sorted descending by similarity score.
pub collisions: Vec<CollisionPair>,
/// Stable per-tool fingerprints for prompt-cache drift detection in [`AuditDiff`].
#[serde(default)]
pub tool_fingerprints: BTreeMap<String, String>,
}
impl AuditReport {
/// Returns `true` if the catalog passed the configured severity gate.
pub fn passed(&self) -> bool {
self.summary.passed
}
/// Serializes this report as pretty-printed canonical JSON.
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
/// Serializes this report as minified single-line JSON to conserve AI agent context tokens.
pub fn to_json_compact(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
/// Returns a cloned report retaining at most `max_findings` highest-severity findings,
/// preserving exact `summary` totals so AI agents stay inside strict token budgets.
#[must_use]
pub fn with_max_findings(&self, max_findings: usize) -> Self {
let mut cloned = self.clone();
cloned.findings.truncate(max_findings);
cloned
}
/// Generates a worst-tool-first [`RepairPlan`] grouped by tool for AI coding agents.
pub fn to_repair_plan(&self) -> RepairPlan {
let mut grouped: BTreeMap<String, Vec<Finding>> = BTreeMap::new();
for f in &self.findings {
grouped.entry(f.tool.clone()).or_default().push(f.clone());
}
let score_map: BTreeMap<&str, &ToolScore> = self
.tool_scores
.iter()
.map(|ts| (ts.tool.as_str(), ts))
.collect();
let mut items: Vec<ToolRepairItem> = grouped
.into_iter()
.map(|(tool, findings)| {
let (current_score, tier, estimated_tokens) = match score_map.get(tool.as_str()) {
Some(ts) => (ts.overall, ts.tier, ts.estimated_tokens),
None => (
self.summary.overall_score,
self.summary.tier,
self.summary.estimated_catalog_tokens,
),
};
ToolRepairItem {
tool,
current_score,
tier,
estimated_tokens,
findings,
}
})
.collect();
items.sort_by(|a, b| {
a.current_score
.total_cmp(&b.current_score)
.then_with(|| b.findings.len().cmp(&a.findings.len()))
.then_with(|| a.tool.cmp(&b.tool))
});
RepairPlan {
schema_version: self.schema_version.clone(),
current_overall_score: self.summary.overall_score,
current_tier: self.summary.tier,
tools_to_fix: items.len(),
total_findings: self.findings.len(),
items,
}
}
/// Formats a concise human-readable terminal summary.
pub fn to_text(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"mcp-vol audit: {} | score {:.2}/5.00 (Tier {}) | worst tool {:.2} | {} tools | ~{} tokens (~${:.2}/200-turn uncached, ~${:.2} cached)\n",
if self.summary.passed { "PASS" } else { "FAIL" },
self.summary.overall_score,
self.summary.tier,
self.summary.worst_tool_score,
self.summary.tool_count,
self.summary.estimated_catalog_tokens,
self.summary.estimated_200_turn_session_usd,
self.summary.estimated_200_turn_cached_usd,
));
out.push_str(&format!(
"findings: {} error, {} warn, {} info | collisions: {} | shadowing risks: {}\n",
self.summary.error_count,
self.summary.warning_count,
self.summary.info_count,
self.summary.collision_count,
self.summary.shadowing_count,
));
if !self.findings.is_empty() {
out.push('\n');
for f in &self.findings {
let mut target = match &f.related_tool {
Some(rel) => format!("{} <-> {}", f.tool, rel),
None => f.tool.clone(),
};
if let Some(srv) = &f.source_server {
target = format!("[{srv}] {target}");
}
if let Some(loc) = &f.source_location {
target.push_str(&format!(" ({}:{})", loc.file, loc.line));
}
out.push_str(&format!(
"[{}] {} ({}) {}\n {}\n fix: {}\n",
f.severity.as_str().to_uppercase(),
f.code,
f.slug,
target,
f.message,
f.fix_hint
));
}
}
out
}
/// Formats a GitHub-Flavored Markdown summary suitable for Pull Request comments.
pub fn to_markdown(&self) -> String {
let status = if self.summary.passed { "PASS" } else { "FAIL" };
let mut out = String::new();
out.push_str(&format!(
"### `mcp-vol` Audit Report — **{status}** (Score **{:.2}/5.00**, Tier **{}**)\n\n",
self.summary.overall_score, self.summary.tier
));
out.push_str("| Tools | Worst Tool | Est. Tokens | Est. 200-Turn Cost (Uncached / Cached) | Errors | Warnings | Collisions | Shadowing |\n");
out.push_str("|---:|---:|---:|---:|---:|---:|---:|---:|\n");
out.push_str(&format!(
"| {} | {:.2} | ~{} | ${:.2} / ${:.2} | {} | {} | {} | {} |\n\n",
self.summary.tool_count,
self.summary.worst_tool_score,
self.summary.estimated_catalog_tokens,
self.summary.estimated_200_turn_session_usd,
self.summary.estimated_200_turn_cached_usd,
self.summary.error_count,
self.summary.warning_count,
self.summary.collision_count,
self.summary.shadowing_count,
));
out.push_str("#### Dimension Scores\n\n| Dimension | Score |\n|---|---:|\n");
for dim in Dimension::ALL {
let s = self.dimension_scores.get(&dim).copied().unwrap_or(5.0);
out.push_str(&format!("| `{}` | {:.2} / 5.00 |\n", dim.as_str(), s));
}
if !self.findings.is_empty() {
out.push_str("\n#### Findings\n\n| Severity | Code | Tool | Issue | Fix Hint |\n|---|---|---|---|---|\n");
for f in self.findings.iter().take(50) {
let mut target = match &f.related_tool {
Some(rel) => format!("`{}` ↔ `{}`", f.tool, rel),
None => format!("`{}`", f.tool),
};
if let Some(loc) = &f.source_location {
target.push_str(&format!(" (`{}:{}`)", loc.file, loc.line));
}
out.push_str(&format!(
"| `{}` | `{}` | {} | {} | {} |\n",
f.severity.as_str().to_uppercase(),
f.code,
target,
f.message.replace('|', "\\|"),
f.fix_hint.replace('|', "\\|")
));
}
if self.findings.len() > 50 {
out.push_str(&format!(
"\n*Showing first 50 of {} findings. Run `mcp-vol check --format json` for the full list.*\n",
self.findings.len()
));
}
}
out
}
}
/// Regression and prompt-cache volatility diff between two [`AuditReport`] snapshots.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditDiff {
/// Schema version.
pub schema_version: String,
/// Change in overall catalog score (`current - baseline`).
pub score_delta: f32,
/// Change in estimated catalog tokens (`current - baseline`).
pub token_delta: i64,
/// Change in estimated 200-turn uncached session cost (USD).
#[serde(default)]
pub session_cost_delta_usd: f32,
/// Change in error finding count.
pub error_delta: i64,
/// Change in warning finding count.
pub warning_delta: i64,
/// Findings present in `current` that were not in `baseline`.
pub new_findings: Vec<Finding>,
/// Findings present in `baseline` that were fixed in `current`.
pub resolved_findings: Vec<Finding>,
/// Tools added since baseline.
pub added_tools: Vec<String>,
/// Tools removed since baseline.
pub removed_tools: Vec<String>,
/// Tools whose serialized schema or description changed since baseline.
pub modified_tools: Vec<String>,
/// `true` if any tool was added, removed, or modified (invalidating LLM prompt cache).
pub cache_busting_change: bool,
/// `true` if score dropped, error count increased, or new errors appeared.
pub regressed: bool,
}
impl AuditDiff {
/// Serializes this diff as pretty-printed JSON.
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
/// Formats a concise human-readable diff summary.
pub fn to_text(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"mcp-vol diff: {} | score {:+.2} | tokens {:+} (${:+.2}/200-turn) | errors {:+} | warnings {:+}\n",
if self.regressed { "REGRESSED" } else { "OK" },
self.score_delta,
self.token_delta,
self.session_cost_delta_usd,
self.error_delta,
self.warning_delta,
));
out.push_str(&format!(
"prompt cache impact: {} (added: {}, removed: {}, modified: {})\n",
if self.cache_busting_change {
"CACHE INVALIDATED"
} else {
"STABLE"
},
self.added_tools.len(),
self.removed_tools.len(),
self.modified_tools.len(),
));
out.push_str(&format!(
"findings: +{} new, -{} resolved\n",
self.new_findings.len(),
self.resolved_findings.len(),
));
out
}
/// Formats a GitHub-Flavored Markdown diff summary for Pull Request comments.
pub fn to_markdown(&self) -> String {
let status = if self.regressed { "REGRESSED" } else { "OK" };
let cache = if self.cache_busting_change {
"INVALIDATED"
} else {
"STABLE"
};
let mut out = String::new();
out.push_str(&format!("### `mcp-vol` Diff — **{status}**\n\n"));
out.push_str("| Score Delta | Token Delta | 200-Turn Cost Delta | New / Resolved Findings | Prompt Cache |\n");
out.push_str("|---:|---:|---:|---:|:---:|\n");
out.push_str(&format!(
"| `{:+.2}` | `{:+}` | `${:+.2}` | `+{}` / `-{}` | **{}** |\n",
self.score_delta,
self.token_delta,
self.session_cost_delta_usd,
self.new_findings.len(),
self.resolved_findings.len(),
cache,
));
out
}
}
/// Rounds a floating-point metric to 2 decimal places for stable JSON snapshots.
pub(crate) fn round2(v: f32) -> f32 {
(v * 100.0).round() / 100.0
}
/// Rounds a floating-point metric to 4 decimal places for similarity and ranking scores.
pub(crate) fn round4(v: f32) -> f32 {
(v * 10_000.0).round() / 10_000.0
}