mcp-vol 0.1.0

Zero-LLM, deterministic MCP tool linter (24 rules), static Rust/TS/Python scanner, multi-server composer, RFC 6902 patcher, and pre-indexed BM25 eval harness for rmcp and AI agents.
Documentation
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
use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};

use crate::auditor::{AuditConfig, Auditor};
use crate::error::Result;
use crate::model::{AuditReport, Catalog, ToolHints, SCHEMA_VERSION};
use crate::text::{infer_polarity, leading_name_verb, tokenize_raw, ActionPolarity};

/// Confidence tier of an automatically generated RFC 6902 patch suggestion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PatchConfidence {
    /// Heuristic fix that an AI agent or maintainer should verify against actual handler behavior.
    Medium,
    /// Mechanically certain fix (e.g., removing an empty outputSchema stub or resolving a direct contradiction).
    High,
}

/// Single RFC 6902 JSON Patch operation (`add`, `replace`, `remove`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsonPatchOp {
    /// RFC 6902 operation name (`"add"`, `"replace"`, or `"remove"`).
    pub op: String,
    /// RFC 6901 JSON Pointer path relative to the catalog root (`/tools/<tool>/...`).
    pub path: String,
    /// Value to add or replace (omitted for `"remove"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<Value>,
}

/// Actionable machine-applicable patch linked back to a specific `VOL###` finding.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SuggestedPatch {
    /// Rule code that triggered this patch (e.g., `"VOL006"`, `"VOL007"`, `"VOL016"`, `"VOL018"`).
    pub code: String,
    /// Target tool name.
    pub tool: String,
    /// Mechanical confidence level (`"high"` or `"medium"`).
    pub confidence: PatchConfidence,
    /// Short rationale explaining why this deterministic edit resolves the finding.
    pub rationale: String,
    /// Ordered RFC 6902 JSON Patch operations to apply.
    pub operations: Vec<JsonPatchOp>,
}

/// Collection of deterministic RFC 6902 patch suggestions returned by [`suggest_patches`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PatchSet {
    /// Schema version.
    pub schema_version: String,
    /// Number of patches generated.
    pub patch_count: usize,
    /// Number of remaining findings that require prose authoring rather than mechanical patching.
    pub manual_prose_findings: usize,
    /// Suggested patches sorted highest confidence first, then code, then tool.
    pub patches: Vec<SuggestedPatch>,
}

impl PatchSet {
    /// Serializes this patch set as pretty-printed JSON.
    pub fn to_json_pretty(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(self)?)
    }

    /// Serializes this patch set as minified single-line JSON for token-constrained AI agents.
    pub fn to_json_compact(&self) -> Result<String> {
        Ok(serde_json::to_string(self)?)
    }
}

