Skip to main content

mcp_vol/
patch.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use serde::{Deserialize, Serialize};
4use serde_json::{json, Map, Value};
5
6use crate::auditor::{AuditConfig, Auditor};
7use crate::error::Result;
8use crate::model::{AuditReport, Catalog, ToolHints, SCHEMA_VERSION};
9use crate::text::{infer_polarity, leading_name_verb, tokenize_raw, ActionPolarity};
10
11/// Confidence tier of an automatically generated RFC 6902 patch suggestion.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum PatchConfidence {
15    /// Heuristic fix that an AI agent or maintainer should verify against actual handler behavior.
16    Medium,
17    /// Mechanically certain fix (e.g., removing an empty outputSchema stub or resolving a direct contradiction).
18    High,
19}
20
21/// Single RFC 6902 JSON Patch operation (`add`, `replace`, `remove`).
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub struct JsonPatchOp {
24    /// RFC 6902 operation name (`"add"`, `"replace"`, or `"remove"`).
25    pub op: String,
26    /// RFC 6901 JSON Pointer path relative to the catalog root (`/tools/<tool>/...`).
27    pub path: String,
28    /// Value to add or replace (omitted for `"remove"`).
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub value: Option<Value>,
31}
32
33/// Actionable machine-applicable patch linked back to a specific `VOL###` finding.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct SuggestedPatch {
36    /// Rule code that triggered this patch (e.g., `"VOL006"`, `"VOL007"`, `"VOL016"`, `"VOL018"`).
37    pub code: String,
38    /// Target tool name.
39    pub tool: String,
40    /// Mechanical confidence level (`"high"` or `"medium"`).
41    pub confidence: PatchConfidence,
42    /// Short rationale explaining why this deterministic edit resolves the finding.
43    pub rationale: String,
44    /// Ordered RFC 6902 JSON Patch operations to apply.
45    pub operations: Vec<JsonPatchOp>,
46}
47
48/// Collection of deterministic RFC 6902 patch suggestions returned by [`suggest_patches`].
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50pub struct PatchSet {
51    /// Schema version.
52    pub schema_version: String,
53    /// Number of patches generated.
54    pub patch_count: usize,
55    /// Number of remaining findings that require prose authoring rather than mechanical patching.
56    pub manual_prose_findings: usize,
57    /// Suggested patches sorted highest confidence first, then code, then tool.
58    pub patches: Vec<SuggestedPatch>,
59}
60
61impl PatchSet {
62    /// Serializes this patch set as pretty-printed JSON.
63    pub fn to_json_pretty(&self) -> Result<String> {
64        Ok(serde_json::to_string_pretty(self)?)
65    }
66
67    /// Serializes this patch set as minified single-line JSON for token-constrained AI agents.
68    pub fn to_json_compact(&self) -> Result<String> {
69        Ok(serde_json::to_string(self)?)
70    }
71}
72
73/// Generates deterministic RFC 6902 JSON Patch suggestions for mechanically fixable findings
74/// (`VOL006`, `VOL007`, `VOL016`, `VOL017` tool names, `VOL018`) without calling an LLM.
75#[must_use]
76pub fn suggest_patches(catalog: &Catalog, report: &AuditReport) -> PatchSet {
77    let mut patches = Vec::new();
78
79    const DESTRUCTIVE_VERBS: &[&str] = &[
80        "delete",
81        "remove",
82        "drop",
83        "destroy",
84        "purge",
85        "truncate",
86        "erase",
87        "wipe",
88        "overwrite",
89        "reset",
90        "revoke",
91    ];
92    const OPEN_WORLD_VERBS: &[&str] = &[
93        "http", "fetch", "web", "slack", "github", "gitlab", "maps", "sentry", "brave", "send",
94        "post", "publish", "deploy", "navigate",
95    ];
96
97    for finding in &report.findings {
98        let Some(tool) = catalog.get(&finding.tool) else {
99            continue;
100        };
101        let ptr_tool = escape_pointer(&tool.name);
102
103        match finding.code.as_str() {
104            "VOL006" => {
105                let mut ops = Vec::new();
106                if finding.json_pointer.ends_with("/readOnlyHint") {
107                    ops.push(JsonPatchOp {
108                        op: "replace".into(),
109                        path: format!("/tools/{ptr_tool}/annotations/readOnlyHint"),
110                        value: Some(json!(false)),
111                    });
112                    if leading_name_verb(&tool.name, DESTRUCTIVE_VERBS).is_some() {
113                        ops.push(JsonPatchOp {
114                            op: "replace".into(),
115                            path: format!("/tools/{ptr_tool}/annotations/destructiveHint"),
116                            value: Some(json!(true)),
117                        });
118                    }
119                } else if finding.json_pointer.ends_with("/destructiveHint") {
120                    let read_only = infer_polarity(&tool.name, None) == ActionPolarity::Read;
121                    ops.push(JsonPatchOp {
122                        op: "replace".into(),
123                        path: format!("/tools/{ptr_tool}/annotations/destructiveHint"),
124                        value: Some(json!(!read_only)),
125                    });
126                    if read_only {
127                        ops.push(JsonPatchOp {
128                            op: "replace".into(),
129                            path: format!("/tools/{ptr_tool}/annotations/readOnlyHint"),
130                            value: Some(json!(true)),
131                        });
132                    }
133                }
134                if !ops.is_empty() {
135                    patches.push(SuggestedPatch {
136                        code: "VOL006".into(),
137                        tool: tool.name.clone(),
138                        confidence: PatchConfidence::High,
139                        rationale: "Align ToolAnnotations with the tool's declared action polarity to remove the behavioral contradiction.".into(),
140                        operations: ops,
141                    });
142                }
143            }
144            "VOL007" => {
145                let polarity = infer_polarity(&tool.name, None);
146                let is_read = polarity == ActionPolarity::Read;
147                let is_destructive =
148                    !is_read && leading_name_verb(&tool.name, DESTRUCTIVE_VERBS).is_some();
149                let is_open_world = tokenize_raw(&tool.name)
150                    .iter()
151                    .any(|t| OPEN_WORLD_VERBS.contains(&t.as_str()));
152
153                patches.push(SuggestedPatch {
154                    code: "VOL007".into(),
155                    tool: tool.name.clone(),
156                    confidence: PatchConfidence::Medium,
157                    rationale: "Infer baseline MCP ToolAnnotations from tool name polarity (verify against actual handler implementation).".into(),
158                    operations: vec![JsonPatchOp {
159                        op: "add".into(),
160                        path: format!("/tools/{ptr_tool}/annotations"),
161                        value: Some(json!({
162                            "readOnlyHint": is_read,
163                            "destructiveHint": is_destructive,
164                            "idempotentHint": is_read,
165                            "openWorldHint": is_open_world
166                        })),
167                    }],
168                });
169            }
170            "VOL016" => {
171                patches.push(SuggestedPatch {
172                    code: "VOL016".into(),
173                    tool: tool.name.clone(),
174                    confidence: PatchConfidence::High,
175                    rationale: "Remove uninformative empty `{\"type\":\"object\"}` outputSchema stub until typed return properties are defined.".into(),
176                    operations: vec![JsonPatchOp {
177                        op: "remove".into(),
178                        path: format!("/tools/{ptr_tool}/outputSchema"),
179                        value: None,
180                    }],
181                });
182            }
183            "VOL017" if finding.tool != "<catalog>" => {
184                let sanitized = tokenize_raw(&tool.name).join("_");
185                if !sanitized.is_empty() && sanitized != tool.name {
186                    patches.push(SuggestedPatch {
187                        code: "VOL017".into(),
188                        tool: tool.name.clone(),
189                        confidence: PatchConfidence::Medium,
190                        rationale: format!(
191                            "Normalize tool identifier to SEP-986-compliant snake_case ('{sanitized}')."
192                        ),
193                        operations: vec![JsonPatchOp {
194                            op: "replace".into(),
195                            path: format!("/tools/{ptr_tool}/name"),
196                            value: Some(json!(sanitized)),
197                        }],
198                    });
199                }
200            }
201            "VOL018" => {
202                patches.push(SuggestedPatch {
203                    code: "VOL018".into(),
204                    tool: tool.name.clone(),
205                    confidence: PatchConfidence::Medium,
206                    rationale: "Add an optional `limit` parameter with a sensible cap to prevent unbounded context-window output.".into(),
207                    operations: vec![JsonPatchOp {
208                        op: "add".into(),
209                        path: format!("/tools/{ptr_tool}/inputSchema/properties/limit"),
210                        value: Some(json!({
211                            "type": "integer",
212                            "minimum": 1,
213                            "maximum": 100,
214                            "default": 50,
215                            "description": "Maximum number of items to return per call (default 50, max 100)."
216                        })),
217                    }],
218                });
219            }
220            "VOL020" => {
221                if finding
222                    .evidence
223                    .get("root_not_object")
224                    .and_then(Value::as_bool)
225                    == Some(true)
226                {
227                    let op = if tool.input_schema.contains_key("type") {
228                        "replace"
229                    } else {
230                        "add"
231                    };
232                    patches.push(SuggestedPatch {
233                        code: "VOL020".into(),
234                        tool: tool.name.clone(),
235                        confidence: PatchConfidence::High,
236                        rationale: "Set root `inputSchema.type` to `\"object\"` for strict MCP & LLM tool-calling compatibility.".into(),
237                        operations: vec![JsonPatchOp {
238                            op: op.into(),
239                            path: format!("/tools/{ptr_tool}/inputSchema/type"),
240                            value: Some(json!("object")),
241                        }],
242                    });
243                }
244            }
245            "VOL021" => {
246                // Filter top-level `required` to retain only properties actually declared in `properties`.
247                if let Some(req_arr) = tool.input_schema.get("required").and_then(Value::as_array) {
248                    let props = tool.schema_properties();
249                    let cleaned: Vec<Value> = req_arr
250                        .iter()
251                        .filter(|v| {
252                            v.as_str()
253                                .is_some_and(|name| props.is_some_and(|m| m.contains_key(name)))
254                        })
255                        .cloned()
256                        .collect();
257                    if cleaned.len() < req_arr.len() {
258                        patches.push(SuggestedPatch {
259                            code: "VOL021".into(),
260                            tool: tool.name.clone(),
261                            confidence: PatchConfidence::High,
262                            rationale: "Remove undeclared property names from root `inputSchema.required` so the schema is satisfiable.".into(),
263                            operations: vec![JsonPatchOp {
264                                op: "replace".into(),
265                                path: format!("/tools/{ptr_tool}/inputSchema/required"),
266                                value: Some(Value::Array(cleaned)),
267                            }],
268                        });
269                    }
270                }
271            }
272            _ => {}
273        }
274    }
275
276    patches.sort_by(|a, b| {
277        b.confidence
278            .cmp(&a.confidence)
279            .then_with(|| a.code.cmp(&b.code))
280            .then_with(|| a.tool.cmp(&b.tool))
281    });
282
283    let patch_count = patches.len();
284    let manual_prose_findings = report.findings.len().saturating_sub(patch_count);
285
286    PatchSet {
287        schema_version: SCHEMA_VERSION.into(),
288        patch_count,
289        manual_prose_findings,
290        patches,
291    }
292}
293
294/// Verified before/after summary produced by [`apply_patches`].
295#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
296pub struct ApplyReport {
297    /// Schema version.
298    pub schema_version: String,
299    /// Minimum patch confidence applied (`"high"` or `"medium"`).
300    pub min_confidence: PatchConfidence,
301    /// Number of patches successfully applied to the catalog.
302    pub applied_patch_count: usize,
303    /// Number of suggested patches skipped (below confidence threshold or unsafe rename collision).
304    pub skipped_patch_count: usize,
305    /// Catalog overall score before applying patches (1.0–5.0).
306    pub score_before: f64,
307    /// Catalog overall score after applying patches (1.0–5.0).
308    pub score_after: f64,
309    /// Error count before patching.
310    pub errors_before: usize,
311    /// Error count after patching.
312    pub errors_after: usize,
313    /// Warning count before patching.
314    pub warnings_before: usize,
315    /// Warning count after patching.
316    pub warnings_after: usize,
317    /// Deduplicated rule codes remediated in this pass.
318    pub applied_codes: Vec<String>,
319    /// Remaining findings after patching (typically prose/schema authoring items).
320    pub remaining_findings: usize,
321}
322
323impl ApplyReport {
324    /// Serializes this apply report as pretty-printed JSON.
325    pub fn to_json_pretty(&self) -> Result<String> {
326        Ok(serde_json::to_string_pretty(self)?)
327    }
328
329    /// Serializes this apply report as minified single-line JSON.
330    pub fn to_json_compact(&self) -> Result<String> {
331        Ok(serde_json::to_string(self)?)
332    }
333}
334
335/// Deterministically applies all mechanical patches at or above `min_confidence` to a cloned
336/// [`Catalog`], re-audits the result, and returns both the repaired catalog and a verified
337/// before/after [`ApplyReport`].
338#[must_use]
339pub fn apply_patches(
340    catalog: &Catalog,
341    config: &AuditConfig,
342    min_confidence: PatchConfidence,
343) -> (Catalog, ApplyReport) {
344    let auditor = Auditor::new(config.clone());
345    let before = auditor.audit(catalog);
346    let patch_set = suggest_patches(catalog, &before);
347
348    let mut tools = catalog.tools().to_vec();
349    let mut name_redirects: BTreeMap<String, String> = BTreeMap::new();
350    let mut applied_patch_count = 0usize;
351    let mut skipped_patch_count = 0usize;
352    let mut applied_codes_set: BTreeSet<String> = BTreeSet::new();
353
354    for patch in &patch_set.patches {
355        if patch.confidence < min_confidence {
356            skipped_patch_count += 1;
357            continue;
358        }
359        let target_name = name_redirects
360            .get(&patch.tool)
361            .cloned()
362            .unwrap_or_else(|| patch.tool.clone());
363        let Some(tool_idx) = tools.iter().position(|t| t.name == target_name) else {
364            skipped_patch_count += 1;
365            continue;
366        };
367
368        let mut applied_any = false;
369        for op in &patch.operations {
370            if op.path.ends_with("/annotations/readOnlyHint") && op.op == "replace" {
371                if let Some(val) = op.value.as_ref().and_then(Value::as_bool) {
372                    let hints = tools[tool_idx]
373                        .annotations
374                        .get_or_insert_with(ToolHints::default);
375                    hints.read_only_hint = Some(val);
376                    applied_any = true;
377                }
378            } else if op.path.ends_with("/annotations/destructiveHint") && op.op == "replace" {
379                if let Some(val) = op.value.as_ref().and_then(Value::as_bool) {
380                    let hints = tools[tool_idx]
381                        .annotations
382                        .get_or_insert_with(ToolHints::default);
383                    hints.destructive_hint = Some(val);
384                    applied_any = true;
385                }
386            } else if op.path.ends_with("/annotations") && op.op == "add" {
387                if let Some(val) = &op.value {
388                    if let Ok(hints) = serde_json::from_value::<ToolHints>(val.clone()) {
389                        tools[tool_idx].annotations = Some(hints);
390                        applied_any = true;
391                    }
392                }
393            } else if op.path.ends_with("/outputSchema") && op.op == "remove" {
394                tools[tool_idx].output_schema = None;
395                applied_any = true;
396            } else if op.path.ends_with("/inputSchema/type")
397                && (op.op == "add" || op.op == "replace")
398            {
399                if let Some(val) = &op.value {
400                    tools[tool_idx]
401                        .input_schema
402                        .insert("type".to_string(), val.clone());
403                    applied_any = true;
404                }
405            } else if op.path.ends_with("/inputSchema/required") && op.op == "replace" {
406                if let Some(val) = &op.value {
407                    tools[tool_idx]
408                        .input_schema
409                        .insert("required".to_string(), val.clone());
410                    applied_any = true;
411                }
412            } else if op.path.ends_with("/name") && op.op == "replace" {
413                if let Some(new_name) = op.value.as_ref().and_then(Value::as_str) {
414                    let collision = tools
415                        .iter()
416                        .enumerate()
417                        .any(|(i, t)| i != tool_idx && t.name == new_name);
418                    if !collision {
419                        let old_name = tools[tool_idx].name.clone();
420                        tools[tool_idx].name = new_name.to_string();
421                        name_redirects.insert(old_name, new_name.to_string());
422                        applied_any = true;
423                    }
424                }
425            } else if let Some((_, prop_raw)) = op.path.split_once("/inputSchema/properties/") {
426                if op.op == "add" {
427                    if let Some(val) = &op.value {
428                        let prop_name = unescape_pointer(prop_raw);
429                        let props_entry = tools[tool_idx]
430                            .input_schema
431                            .entry("properties".to_string())
432                            .or_insert_with(|| Value::Object(Map::new()));
433                        if let Some(props_map) = props_entry.as_object_mut() {
434                            props_map.insert(prop_name, val.clone());
435                            applied_any = true;
436                        }
437                    }
438                }
439            }
440        }
441
442        if applied_any {
443            applied_patch_count += 1;
444            applied_codes_set.insert(patch.code.clone());
445        } else {
446            skipped_patch_count += 1;
447        }
448    }
449
450    let fixed_catalog = Catalog::new(tools);
451    let after = auditor.audit(&fixed_catalog);
452
453    let report = ApplyReport {
454        schema_version: SCHEMA_VERSION.into(),
455        min_confidence,
456        applied_patch_count,
457        skipped_patch_count,
458        score_before: round2_f64(before.summary.overall_score),
459        score_after: round2_f64(after.summary.overall_score),
460        errors_before: before.summary.error_count,
461        errors_after: after.summary.error_count,
462        warnings_before: before.summary.warning_count,
463        warnings_after: after.summary.warning_count,
464        applied_codes: applied_codes_set.into_iter().collect(),
465        remaining_findings: after.findings.len(),
466    };
467
468    (fixed_catalog, report)
469}
470
471fn round2_f64(v: f32) -> f64 {
472    (f64::from(v) * 100.0).round() / 100.0
473}
474
475fn escape_pointer(segment: &str) -> String {
476    segment.replace('~', "~0").replace('/', "~1")
477}
478
479fn unescape_pointer(segment: &str) -> String {
480    segment.replace("~1", "/").replace("~0", "~")
481}