Skip to main content

Crate mcp_vol

Crate mcp_vol 

Source
Expand description

§mcp-vol — Deterministic MCP Tool Volatility & Selection Auditor

Zero-LLM, sub-millisecond MCP tool linter, deep JSON Schema walker, sibling collision analyzer, RFC 6902 patch suggester, and BM25 / TF-IDF / Hybrid RRF evaluation harness designed specifically for AI coding agents and Rust (rmcp) CI gates.

§AI Agent Quick Reference (Single-Read Cheat Sheet)

[dev-dependencies]
mcp-vol = { version = "0.1", features = ["rmcp"] }

§2. One-Line Prelude & Facades (Minimal Boilerplate)

use mcp_vol::prelude::*;

let json = r#"{
  "tools": [
    {
      "name": "list_issues",
      "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.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "repo": { "type": "string", "description": "Repository in owner/name format." },
          "state": { "type": "string", "enum": ["open", "closed", "all"], "description": "Issue state filter." },
          "limit": { "type": "integer", "description": "Maximum issues per page (default 50)." }
        },
        "required": ["repo"]
      },
      "annotations": {
        "readOnlyHint": true,
        "destructiveHint": false,
        "idempotentHint": true,
        "openWorldHint": true
      }
    }
  ]
}"#;

// One-line JSON audit + assertion
let report = audit_json(json).unwrap();
assert!(report.passed());

// Selection routing eval (Bm25Ranker, TfIdfRanker, or HybridRanker)
let catalog = Catalog::from_mcp_json(json).unwrap();
assert_catalog_clean(&catalog);
let suite = EvalSuite::new([EvalCase {
    id: "c1".into(),
    query: "show open issues in this repo".into(),
    expected_tool: "list_issues".into(),
    acceptable_tools: vec![],
}]);
assert_eq!(suite.run(&catalog, &Bm25Ranker::default(), 3).top1_accuracy, 1.0);
assert_eq!(suite.run(&catalog, &HybridRanker::default(), 3).top1_accuracy, 1.0);

§3. One-Line rmcp v3.12 Test Gate (features = ["rmcp"])

ⓘ
#[test]
fn mcp_tools_are_agent_ready() {
    let tools: Vec<rmcp::model::Tool> = my_server_tools();
    mcp_vol::assert_rmcp_tools_clean(&tools);
}

§4. Rule Codes (VOL001–VOL024)

  • Purpose Clarity: VOL001 missing description, VOL002 tautology, VOL003 vague verb
  • Usage Guidelines: VOL004 missing usage cue (catalog ≥ 5), VOL005 missing sibling boundary
  • Behavioral Transparency: VOL006 annotation contradiction, VOL007 missing annotations, VOL008 undisclosed side effect/limit, VOL018 unbounded list/search, VOL019 coercive routing / hidden directive, VOL024 missing return contract
  • Parameter Semantics (recursive $ref/nested): VOL009 undocumented param, VOL010 unconstrained closed-set string, VOL011 opaque name or missing date/regex format, VOL020 incompatible/broken inputSchema or $ref, VOL021 unsatisfiable schema constraint
  • Conciseness: VOL012 token budget exceeded (>250/tool or >15k/catalog), VOL013 schema-prose duplication, VOL023 excessive parameter count (>12) or nesting depth (>4)
  • Contextual Completeness: VOL014 tool collision (≥0.72 or dup), VOL015 TDQS shadowing risk, VOL016 empty outputSchema stub, VOL017 SEP-986 / mixed naming style, VOL022 duplicate or placeholder description

§5. Mechanical RFC 6902 Auto-Fix, Baseline Eval Bootstrapping & Self-Describing Schemas

use mcp_vol::prelude::*;

let broken = r#"[{"name":"delete_all","description":"Deletes records.","inputSchema":{"type":"object"},"annotations":{"readOnlyHint":true,"destructiveHint":false}}]"#;
let catalog = Catalog::from_mcp_json(broken).unwrap();
let report = Auditor::default().audit(&catalog);
let patches = suggest_patches(&catalog, &report);
assert!(patches.patch_count >= 1);

// Apply high-confidence patches deterministically and verify score lift
let (fixed_catalog, applied) = apply_patches(&catalog, &AuditConfig::default(), PatchConfidence::High);
assert_eq!(applied.errors_after, 0);
assert!(applied.score_after > applied.score_before);

// Synthesize a starter routing eval suite in <1 ms, index with Bm25Index & inspect JSON Schemas
let suite = EvalSuite::generate_baseline(&fixed_catalog);
let index = Bm25Index::build(&fixed_catalog);
assert_eq!(suite.run(&fixed_catalog, &index, 1).top1_accuracy, 1.0);
assert!(json_schema_for(SchemaTarget::AuditReport)["properties"]["findings"].is_object());

Modules§

prelude
Convenience one-line wildcard import for AI agents and test modules: use mcp_vol::prelude::*;.

Structs§