/// Generates deterministic RFC 6902 JSON Patch suggestions for mechanically fixable findings
/// (`VOL006`, `VOL007`, `VOL016`, `VOL017` tool names, `VOL018`) without calling an LLM.
#[must_use]
pub fn suggest_patches(catalog: &Catalog, report: &AuditReport) -> PatchSet {
    let mut patches = Vec::new();

    const DESTRUCTIVE_VERBS: &[&str] = &[
        "delete",
        "remove",
        "drop",
        "destroy",
        "purge",
        "truncate",
        "erase",
        "wipe",
        "overwrite",
        "reset",
        "revoke",
    ];
    const OPEN_WORLD_VERBS: &[&str] = &[
        "http", "fetch", "web", "slack", "github", "gitlab", "maps", "sentry", "brave", "send",
        "post", "publish", "deploy", "navigate",
    ];

    for finding in &report.findings {
        let Some(tool) = catalog.get(&finding.tool) else {
            continue;
        };
        let ptr_tool = escape_pointer(&tool.name);

        match finding.code.as_str() {
            "VOL006" => {
                let mut ops = Vec::new();
                if finding.json_pointer.ends_with("/readOnlyHint") {
                    ops.push(JsonPatchOp {
                        op: "replace".into(),
                        path: format!("/tools/{ptr_tool}/annotations/readOnlyHint"),
                        value: Some(json!(false)),
                    });
                    if leading_name_verb(&tool.name, DESTRUCTIVE_VERBS).is_some() {
                        ops.push(JsonPatchOp {
                            op: "replace".into(),
                            path: format!("/tools/{ptr_tool}/annotations/destructiveHint"),
                            value: Some(json!(true)),
                        });
                    }
                } else if finding.json_pointer.ends_with("/destructiveHint") {
                    let read_only = infer_polarity(&tool.name, None) == ActionPolarity::Read;
                    ops.push(JsonPatchOp {
                        op: "replace".into(),
                        path: format!("/tools/{ptr_tool}/annotations/destructiveHint"),
                        value: Some(json!(!read_only)),
                    });
                    if read_only {
                        ops.push(JsonPatchOp {
                            op: "replace".into(),
                            path: format!("/tools/{ptr_tool}/annotations/readOnlyHint"),
                            value: Some(json!(true)),
                        });
                    }
                }
                if !ops.is_empty() {
                    patches.push(SuggestedPatch {
                        code: "VOL006".into(),
                        tool: tool.name.clone(),
                        confidence: PatchConfidence::High,
                        rationale: "Align ToolAnnotations with the tool's declared action polarity to remove the behavioral contradiction.".into(),
                        operations: ops,
                    });
                }
            }
            "VOL007" => {
                let polarity = infer_polarity(&tool.name, None);
                let is_read = polarity == ActionPolarity::Read;
                let is_destructive =
                    !is_read && leading_name_verb(&tool.name, DESTRUCTIVE_VERBS).is_some();
                let is_open_world = tokenize_raw(&tool.name)
                    .iter()
                    .any(|t| OPEN_WORLD_VERBS.contains(&t.as_str()));

                patches.push(SuggestedPatch {
                    code: "VOL007".into(),
                    tool: tool.name.clone(),
                    confidence: PatchConfidence::Medium,
                    rationale: "Infer baseline MCP ToolAnnotations from tool name polarity (verify against actual handler implementation).".into(),
                    operations: vec![JsonPatchOp {
                        op: "add".into(),
                        path: format!("/tools/{ptr_tool}/annotations"),
                        value: Some(json!({
                            "readOnlyHint": is_read,
                            "destructiveHint": is_destructive,
                            "idempotentHint": is_read,
                            "openWorldHint": is_open_world
                        })),
                    }],
                });
            }
            "VOL016" => {
                patches.push(SuggestedPatch {
                    code: "VOL016".into(),
                    tool: tool.name.clone(),
                    confidence: PatchConfidence::High,
                    rationale: "Remove uninformative empty `{\"type\":\"object\"}` outputSchema stub until typed return properties are defined.".into(),
                    operations: vec![JsonPatchOp {
                        op: "remove".into(),
                        path: format!("/tools/{ptr_tool}/outputSchema"),
                        value: None,
                    }],
                });
            }
            "VOL017" if finding.tool != "<catalog>" => {
                let sanitized = tokenize_raw(&tool.name).join("_");
                if !sanitized.is_empty() && sanitized != tool.name {
                    patches.push(SuggestedPatch {
                        code: "VOL017".into(),
                        tool: tool.name.clone(),
                        confidence: PatchConfidence::Medium,
                        rationale: format!(
                            "Normalize tool identifier to SEP-986-compliant snake_case ('{sanitized}')."
                        ),
                        operations: vec![JsonPatchOp {
                            op: "replace".into(),
                            path: format!("/tools/{ptr_tool}/name"),
                            value: Some(json!(sanitized)),
                        }],
                    });
                }
            }
            "VOL018" => {
                patches.push(SuggestedPatch {
                    code: "VOL018".into(),
                    tool: tool.name.clone(),
                    confidence: PatchConfidence::Medium,
                    rationale: "Add an optional `limit` parameter with a sensible cap to prevent unbounded context-window output.".into(),
                    operations: vec![JsonPatchOp {
                        op: "add".into(),
                        path: format!("/tools/{ptr_tool}/inputSchema/properties/limit"),
                        value: Some(json!({
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 100,
                            "default": 50,
                            "description": "Maximum number of items to return per call (default 50, max 100)."
                        })),
                    }],
                });
            }
            "VOL020" => {
                if finding
                    .evidence
                    .get("root_not_object")
                    .and_then(Value::as_bool)
                    == Some(true)
                {
                    let op = if tool.input_schema.contains_key("type") {
                        "replace"
                    } else {
                        "add"
                    };
                    patches.push(SuggestedPatch {
                        code: "VOL020".into(),
                        tool: tool.name.clone(),
                        confidence: PatchConfidence::High,
                        rationale: "Set root `inputSchema.type` to `\"object\"` for strict MCP & LLM tool-calling compatibility.".into(),
                        operations: vec![JsonPatchOp {
                            op: op.into(),
                            path: format!("/tools/{ptr_tool}/inputSchema/type"),
                            value: Some(json!("object")),
                        }],
                    });
                }
            }
            "VOL021" => {
                // Filter top-level `required` to retain only properties actually declared in `properties`.
                if let Some(req_arr) = tool.input_schema.get("required").and_then(Value::as_array) {
                    let props = tool.schema_properties();
                    let cleaned: Vec<Value> = req_arr
                        .iter()
                        .filter(|v| {
                            v.as_str()
                                .is_some_and(|name| props.is_some_and(|m| m.contains_key(name)))
                        })
                        .cloned()
                        .collect();
                    if cleaned.len() < req_arr.len() {
                        patches.push(SuggestedPatch {
                            code: "VOL021".into(),
                            tool: tool.name.clone(),
                            confidence: PatchConfidence::High,
                            rationale: "Remove undeclared property names from root `inputSchema.required` so the schema is satisfiable.".into(),
                            operations: vec![JsonPatchOp {
                                op: "replace".into(),
                                path: format!("/tools/{ptr_tool}/inputSchema/required"),
                                value: Some(Value::Array(cleaned)),
                            }],
                        });
                    }
                }
            }
            _ => {}
        }
    }

    patches.sort_by(|a, b| {
        b.confidence
            .cmp(&a.confidence)
            .then_with(|| a.code.cmp(&b.code))
            .then_with(|| a.tool.cmp(&b.tool))
    });

    let patch_count = patches.len();
    let manual_prose_findings = report.findings.len().saturating_sub(patch_count);

    PatchSet {
        schema_version: SCHEMA_VERSION.into(),
        patch_count,
        manual_prose_findings,
        patches,
    }
}

