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};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PatchConfidence {
Medium,
High,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsonPatchOp {
pub op: String,
pub path: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SuggestedPatch {
pub code: String,
pub tool: String,
pub confidence: PatchConfidence,
pub rationale: String,
pub operations: Vec<JsonPatchOp>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PatchSet {
pub schema_version: String,
pub patch_count: usize,
pub manual_prose_findings: usize,
pub patches: Vec<SuggestedPatch>,
}
impl PatchSet {
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
pub fn to_json_compact(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
}
#[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" => {
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,
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApplyReport {
pub schema_version: String,
pub min_confidence: PatchConfidence,
pub applied_patch_count: usize,
pub skipped_patch_count: usize,
pub score_before: f64,
pub score_after: f64,
pub errors_before: usize,
pub errors_after: usize,
pub warnings_before: usize,
pub warnings_after: usize,
pub applied_codes: Vec<String>,
pub remaining_findings: usize,
}
impl ApplyReport {
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
pub fn to_json_compact(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
}
#[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", "~")
}