ApplyReport
Verified before/after summary produced by apply_patches.
AuditConfig
Configuration governing rule thresholds, token cost pricing, and pass/fail gates for Auditor.
AuditDiff
Regression and prompt-cache volatility diff between two AuditReport snapshots.
AuditReport
Complete deterministic audit report returned by crate::Auditor::audit.
AuditSummary
Top-level summary metrics of an AuditReport.
Auditor
Deterministic, zero-LLM auditor for MCP tool catalogs.
Bm25Index
Precomputed inverted Okapi BM25 index for sub-millisecond tool search at scale (1,000+ tools).
Bm25Ranker
Zero-dependency, field-weighted Okapi BM25 ranker tuned for MCP tool metadata.
Catalog
Collection of MCP tools audited or evaluated together as a single catalog.
CollisionPair
Pairwise similarity and shadowing entry between two tools in the same catalog.
ComposeReport
Complete multi-server composition and federation audit report returned by compose_catalogs.
ConfusionEntry
Pairwise confusion count showing which wrong tool was picked instead of the expected tool.
CrossServerCollision
Cross-server tool collision occurring when two distinct MCP servers expose identical or highly overlapping tools into the same agent context.
DeferralRecommendation
Recommendation to move a heavy server behind on-demand tool discovery (rmcp ToolSearchServer or defer_loading: true) when the composed catalog exceeds the context token budget.
EvalCase
A single query-to-tool expectation test case.
EvalFailure
Detailed failure entry for a single EvalCase whose Top-1 prediction missed.
EvalReport
Complete evaluation report returned by EvalSuite::run.
EvalSuite
Executable suite of query-to-tool selection assertions runnable in CI.
Finding
A single actionable diagnostic finding emitted by crate::Auditor.
HybridRanker
Zero-dependency Reciprocal Rank Fusion (RRF) ranker combining Bm25Ranker and TfIdfRanker.
JsonPatchOp
Single RFC 6902 JSON Patch operation (add, replace, remove).
McpServerLaunch
Launch specification extracted from a standard MCP client config (claude_desktop_config.json, .mcp.json, .cursor/mcp.json, or VS Code mcp.json).
PatchSet
Collection of deterministic RFC 6902 patch suggestions returned by suggest_patches.
QueryExplanation
Full explainable routing diagnostic returned by explain_query.
RankedTool
Single ranked candidate returned by a Ranker.
RankerComparison
Side-by-side multi-ranker A/B comparison returned by compare_rankers.
RankerScoreRow
Summary row for a single ranker inside RankerComparison.
RepairPlan
Compact, worst-tool-first repair roadmap designed for AI coding agents.
RuleMeta
Static documentation metadata for a built-in VOL001–VOL024 rule.
ServerTokenShare
Per-server token, cost, and quality attribution inside a composed multi-server agent stack.
SourceLocation
Source file coordinates populated by static source scanners (mcp-vol scan).
SourceScanReport
Output returned by scan_path summarizing static MCP tool extraction across a codebase.
SuggestedPatch
Actionable machine-applicable patch linked back to a specific VOL### finding.
TermContribution
Per-term BM25 score contribution returned by explain_query.
TfIdfRanker
Zero-dependency semantic TF-IDF cosine + character-trigram ranker.
ToolExplanation
Term-by-term ranking explanation for one candidate tool.
ToolHints
Behavioral hints matching MCP ToolAnnotations.
ToolRepairItem
Prioritized per-tool repair entry inside a RepairPlan.
ToolScore
Per-tool quality score breakdown.
ToolSpec
Canonical, SDK-agnostic representation of an MCP tool definition.

Enums§

Dimension
Six research-backed quality dimensions aligned with arXiv 2602.14878 and Glama TDQS.
Error
Errors returned by mcp-vol parsing, serialization, and evaluation APIs.
PatchConfidence
Confidence tier of an automatically generated RFC 6902 patch suggestion.
SchemaTarget
Machine-readable JSON Schema targets exposed by mcp-vol so AI coding agents never have to guess input or output payload shapes.
Severity
Severity level of an audit finding, ordered Info < Warn < Error.
SourceLanguage
Source language supported by scan_source_str and scan_path.
Tier
Letter grade tier derived from the 1.0–5.0 overall quality score.

Constants§

SCHEMA_VERSION
Current JSON report schema version emitted by mcp-vol.

Traits§

Ranker
Pluggable tool-selection ranker used by crate::EvalSuite.

Functions§

all_rules
Returns static metadata for all 24 built-in deterministic rules (VOL001–VOL024).
apply_patches
Deterministically applies all mechanical patches at or above min_confidence to a cloned Catalog, re-audits the result, and returns both the repaired catalog and a verified before/after ApplyReport.
assert_catalog_clean
One-line cargo test assertion that panics with a prioritized agent-readable RepairPlan if any finding meets or exceeds Severity::Error.
assert_rmcp_tools_clean
One-line cargo test CI assertion for rmcp::model::Tool slices.
audit_json
One-line helper to parse and audit any MCP tools/list JSON string with default settings.
audit_rmcp
One-line helper to audit a slice of rmcp::model::Tool values with default settings.
compare_rankers
Evaluates multiple named Ranker implementations side-by-side on the exact same EvalSuite and Catalog and identifies the top performer.
compose_catalogs
Composes multiple named MCP server catalogs into a unified agent stack, computing per-server token/USD attribution, cross-server duplicate/semantic collisions, namespace-prefixing impact, and on-demand deferral recommendations.
diff_reports
Compares a baseline AuditReport against a newer report to detect quality regressions and LLM prompt-cache-busting schema mutations.
explain_query
Explains exactly why Okapi BM25 ranked the top-k tools for query, attributing score contributions to individual query terms and tool metadata fields (name, title, description, parameters).
json_schema_for
Returns a Draft 2020-12 JSON Schema describing the requested mcp-vol contract.
parse_mcp_client_config
Parses standard client MCP configuration JSON ({"mcpServers": {...}} or {"servers": {...}}) into sorted McpServerLaunch descriptors.
scan_path
Recursively scans a source file or directory for static Rust (rmcp), TypeScript, and Python MCP tool definitions without compiling or spawning the server.
scan_source_str
Pure in-memory static extractor for a single Rust, TypeScript, or Python source string.
suggest_patches
Generates deterministic RFC 6902 JSON Patch suggestions for mechanically fixable findings (VOL006, VOL007, VOL016, VOL017 tool names, VOL018) without calling an LLM.

Type Aliases§

Result
Convenience result alias for mcp-vol.