/// Verified before/after summary produced by [`apply_patches`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApplyReport {
    /// Schema version.
    pub schema_version: String,
    /// Minimum patch confidence applied (`"high"` or `"medium"`).
    pub min_confidence: PatchConfidence,
    /// Number of patches successfully applied to the catalog.
    pub applied_patch_count: usize,
    /// Number of suggested patches skipped (below confidence threshold or unsafe rename collision).
    pub skipped_patch_count: usize,
    /// Catalog overall score before applying patches (1.0–5.0).
    pub score_before: f64,
    /// Catalog overall score after applying patches (1.0–5.0).
    pub score_after: f64,
    /// Error count before patching.
    pub errors_before: usize,
    /// Error count after patching.
    pub errors_after: usize,
    /// Warning count before patching.
    pub warnings_before: usize,
    /// Warning count after patching.
    pub warnings_after: usize,
    /// Deduplicated rule codes remediated in this pass.
    pub applied_codes: Vec<String>,
    /// Remaining findings after patching (typically prose/schema authoring items).
    pub remaining_findings: usize,
}

impl ApplyReport {
    /// Serializes this apply report as pretty-printed JSON.
    pub fn to_json_pretty(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(self)?)
    }

    /// Serializes this apply report as minified single-line JSON.
    pub fn to_json_compact(&self) -> Result<String> {
        Ok(serde_json::to_string(self)?)
    }
}

