mcp_vol/lib.rs
1#![deny(missing_docs)]
2//! # `mcp-vol` — Deterministic MCP Tool Volatility & Selection Auditor
3//!
4//! Zero-LLM, sub-millisecond **MCP tool linter**, **deep JSON Schema walker**, **sibling
5//! collision analyzer**, **RFC 6902 patch suggester**, and **BM25 / TF-IDF / Hybrid RRF
6//! evaluation harness** designed specifically for **AI coding agents** and Rust (`rmcp`) CI gates.
7//!
8//! ## AI Agent Quick Reference (Single-Read Cheat Sheet)
9//!
10//! ### 1. Recommended `Cargo.toml`
11//! ```toml
12//! [dev-dependencies]
13//! mcp-vol = { version = "0.1", features = ["rmcp"] }
14//! ```
15//!
16//! ### 2. One-Line Prelude & Facades (Minimal Boilerplate)
17//! ```rust
18//! use mcp_vol::prelude::*;
19//!
20//! let json = r#"{
21//! "tools": [
22//! {
23//! "name": "list_issues",
24//! "description": "Lists open or closed GitHub issues for a repository. Use this when browsing issues; for cross-repo keyword search use search_issues. Returns at most 50 issues per page.",
25//! "inputSchema": {
26//! "type": "object",
27//! "properties": {
28//! "repo": { "type": "string", "description": "Repository in owner/name format." },
29//! "state": { "type": "string", "enum": ["open", "closed", "all"], "description": "Issue state filter." },
30//! "limit": { "type": "integer", "description": "Maximum issues per page (default 50)." }
31//! },
32//! "required": ["repo"]
33//! },
34//! "annotations": {
35//! "readOnlyHint": true,
36//! "destructiveHint": false,
37//! "idempotentHint": true,
38//! "openWorldHint": true
39//! }
40//! }
41//! ]
42//! }"#;
43//!
44//! // One-line JSON audit + assertion
45//! let report = audit_json(json).unwrap();
46//! assert!(report.passed());
47//!
48//! // Selection routing eval (Bm25Ranker, TfIdfRanker, or HybridRanker)
49//! let catalog = Catalog::from_mcp_json(json).unwrap();
50//! assert_catalog_clean(&catalog);
51//! let suite = EvalSuite::new([EvalCase {
52//! id: "c1".into(),
53//! query: "show open issues in this repo".into(),
54//! expected_tool: "list_issues".into(),
55//! acceptable_tools: vec![],
56//! }]);
57//! assert_eq!(suite.run(&catalog, &Bm25Ranker::default(), 3).top1_accuracy, 1.0);
58//! assert_eq!(suite.run(&catalog, &HybridRanker::default(), 3).top1_accuracy, 1.0);
59//! ```
60//!
61//! ### 3. One-Line `rmcp` v3.12 Test Gate (`features = ["rmcp"]`)
62//! ```rust,ignore
63//! #[test]
64//! fn mcp_tools_are_agent_ready() {
65//! let tools: Vec<rmcp::model::Tool> = my_server_tools();
66//! mcp_vol::assert_rmcp_tools_clean(&tools);
67//! }
68//! ```
69//!
70//! ### 4. Rule Codes (`VOL001`–`VOL024`)
71//! - **Purpose Clarity:** `VOL001` missing description, `VOL002` tautology, `VOL003` vague verb
72//! - **Usage Guidelines:** `VOL004` missing usage cue (catalog ≥ 5), `VOL005` missing sibling boundary
73//! - **Behavioral Transparency:** `VOL006` annotation contradiction, `VOL007` missing annotations,
74//! `VOL008` undisclosed side effect/limit, `VOL018` unbounded list/search,
75//! `VOL019` coercive routing / hidden directive, `VOL024` missing return contract
76//! - **Parameter Semantics (recursive `$ref`/nested):** `VOL009` undocumented param,
77//! `VOL010` unconstrained closed-set string, `VOL011` opaque name or missing date/regex format,
78//! `VOL020` incompatible/broken `inputSchema` or `$ref`, `VOL021` unsatisfiable schema constraint
79//! - **Conciseness:** `VOL012` token budget exceeded (>250/tool or >15k/catalog), `VOL013` schema-prose duplication,
80//! `VOL023` excessive parameter count (>12) or nesting depth (>4)
81//! - **Contextual Completeness:** `VOL014` tool collision (≥0.72 or dup), `VOL015` TDQS shadowing risk,
82//! `VOL016` empty `outputSchema` stub, `VOL017` SEP-986 / mixed naming style,
83//! `VOL022` duplicate or placeholder description
84//!
85//! ### 5. Mechanical RFC 6902 Auto-Fix, Baseline Eval Bootstrapping & Self-Describing Schemas
86//! ```rust
87//! use mcp_vol::prelude::*;
88//!
89//! let broken = r#"[{"name":"delete_all","description":"Deletes records.","inputSchema":{"type":"object"},"annotations":{"readOnlyHint":true,"destructiveHint":false}}]"#;
90//! let catalog = Catalog::from_mcp_json(broken).unwrap();
91//! let report = Auditor::default().audit(&catalog);
92//! let patches = suggest_patches(&catalog, &report);
93//! assert!(patches.patch_count >= 1);
94//!
95//! // Apply high-confidence patches deterministically and verify score lift
96//! let (fixed_catalog, applied) = apply_patches(&catalog, &AuditConfig::default(), PatchConfidence::High);
97//! assert_eq!(applied.errors_after, 0);
98//! assert!(applied.score_after > applied.score_before);
99//!
100//! // Synthesize a starter routing eval suite in <1 ms, index with Bm25Index & inspect JSON Schemas
101//! let suite = EvalSuite::generate_baseline(&fixed_catalog);
102//! let index = Bm25Index::build(&fixed_catalog);
103//! assert_eq!(suite.run(&fixed_catalog, &index, 1).top1_accuracy, 1.0);
104//! assert!(json_schema_for(SchemaTarget::AuditReport)["properties"]["findings"].is_object());
105//! ```
106
107mod auditor;
108mod collision;
109mod compose;
110mod error;
111mod eval;
112mod json_schema;
113mod model;
114mod patch;
115mod ranker;
116#[cfg(feature = "rmcp")]
117mod rmcp_adapter;
118mod rules;
119#[cfg(feature = "sarif")]
120mod sarif;
121mod schema;
122mod source_scan;
123mod text;
124
125pub use auditor::{diff_reports, AuditConfig, Auditor};
126pub use compose::{
127 compose_catalogs, parse_mcp_client_config, ComposeReport, CrossServerCollision,
128 DeferralRecommendation, McpServerLaunch, ServerTokenShare,
129};
130pub use error::{Error, Result};
131pub use eval::{
132 compare_rankers, ConfusionEntry, EvalCase, EvalFailure, EvalReport, EvalSuite,
133 RankerComparison, RankerScoreRow,
134};
135pub use json_schema::{json_schema_for, SchemaTarget};
136pub use model::{
137 AuditDiff, AuditReport, AuditSummary, Catalog, CollisionPair, Dimension, Finding, RepairPlan,
138 RuleMeta, Severity, SourceLocation, Tier, ToolHints, ToolRepairItem, ToolScore, ToolSpec,
139 SCHEMA_VERSION,
140};
141pub use patch::{
142 apply_patches, suggest_patches, ApplyReport, JsonPatchOp, PatchConfidence, PatchSet,
143 SuggestedPatch,
144};
145pub use ranker::{
146 explain_query, Bm25Index, Bm25Ranker, HybridRanker, QueryExplanation, RankedTool, Ranker,
147 TermContribution, TfIdfRanker, ToolExplanation,
148};
149#[cfg(feature = "rmcp")]
150pub use rmcp_adapter::{assert_rmcp_tools_clean, audit_rmcp};
151pub use rules::all_rules;
152pub use source_scan::{scan_path, scan_source_str, SourceLanguage, SourceScanReport};
153
154/// Convenience one-line wildcard import for AI agents and test modules: `use mcp_vol::prelude::*;`.
155pub mod prelude {
156 #[cfg(feature = "rmcp")]
157 pub use crate::rmcp_adapter::{assert_rmcp_tools_clean, audit_rmcp};
158 pub use crate::{
159 all_rules, apply_patches, assert_catalog_clean, audit_json, compare_rankers,
160 compose_catalogs, diff_reports, explain_query, json_schema_for, parse_mcp_client_config,
161 scan_path, scan_source_str, suggest_patches, ApplyReport, AuditConfig, AuditDiff,
162 AuditReport, Auditor, Bm25Index, Bm25Ranker, Catalog, ComposeReport, Dimension, EvalCase,
163 EvalReport, EvalSuite, Finding, HybridRanker, PatchConfidence, PatchSet, QueryExplanation,
164 RankedTool, Ranker, RankerComparison, RepairPlan, SchemaTarget, Severity, SourceLanguage,
165 SourceLocation, SourceScanReport, TfIdfRanker, Tier, ToolHints, ToolSpec,
166 };
167}
168
169/// One-line helper to parse and audit any MCP `tools/list` JSON string with default settings.
170pub fn audit_json(json: &str) -> Result<AuditReport> {
171 let catalog = Catalog::from_mcp_json(json)?;
172 Ok(Auditor::new(AuditConfig::default()).audit(&catalog))
173}
174
175/// One-line `cargo test` assertion that panics with a prioritized agent-readable [`RepairPlan`]
176/// if any finding meets or exceeds `Severity::Error`.
177///
178/// # Panics
179///
180/// Panics if [`AuditReport::passed`] is `false`.
181pub fn assert_catalog_clean(catalog: &Catalog) {
182 let report = Auditor::new(AuditConfig::default()).audit(catalog);
183 assert!(
184 report.passed(),
185 "mcp-vol audit failed:\n{}",
186 report.to_repair_plan().to_markdown()
187 );
188}