/// 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`].
#[must_use]
pub fn apply_patches(
    catalog: &Catalog,
    config: &AuditConfig,
    min_confidence: PatchConfidence,
) -> (Catalog, ApplyReport) {
    let auditor = Auditor::new(config.clone());
    let before = auditor.audit(catalog);
    let patch_set = suggest_patches(catalog, &before);

    let mut tools = catalog.tools().to_vec();
    let mut name_redirects: BTreeMap<String, String> = BTreeMap::new();
    let mut applied_patch_count = 0usize;
    let mut skipped_patch_count = 0usize;
    let mut applied_codes_set: BTreeSet<String> = BTreeSet::new();

    for patch in &patch_set.patches {
        if patch.confidence < min_confidence {
            skipped_patch_count += 1;
            continue;
        }
        let target_name = name_redirects
            .get(&patch.tool)
            .cloned()
            .unwrap_or_else(|| patch.tool.clone());
        let Some(tool_idx) = tools.iter().position(|t| t.name == target_name) else {
            skipped_patch_count += 1;
            continue;
        };

        let mut applied_any = false;
        for op in &patch.operations {
            if op.path.ends_with("/annotations/readOnlyHint") && op.op == "replace" {
                if let Some(val) = op.value.as_ref().and_then(Value::as_bool) {
                    let hints = tools[tool_idx]
                        .annotations
                        .get_or_insert_with(ToolHints::default);
                    hints.read_only_hint = Some(val);
                    applied_any = true;
                }
            } else if op.path.ends_with("/annotations/destructiveHint") && op.op == "replace" {
                if let Some(val) = op.value.as_ref().and_then(Value::as_bool) {
                    let hints = tools[tool_idx]
                        .annotations
                        .get_or_insert_with(ToolHints::default);
                    hints.destructive_hint = Some(val);
                    applied_any = true;
                }
            } else if op.path.ends_with("/annotations") && op.op == "add" {
                if let Some(val) = &op.value {
                    if let Ok(hints) = serde_json::from_value::<ToolHints>(val.clone()) {
                        tools[tool_idx].annotations = Some(hints);
                        applied_any = true;
                    }
                }
            } else if op.path.ends_with("/outputSchema") && op.op == "remove" {
                tools[tool_idx].output_schema = None;
                applied_any = true;
            } else if op.path.ends_with("/inputSchema/type")
                && (op.op == "add" || op.op == "replace")
            {
                if let Some(val) = &op.value {
                    tools[tool_idx]
                        .input_schema
                        .insert("type".to_string(), val.clone());
                    applied_any = true;
                }
            } else if op.path.ends_with("/inputSchema/required") && op.op == "replace" {
                if let Some(val) = &op.value {
                    tools[tool_idx]
                        .input_schema
                        .insert("required".to_string(), val.clone());
                    applied_any = true;
                }
            } else if op.path.ends_with("/name") && op.op == "replace" {
                if let Some(new_name) = op.value.as_ref().and_then(Value::as_str) {
                    let collision = tools
                        .iter()
                        .enumerate()
                        .any(|(i, t)| i != tool_idx && t.name == new_name);
                    if !collision {
                        let old_name = tools[tool_idx].name.clone();
                        tools[tool_idx].name = new_name.to_string();
                        name_redirects.insert(old_name, new_name.to_string());
                        applied_any = true;
                    }
                }
            } else if let Some((_, prop_raw)) = op.path.split_once("/inputSchema/properties/") {
                if op.op == "add" {
                    if let Some(val) = &op.value {
                        let prop_name = unescape_pointer(prop_raw);
                        let props_entry = tools[tool_idx]
                            .input_schema
                            .entry("properties".to_string())
                            .or_insert_with(|| Value::Object(Map::new()));
                        if let Some(props_map) = props_entry.as_object_mut() {
                            props_map.insert(prop_name, val.clone());
                            applied_any = true;
                        }
                    }
                }
            }
        }

        if applied_any {
            applied_patch_count += 1;
            applied_codes_set.insert(patch.code.clone());
        } else {
            skipped_patch_count += 1;
        }
    }

    let fixed_catalog = Catalog::new(tools);
    let after = auditor.audit(&fixed_catalog);

    let report = ApplyReport {
        schema_version: SCHEMA_VERSION.into(),
        min_confidence,
        applied_patch_count,
        skipped_patch_count,
        score_before: round2_f64(before.summary.overall_score),
        score_after: round2_f64(after.summary.overall_score),
        errors_before: before.summary.error_count,
        errors_after: after.summary.error_count,
        warnings_before: before.summary.warning_count,
        warnings_after: after.summary.warning_count,
        applied_codes: applied_codes_set.into_iter().collect(),
        remaining_findings: after.findings.len(),
    };

    (fixed_catalog, report)
}

fn round2_f64(v: f32) -> f64 {
    (f64::from(v) * 100.0).round() / 100.0
}

fn escape_pointer(segment: &str) -> String {
    segment.replace('~', "~0").replace('/', "~1")
}

fn unescape_pointer(segment: &str) -> String {
    segment.replace("~1", "/").replace("~0", "~")
}