use std::collections::{BTreeMap, BTreeSet};
use serde_json::{json, Value};
use crate::auditor::AuditConfig;
use crate::model::{Catalog, CollisionPair, Dimension, Finding, RuleMeta, Severity, ToolSpec};
use crate::schema::{
collect_schema_params, has_description, inspect_schema_integrity, is_empty_output_schema,
schema_is_string,
};
use crate::text::{
contains_non_negated_term, leading_name_verb, stem_token, tokenize_raw, tokenize_stemmed,
};
pub fn all_rules() -> Vec<RuleMeta> {
vec![
RuleMeta {
code: "VOL001".into(),
slug: "missing-description".into(),
dimension: Dimension::PurposeClarity,
default_severity: Severity::Error,
summary: "Tool omits `description` or leaves it blank.".into(),
remediation: "Add a concise 1-sentence purpose stating the exact action, resource, and return value.".into(),
},
RuleMeta {
code: "VOL002".into(),
slug: "tautological-description".into(),
dimension: Dimension::PurposeClarity,
default_severity: Severity::Error,
summary: "Description merely restates the tool name or title without adding routing signal.".into(),
remediation: "Replace name repetition with concrete behavior, data source, and returned fields.".into(),
},
RuleMeta {
code: "VOL003".into(),
slug: "vague-action-verb".into(),
dimension: Dimension::PurposeClarity,
default_severity: Severity::Warn,
summary: "Description relies on vague boilerplate verbs (`handles`, `manages`, `processes`, `helper for`).".into(),
remediation: "Lead with a concrete action verb (`list`, `query`, `create`, `delete`) and explicit resource.".into(),
},
RuleMeta {
code: "VOL004".into(),
slug: "missing-usage-cue".into(),
dimension: Dimension::UsageGuidelines,
default_severity: Severity::Warn,
summary: "In multi-tool catalogs (>= 5 tools), description lacks explicit when-to-use or exclusion guidance.".into(),
remediation: "Add one sentence stating when to invoke this tool and when to prefer an alternative.".into(),
},
RuleMeta {
code: "VOL005".into(),
slug: "missing-sibling-disambiguation".into(),
dimension: Dimension::UsageGuidelines,
default_severity: Severity::Warn,
summary: "Tool overlaps strongly with a sibling tool but does not name it to draw a boundary.".into(),
remediation: "Explicitly contrast this tool with the overlapping sibling by name in the description.".into(),
},
RuleMeta {
code: "VOL006".into(),
slug: "annotation-contradiction".into(),
dimension: Dimension::BehavioralTransparency,
default_severity: Severity::Error,
summary: "MCP `annotations` contradict the tool name or description (e.g., `readOnlyHint=true` on a `delete` tool).".into(),
remediation: "Align `readOnlyHint`/`destructiveHint` with actual tool side effects or fix misleading wording.".into(),
},
RuleMeta {
code: "VOL007".into(),
slug: "missing-behavior-annotations".into(),
dimension: Dimension::BehavioralTransparency,
default_severity: Severity::Warn,
summary: "Tool omits MCP behavioral `annotations` (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`).".into(),
remediation: "Declare `ToolAnnotations` so agents and clients know side effects and idempotency upfront.".into(),
},
RuleMeta {
code: "VOL008".into(),
slug: "undisclosed-side-effect-or-limit".into(),
dimension: Dimension::BehavioralTransparency,
default_severity: Severity::Warn,
summary: "Mutating or open-world tool does not disclose side effects, limits, auth, pagination, or caveats.".into(),
remediation: "State what mutates, whether changes are irreversible, and any rate/result/auth constraints.".into(),
},
RuleMeta {
code: "VOL009".into(),
slug: "undocumented-schema-parameter".into(),
dimension: Dimension::ParameterSemantics,
default_severity: Severity::Error,
summary: "One or more `inputSchema` parameters (including nested objects and `$ref` targets) omit a `description`.".into(),
remediation: "Add a clear semantic `description` to every parameter in `inputSchema`.".into(),
},
RuleMeta {
code: "VOL010".into(),
slug: "unconstrained-string-enum".into(),
dimension: Dimension::ParameterSemantics,
default_severity: Severity::Warn,
summary: "A string parameter implying a closed value set (`status`, `mode`, `format`, `sort`, etc.) omits `enum`/`pattern`.".into(),
remediation: "Constrain valid values with JSON Schema `enum` (or `pattern`) instead of free-text `string`.".into(),
},
RuleMeta {
code: "VOL011".into(),
slug: "opaque-parameter-or-format".into(),
dimension: Dimension::ParameterSemantics,
default_severity: Severity::Warn,
summary: "Parameter uses an opaque name (`data`, `input`, `arg`) or expects a date/regex/path without specifying format.".into(),
remediation: "Use a semantic parameter name and declare expected format (e.g., `ISO-8601 YYYY-MM-DD`).".into(),
},
RuleMeta {
code: "VOL012".into(),
slug: "token-budget-exceeded".into(),
dimension: Dimension::Conciseness,
default_severity: Severity::Warn,
summary: "Tool description or full catalog exceeds the configured token budget.".into(),
remediation: "Trim redundant prose to 150-250 tokens per tool and front-load the primary purpose.".into(),
},
RuleMeta {
code: "VOL013".into(),
slug: "schema-prose-duplication".into(),
dimension: Dimension::Conciseness,
default_severity: Severity::Info,
summary: "Tool description duplicates parameter names and types already documented in `inputSchema`.".into(),
remediation: "Remove parameter listings from prose and keep parameter documentation inside `inputSchema`.".into(),
},
RuleMeta {
code: "VOL014".into(),
slug: "tool-intent-collision".into(),
dimension: Dimension::ContextualCompleteness,
default_severity: Severity::Error,
summary: "Two tools have duplicate names or high semantic similarity likely to cause agent misrouting.".into(),
remediation: "Merge overlapping tools or rename and scope them so their domains are strictly disjoint.".into(),
},
RuleMeta {
code: "VOL015".into(),
slug: "shadowed-tool-asymmetry".into(),
dimension: Dimension::ContextualCompleteness,
default_severity: Severity::Warn,
summary: "A low-parameter sibling tool can shadow a heavier filtered sibling tool (TDQS shadowing ratio).".into(),
remediation: "Narrow the cheaper tool, merge both into one tool, or explicitly redirect filtered queries to the heavier sibling.".into(),
},
RuleMeta {
code: "VOL016".into(),
slug: "empty-or-untyped-output-schema".into(),
dimension: Dimension::ContextualCompleteness,
default_severity: Severity::Warn,
summary: "Declared `outputSchema` is an empty object stub (`{\"type\":\"object\"}`) with no documented properties.".into(),
remediation: "Populate `outputSchema.properties` with typed, described return fields or omit the empty stub.".into(),
},
RuleMeta {
code: "VOL017".into(),
slug: "inconsistent-naming-convention".into(),
dimension: Dimension::ContextualCompleteness,
default_severity: Severity::Warn,
summary: "Tool name violates MCP SEP-986 characters or catalog mixes conflicting styles (`snake_case`, `camelCase`, `kebab-case`).".into(),
remediation: "Use a single consistent SEP-986-compliant naming convention across all tools in the server.".into(),
},
RuleMeta {
code: "VOL018".into(),
slug: "unbounded-list-or-search".into(),
dimension: Dimension::BehavioralTransparency,
default_severity: Severity::Warn,
summary: "List/search/query tool declares no pagination or limit parameter and states no upper result bound.".into(),
remediation: "Add a `limit`/`page`/`cursor` parameter (with sensible default) or document the server-side result cap.".into(),
},
RuleMeta {
code: "VOL019".into(),
slug: "coercive-routing-or-hidden-directive".into(),
dimension: Dimension::BehavioralTransparency,
default_severity: Severity::Error,
summary: "Tool metadata contains invisible Unicode/BiDi chars, hidden prompt tags, or coercive routing-hijack directives.".into(),
remediation: "Remove hidden characters, prompt tags, and imperative override directives so agents select tools purely on neutral capability boundaries.".into(),
},
RuleMeta {
code: "VOL020".into(),
slug: "incompatible-or-broken-input-schema".into(),
dimension: Dimension::ParameterSemantics,
default_severity: Severity::Error,
summary: "Tool `inputSchema` has a non-object root, a root combinator (`oneOf`/`anyOf`/`allOf`), or an unresolvable/external `$ref`.".into(),
remediation: "Set root `inputSchema.type = \"object\"`, move combinators inside properties, and ensure every `$ref` resolves locally inside `#/$defs`.".into(),
},
RuleMeta {
code: "VOL021".into(),
slug: "unsatisfiable-schema-constraint".into(),
dimension: Dimension::ParameterSemantics,
default_severity: Severity::Error,
summary: "Tool `inputSchema` lists a `required` property missing from `properties`, an empty `enum`, or inverted `min`/`max` bounds.".into(),
remediation: "Declare every `required` property in `properties`, populate non-empty `enum` values, and ensure `minimum <= maximum`.".into(),
},
RuleMeta {
code: "VOL022".into(),
slug: "duplicate-or-placeholder-description".into(),
dimension: Dimension::ContextualCompleteness,
default_severity: Severity::Warn,
summary: "Tool description contains unresolved placeholders (`TODO`/`TBD`/`{{...}}`) or duplicates another tool's description verbatim.".into(),
remediation: "Replace placeholder tokens and author a distinct description tailored to each tool's unique job.".into(),
},
RuleMeta {
code: "VOL023".into(),
slug: "excessive-schema-complexity".into(),
dimension: Dimension::Conciseness,
default_severity: Severity::Warn,
summary: "Tool `inputSchema` declares more than 12 parameters or nests deeper than 4 levels, degrading argument-filling reliability.".into(),
remediation: "Split overloaded tools into focused operations or flatten deeply nested input payloads.".into(),
},
RuleMeta {
code: "VOL024".into(),
slug: "missing-return-contract".into(),
dimension: Dimension::BehavioralTransparency,
default_severity: Severity::Info,
summary: "Tool declares no typed `outputSchema` and omits any mention of what its output/response contains.".into(),
remediation: "Attach a typed `outputSchema` with `properties` or state briefly in `description` what the tool returns.".into(),
},
]
}
pub(crate) fn evaluate_rules(
catalog: &Catalog,
collisions: &[CollisionPair],
config: &AuditConfig,
) -> Vec<Finding> {
let disabled: BTreeSet<&str> = config.disabled_rules.iter().map(String::as_str).collect();
let mut findings = Vec::new();
for tool in catalog.tools() {
check_vol001(tool, &disabled, &mut findings);
check_vol002(tool, &disabled, &mut findings);
check_vol003(tool, &disabled, &mut findings);
check_vol004(tool, catalog.len(), &disabled, &mut findings);
check_vol006(tool, &disabled, &mut findings);
check_vol007(tool, &disabled, &mut findings);
check_vol008(tool, &disabled, &mut findings);
check_vol009(tool, &disabled, &mut findings);
check_vol010(tool, &disabled, &mut findings);
check_vol011(tool, &disabled, &mut findings);
check_vol012_tool(tool, config, &disabled, &mut findings);
check_vol013(tool, &disabled, &mut findings);
check_vol016(tool, &disabled, &mut findings);
check_vol017_tool(tool, &disabled, &mut findings);
check_vol018(tool, &disabled, &mut findings);
check_vol019(tool, &disabled, &mut findings);
check_vol020_vol021_vol023(tool, &disabled, &mut findings);
check_vol022_tool(tool, &disabled, &mut findings);
check_vol024(tool, &disabled, &mut findings);
}
check_vol017_catalog(catalog, &disabled, &mut findings);
check_vol022_catalog(catalog, &disabled, &mut findings);
if !disabled.contains("VOL012") {
let total_tokens = catalog.estimated_total_tokens();
if total_tokens > config.max_catalog_tokens {
findings.push(Finding {
code: "VOL012".into(),
slug: "token-budget-exceeded".into(),
severity: Severity::Warn,
dimension: Dimension::Conciseness,
tool: "<catalog>".into(),
related_tool: None,
json_pointer: "/tools".into(),
message: format!(
"Total serialized catalog payload (~{total_tokens} tokens) exceeds budget ({} tokens).",
config.max_catalog_tokens
),
evidence: json!({
"estimated_catalog_tokens": total_tokens,
"max_catalog_tokens": config.max_catalog_tokens,
"tool_count": catalog.len(),
}),
fix_hint: "Trim verbose descriptions, remove duplicate prose, or split tools behind on-demand tool search (e.g., rmcp ToolSearchServer).".into(),
source_location: None,
source_server: None,
});
}
}
let tool_map: BTreeMap<&str, &ToolSpec> = catalog
.tools()
.iter()
.map(|t| (t.name.as_str(), t))
.collect();
for pair in collisions {
let is_exact_dup = pair.tool_a == pair.tool_b;
if !disabled.contains("VOL014")
&& (is_exact_dup || pair.score >= config.collision_threshold)
{
let msg = if is_exact_dup {
format!("Duplicate tool name '{}' detected in catalog.", pair.tool_a)
} else {
format!(
"High tool selection collision risk (similarity={:.2} >= {:.2}) between '{}' and '{}'.",
pair.score, config.collision_threshold, pair.tool_a, pair.tool_b
)
};
findings.push(Finding {
code: "VOL014".into(),
slug: "tool-intent-collision".into(),
severity: Severity::Error,
dimension: Dimension::ContextualCompleteness,
tool: pair.tool_a.clone(),
related_tool: Some(pair.tool_b.clone()),
json_pointer: format!("/tools/{}/description", escape_pointer(&pair.tool_a)),
message: msg,
evidence: json!({
"similarity": pair.score,
"threshold": config.collision_threshold,
"name_similarity": pair.name_similarity,
"description_similarity": pair.description_similarity,
"param_overlap": pair.param_overlap,
"shared_terms": pair.shared_terms,
}),
fix_hint: format!(
"Merge '{}' and '{}' if they serve the same job, or give them distinct verb+resource names and explicit non-overlapping boundaries.",
pair.tool_a, pair.tool_b
),
source_location: None,
source_server: None,
});
}
if !disabled.contains("VOL005")
&& !is_exact_dup
&& pair.score >= config.sibling_disambiguation_threshold
{
if let (Some(ta), Some(tb)) = (
tool_map.get(pair.tool_a.as_str()),
tool_map.get(pair.tool_b.as_str()),
) {
let da = ta.description.as_deref().unwrap_or_default().to_lowercase();
let db = tb.description.as_deref().unwrap_or_default().to_lowercase();
let a_names_b = da.contains(&tb.name.to_lowercase());
let b_names_a = db.contains(&ta.name.to_lowercase());
if !a_names_b && !b_names_a {
findings.push(Finding {
code: "VOL005".into(),
slug: "missing-sibling-disambiguation".into(),
severity: Severity::Warn,
dimension: Dimension::UsageGuidelines,
tool: pair.tool_a.clone(),
related_tool: Some(pair.tool_b.clone()),
json_pointer: format!("/tools/{}/description", escape_pointer(&pair.tool_a)),
message: format!(
"Overlapping siblings '{}' and '{}' (similarity={:.2}) do not cross-reference each other to clarify boundaries.",
pair.tool_a, pair.tool_b, pair.score
),
evidence: json!({
"similarity": pair.score,
"shared_terms": pair.shared_terms,
}),
fix_hint: format!(
"Add a boundary sentence in '{}' naming '{}' (e.g., \"Use '{}' for ...; for ... use '{}'.\").",
pair.tool_a, pair.tool_b, pair.tool_a, pair.tool_b
),
source_location: None,
source_server: None,
});
}
}
}
if !disabled.contains("VOL015") && pair.shadowing_risk {
if let (Some(cheap), Some(expensive)) = (&pair.cheaper_tool, &pair.expensive_tool) {
let cheap_cost = tool_map
.get(cheap.as_str())
.map(|t| t.invocation_cost())
.unwrap_or(0);
let expensive_cost = tool_map
.get(expensive.as_str())
.map(|t| t.invocation_cost())
.unwrap_or(0);
findings.push(Finding {
code: "VOL015".into(),
slug: "shadowed-tool-asymmetry".into(),
severity: Severity::Warn,
dimension: Dimension::ContextualCompleteness,
tool: expensive.clone(),
related_tool: Some(cheap.clone()),
json_pointer: format!("/tools/{}/inputSchema", escape_pointer(expensive)),
message: format!(
"Heavier tool '{}' (cost={}) risks being shadowed by simpler overlapping sibling '{}' (cost={}, similarity={:.2}).",
expensive, expensive_cost, cheap, cheap_cost, pair.score
),
evidence: json!({
"cheaper_tool": cheap,
"cheaper_cost": cheap_cost,
"expensive_tool": expensive,
"expensive_cost": expensive_cost,
"similarity": pair.score,
}),
fix_hint: format!(
"Narrow '{}' or update its description to explicitly direct filtered/complex queries to '{}', or merge both into one tool with optional filters.",
cheap, expensive
),
source_location: None,
source_server: None,
});
}
}
}
findings.sort_by(|a, b| {
b.severity
.cmp(&a.severity)
.then_with(|| a.code.cmp(&b.code))
.then_with(|| a.tool.cmp(&b.tool))
.then_with(|| a.related_tool.cmp(&b.related_tool))
.then_with(|| a.json_pointer.cmp(&b.json_pointer))
});
findings
}
fn check_vol001(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL001") {
return;
}
let missing = tool
.description
.as_deref()
.is_none_or(|d| d.trim().is_empty());
if missing {
out.push(Finding {
code: "VOL001".into(),
slug: "missing-description".into(),
severity: Severity::Error,
dimension: Dimension::PurposeClarity,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!("Tool '{}' has no description.", tool.name),
evidence: json!({ "description_present": false }),
fix_hint: format!(
"Add a description to '{}' stating what resource it operates on, what it returns, and when an agent should invoke it.",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol002(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL002") {
return;
}
let Some(desc) = tool.description.as_deref().map(str::trim) else {
return;
};
if desc.is_empty() {
return;
}
let word_count = desc.split_whitespace().count();
if word_count > 8 {
return;
}
let mut id_tokens: BTreeSet<String> = tokenize_stemmed(&tool.name).into_iter().collect();
if let Some(title) = &tool.title {
id_tokens.extend(tokenize_stemmed(title));
}
let desc_tokens: Vec<String> = tokenize_stemmed(desc);
if desc_tokens.is_empty() {
return;
}
let overlap_count = desc_tokens
.iter()
.filter(|t| id_tokens.contains(*t))
.count();
let ratio = overlap_count as f32 / desc_tokens.len() as f32;
if ratio >= 0.75 {
out.push(Finding {
code: "VOL002".into(),
slug: "tautological-description".into(),
severity: Severity::Error,
dimension: Dimension::PurposeClarity,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!(
"Description for '{}' merely restates its name/title ({:.0}% token overlap, {} words).",
tool.name,
ratio * 100.0,
word_count
),
evidence: json!({
"description": desc,
"word_count": word_count,
"overlap_ratio": (ratio * 100.0).round() / 100.0,
}),
fix_hint: format!(
"Rewrite '{}' description to specify the concrete source, filtering scope, and return payload instead of repeating the tool name.",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol003(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL003") {
return;
}
let Some(desc) = tool.description.as_deref().map(str::trim) else {
return;
};
if desc.is_empty() {
return;
}
let lower = desc.to_lowercase();
let word_count = desc.split_whitespace().count();
const VAGUE_PREFIXES: &[&str] = &[
"handles ",
"handle ",
"manages ",
"manage ",
"processes ",
"process ",
"helper for ",
"utility for ",
"tool for ",
"tool to ",
"performs operation",
"performs an operation",
"does ",
"works with ",
"interacts with ",
"misc ",
"general ",
];
if word_count < 22 {
if let Some(&matched) = VAGUE_PREFIXES.iter().find(|p| lower.starts_with(*p)) {
out.push(Finding {
code: "VOL003".into(),
slug: "vague-action-verb".into(),
severity: Severity::Warn,
dimension: Dimension::PurposeClarity,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!(
"Description for '{}' opens with vague boilerplate '{}'.",
tool.name,
matched.trim()
),
evidence: json!({
"matched_prefix": matched.trim(),
"word_count": word_count,
}),
fix_hint: format!(
"Replace '{}' with a specific verb+object stating what '{}' reads, mutates, or returns.",
matched.trim(),
tool.name
),
source_location: None,
source_server: None,
});
}
}
}
fn check_vol004(
tool: &ToolSpec,
catalog_len: usize,
disabled: &BTreeSet<&str>,
out: &mut Vec<Finding>,
) {
if disabled.contains("VOL004") || catalog_len < 5 {
return;
}
let Some(desc) = tool.description.as_deref().map(str::trim) else {
return;
};
if desc.is_empty() {
return;
}
let lower = desc.to_lowercase();
const STRONG_CUES: &[&str] = &[
"use when",
"use this",
"use for",
"use to ",
"call when",
"call this",
"invoke when",
"prefer ",
"instead of",
"do not use",
"don't use",
"avoid using",
"when you need",
"when you want",
"ideal for",
"best for",
"only when",
"unlike ",
"not for ",
"if you need",
"when searching",
"when querying",
"when creating",
"when updating",
];
if !STRONG_CUES.iter().any(|cue| lower.contains(cue)) {
out.push(Finding {
code: "VOL004".into(),
slug: "missing-usage-cue".into(),
severity: Severity::Warn,
dimension: Dimension::UsageGuidelines,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' in a {}-tool catalog omits explicit when-to-use or when-not-to-use guidance.",
tool.name, catalog_len
),
evidence: json!({ "catalog_size": catalog_len }),
fix_hint: format!(
"Append a usage boundary to '{}', e.g., \"Use this when ...; do not use for ... (prefer <sibling_tool>).\"",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol006(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL006") {
return;
}
let Some(ann) = &tool.annotations else {
return;
};
let desc_raw = tool.description.as_deref().unwrap_or_default();
let self_prose_lower = strip_redirection_clauses(desc_raw);
let desc_lower = desc_raw.to_lowercase();
const MUTATING_VERBS: &[&str] = &[
"delete",
"remove",
"drop",
"destroy",
"purge",
"truncate",
"erase",
"wipe",
"create",
"write",
"update",
"modify",
"mutate",
"patch",
"insert",
"upsert",
"post",
"publish",
"send",
"reset",
"revoke",
"archive",
"overwrite",
];
const UNAMBIGUOUS_PROSE_MUTATING_VERBS: &[&str] = &[
"delete",
"remove",
"destroy",
"purge",
"truncate",
"erase",
"wipe",
"modify",
"mutate",
"insert",
"upsert",
"revoke",
"overwrite",
];
const CLAUSE_OPENING_MUTATING_VERBS: &[&str] = &[
"drop", "create", "write", "update", "patch", "post", "publish", "send", "reset", "archive",
];
const DESTRUCTIVE_VERBS: &[&str] = &[
"delete",
"remove",
"drop",
"destroy",
"purge",
"truncate",
"erase",
"wipe",
"overwrite",
"permanently",
];
const READ_PREFIXES: &[&str] = &[
"get", "list", "read", "fetch", "find", "search", "describe", "inspect", "view", "show",
];
if ann.read_only_hint == Some(true) {
let name_verb = leading_name_verb(&tool.name, MUTATING_VERBS);
let prose_verb = UNAMBIGUOUS_PROSE_MUTATING_VERBS
.iter()
.find(|v| contains_non_negated_term(&self_prose_lower, v))
.map(|v| (*v).to_string())
.or_else(|| {
clause_opening_mutating_verb(&self_prose_lower, CLAUSE_OPENING_MUTATING_VERBS)
});
if let Some(matched) = name_verb.or(prose_verb) {
out.push(Finding {
code: "VOL006".into(),
slug: "annotation-contradiction".into(),
severity: Severity::Error,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!(
"/tools/{}/annotations/readOnlyHint",
escape_pointer(&tool.name)
),
message: format!(
"Tool '{}' implies mutation ('{}'), but annotations.readOnlyHint is true.",
tool.name, matched
),
evidence: json!({
"matched_verb": matched,
"read_only_hint": true,
}),
fix_hint: format!(
"Set annotations.read_only_hint = Some(false) on '{}' (and destructive_hint appropriately), or fix the misleading verb if it is truly read-only.",
tool.name
),
source_location: None,
source_server: None,
});
return;
}
}
if ann.destructive_hint == Some(false) {
let name_verb = leading_name_verb(&tool.name, DESTRUCTIVE_VERBS);
let prose_verb = DESTRUCTIVE_VERBS
.iter()
.find(|v| contains_non_negated_term(&self_prose_lower, v))
.map(|v| (*v).to_string());
if let Some(matched) = name_verb.or(prose_verb) {
out.push(Finding {
code: "VOL006".into(),
slug: "annotation-contradiction".into(),
severity: Severity::Error,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!(
"/tools/{}/annotations/destructiveHint",
escape_pointer(&tool.name)
),
message: format!(
"Tool '{}' indicates destructive behavior ('{}'), but annotations.destructiveHint is false.",
tool.name, matched
),
evidence: json!({
"matched_verb": matched,
"destructive_hint": false,
}),
fix_hint: format!(
"Set annotations.destructive_hint = Some(true) on '{}' and explain what data is deleted or overwritten.",
tool.name
),
source_location: None,
source_server: None,
});
return;
}
}
if ann.destructive_hint == Some(true)
&& leading_name_verb(&tool.name, READ_PREFIXES).is_some()
&& (desc_lower.contains("read-only")
|| desc_lower.contains("read only")
|| desc_lower.contains("does not modify"))
{
out.push(Finding {
code: "VOL006".into(),
slug: "annotation-contradiction".into(),
severity: Severity::Error,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!(
"/tools/{}/annotations/destructiveHint",
escape_pointer(&tool.name)
),
message: format!(
"Tool '{}' describes itself as read-only, but annotations.destructiveHint is true.",
tool.name
),
evidence: json!({ "destructive_hint": true }),
fix_hint: format!(
"Set annotations.read_only_hint = Some(true) and annotations.destructive_hint = Some(false) on '{}'.",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol007(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL007") {
return;
}
let has_hints = tool
.annotations
.as_ref()
.is_some_and(|a| a.has_any_behavior_hint());
if !has_hints {
out.push(Finding {
code: "VOL007".into(),
slug: "missing-behavior-annotations".into(),
severity: Severity::Warn,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/annotations", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' declares no MCP behavioral annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint).",
tool.name
),
evidence: json!({ "annotations_present": false }),
fix_hint: format!(
"Attach ToolAnnotations to '{}' specifying readOnlyHint, destructiveHint, idempotentHint, and openWorldHint.",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol008(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL008") {
return;
}
let Some(desc) = tool.description.as_deref().map(str::trim) else {
return;
};
if desc.is_empty() {
return;
}
let ann = tool.annotations.as_ref();
const RISKY_PREFIXES: &[&str] = &[
"delete", "remove", "drop", "destroy", "create", "write", "update", "patch", "post",
"send", "publish", "execute", "run", "fetch", "http", "request", "deploy", "reset",
"reply", "add", "append", "move", "set", "click", "fill", "navigate", "evaluate",
];
let is_mutating_or_open = ann.and_then(|a| a.read_only_hint) == Some(false)
|| ann.and_then(|a| a.destructive_hint) == Some(true)
|| ann.and_then(|a| a.open_world_hint) == Some(true)
|| (ann.is_none() && leading_name_verb(&tool.name, RISKY_PREFIXES).is_some());
if !is_mutating_or_open {
return;
}
let lower = desc.to_lowercase();
const DISCLOSURE_SIGNALS: &[&str] = &[
"limit",
"max ",
"maximum",
"up to ",
"rate",
"auth",
"token",
"permission",
"scope",
"permanent",
"irreversible",
"cannot be undone",
"overwrite",
"side effect",
"timeout",
"paginat",
"cursor",
"only ",
"cannot ",
"does not ",
"requires ",
"caveat",
"warning",
"idempotent",
"dry-run",
"network",
"external",
"fails if",
"returns an error",
"at most",
"modifies ",
"deletes ",
"creates ",
"writes ",
];
if !DISCLOSURE_SIGNALS.iter().any(|s| lower.contains(s)) {
out.push(Finding {
code: "VOL008".into(),
slug: "undisclosed-side-effect-or-limit".into(),
severity: Severity::Warn,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!(
"Mutating or external tool '{}' does not disclose side effects, auth requirements, or operational limits.",
tool.name
),
evidence: json!({
"read_only_hint": ann.and_then(|a| a.read_only_hint),
"destructive_hint": ann.and_then(|a| a.destructive_hint),
"open_world_hint": ann.and_then(|a| a.open_world_hint),
}),
fix_hint: format!(
"Document key constraints for '{}' (e.g., what state changes, reversibility, auth scopes, pagination/result limits, or failure cases).",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol009(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL009") {
return;
}
let params = collect_schema_params(&tool.input_schema);
if params.is_empty() {
return;
}
let mut missing: Vec<(String, String)> = params
.into_iter()
.filter(|p| !has_description(p.schema))
.map(|p| (p.path, p.pointer_suffix))
.collect();
missing.sort_by(|a, b| a.0.cmp(&b.0));
if !missing.is_empty() {
let paths: Vec<String> = missing.iter().map(|(p, _)| p.clone()).collect();
let first_ptr = &missing[0].1;
out.push(Finding {
code: "VOL009".into(),
slug: "undocumented-schema-parameter".into(),
severity: Severity::Error,
dimension: Dimension::ParameterSemantics,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/inputSchema{first_ptr}", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' has {} parameter(s) missing JSON Schema `description`: {}.",
tool.name,
paths.len(),
paths.join(", ")
),
evidence: json!({
"undocumented_parameters": paths,
"schema_description_coverage": (tool.schema_description_coverage() * 100.0).round() / 100.0,
}),
fix_hint: format!(
"Add a non-empty `description` in inputSchema for: {}.",
paths.join(", ")
),
source_location: None,
source_server: None,
});
}
}
fn check_vol010(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL010") {
return;
}
let params = collect_schema_params(&tool.input_schema);
if params.is_empty() {
return;
}
const CLOSED_SET_NAMES: &[&str] = &[
"status",
"state",
"type",
"kind",
"mode",
"format",
"sort",
"sort_by",
"sortby",
"order",
"direction",
"role",
"scope",
"level",
"severity",
"priority",
"visibility",
"category",
"provider",
"action",
"operation",
"output_format",
];
let mut unconstrained: Vec<(String, String)> = Vec::new();
for param in params {
if !schema_is_string(param.schema) {
continue;
}
let has_constraint = param.schema.get("enum").is_some()
|| param.schema.get("const").is_some()
|| param.schema.get("pattern").is_some()
|| param.schema.get("oneOf").is_some()
|| param.schema.get("anyOf").is_some();
if has_constraint {
continue;
}
let lower = param.name.to_lowercase();
let tokens = tokenize_raw(¶m.name);
let looks_closed = CLOSED_SET_NAMES.contains(&lower.as_str())
|| tokens
.last()
.is_some_and(|last| CLOSED_SET_NAMES.contains(&last.as_str()));
if looks_closed {
unconstrained.push((param.path, param.pointer_suffix));
}
}
unconstrained.sort_by(|a, b| a.0.cmp(&b.0));
if !unconstrained.is_empty() {
let paths: Vec<String> = unconstrained.iter().map(|(p, _)| p.clone()).collect();
let first_ptr = &unconstrained[0].1;
out.push(Finding {
code: "VOL010".into(),
slug: "unconstrained-string-enum".into(),
severity: Severity::Warn,
dimension: Dimension::ParameterSemantics,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/inputSchema{first_ptr}", escape_pointer(&tool.name)),
message: format!(
"Parameter(s) {} on '{}' look like a closed set but are unconstrained free-text strings.",
paths.join(", "),
tool.name
),
evidence: json!({ "parameters": paths }),
fix_hint: format!(
"Add a JSON Schema `enum` list (or regex `pattern`) to parameter(s): {}.",
paths.join(", ")
),
source_location: None,
source_server: None,
});
}
}
fn check_vol011(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL011") {
return;
}
let params = collect_schema_params(&tool.input_schema);
if params.is_empty() {
return;
}
const OPAQUE_NAMES: &[&str] = &[
"data", "input", "arg", "args", "val", "value", "param", "params", "obj", "object",
"payload", "item", "x", "y", "tmp", "misc", "info", "stuff",
];
const FORMAT_SENSITIVE_NAMES: &[&str] = &[
"date",
"start_date",
"end_date",
"from_date",
"to_date",
"since",
"until",
"timestamp",
"created_at",
"updated_at",
"regex",
"cron",
"duration",
"timezone",
];
const FORMAT_CUES: &[&str] = &[
"iso",
"yyyy",
"mm-dd",
"rfc",
"unix",
"epoch",
"utc",
"iana",
"pcre",
"re2",
"ecmascript",
"e.g.",
"example",
"seconds",
"millis",
"ms",
"hh:mm",
"format",
];
let mut opaque_hits: Vec<(String, String)> = Vec::new();
let mut format_hits: Vec<(String, String)> = Vec::new();
for param in params {
let lower = param.name.to_lowercase();
let desc = param
.schema
.get("description")
.and_then(Value::as_str)
.unwrap_or_default()
.trim();
if OPAQUE_NAMES.contains(&lower.as_str()) && desc.len() < 25 {
opaque_hits.push((param.path.clone(), param.pointer_suffix.clone()));
}
if schema_is_string(param.schema) && FORMAT_SENSITIVE_NAMES.contains(&lower.as_str()) {
let has_schema_fmt =
param.schema.get("format").is_some() || param.schema.get("pattern").is_some();
let desc_lower = desc.to_lowercase();
let has_prose_fmt = FORMAT_CUES.iter().any(|c| desc_lower.contains(c));
if !has_schema_fmt && !has_prose_fmt {
format_hits.push((param.path, param.pointer_suffix));
}
}
}
opaque_hits.sort_by(|a, b| a.0.cmp(&b.0));
format_hits.sort_by(|a, b| a.0.cmp(&b.0));
if !opaque_hits.is_empty() || !format_hits.is_empty() {
let first_ptr = opaque_hits
.first()
.or_else(|| format_hits.first())
.map(|(_, ptr)| ptr.as_str())
.unwrap_or("");
let opaque_paths: Vec<String> = opaque_hits.iter().map(|(p, _)| p.clone()).collect();
let format_paths: Vec<String> = format_hits.iter().map(|(p, _)| p.clone()).collect();
let mut reasons = Vec::new();
if !opaque_paths.is_empty() {
reasons.push(format!("opaque name(s): {}", opaque_paths.join(", ")));
}
if !format_paths.is_empty() {
reasons.push(format!(
"unspecified format on: {}",
format_paths.join(", ")
));
}
out.push(Finding {
code: "VOL011".into(),
slug: "opaque-parameter-or-format".into(),
severity: Severity::Warn,
dimension: Dimension::ParameterSemantics,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/inputSchema{first_ptr}", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' has ambiguous parameter specification ({}).",
tool.name,
reasons.join("; ")
),
evidence: json!({
"opaque_parameters": opaque_paths,
"format_unspecified_parameters": format_paths,
}),
fix_hint: "Rename generic parameters to domain-specific nouns and declare explicit formats (e.g., JSON Schema `format`/`pattern` or `ISO-8601 YYYY-MM-DD`).".into(),
source_location: None,
source_server: None,
});
}
}
fn check_vol012_tool(
tool: &ToolSpec,
config: &AuditConfig,
disabled: &BTreeSet<&str>,
out: &mut Vec<Finding>,
) {
if disabled.contains("VOL012") {
return;
}
let desc_tokens = tool.estimated_description_tokens();
if desc_tokens > config.max_tool_tokens {
out.push(Finding {
code: "VOL012".into(),
slug: "token-budget-exceeded".into(),
severity: Severity::Warn,
dimension: Dimension::Conciseness,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!(
"Description for '{}' (~{} tokens) exceeds per-tool budget ({} tokens).",
tool.name, desc_tokens, config.max_tool_tokens
),
evidence: json!({
"estimated_description_tokens": desc_tokens,
"max_tool_tokens": config.max_tool_tokens,
}),
fix_hint: format!(
"Condense '{}' description into the 150-{} token sweet spot; move parameter details into inputSchema.",
tool.name, config.max_tool_tokens
),
source_location: None,
source_server: None,
});
}
}
fn check_vol013(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL013") {
return;
}
let Some(desc) = tool.description.as_deref() else {
return;
};
let Some(props) = tool.schema_properties() else {
return;
};
if props.len() < 2 || tool.schema_description_coverage() < 0.8 {
return;
}
let lower = desc.to_lowercase();
let has_param_section = lower.contains("parameters:")
|| lower.contains("arguments:")
|| lower.contains("args:")
|| lower.contains("inputs:");
let mut repeated_with_type = Vec::new();
for (param, schema) in props {
let p_lower = param.to_lowercase();
let ty = schema
.get("type")
.and_then(Value::as_str)
.unwrap_or_default()
.to_lowercase();
let pat_bullet = format!("- {p_lower}:");
let pat_backtick = format!("`{p_lower}`:");
let pat_typed = if !ty.is_empty() {
format!("{p_lower} ({ty})")
} else {
String::new()
};
if lower.contains(&pat_bullet)
|| lower.contains(&pat_backtick)
|| (!pat_typed.is_empty() && lower.contains(&pat_typed))
|| (has_param_section && lower.contains(&p_lower))
{
repeated_with_type.push(param.clone());
}
}
repeated_with_type.sort();
if repeated_with_type.len() >= 2 {
out.push(Finding {
code: "VOL013".into(),
slug: "schema-prose-duplication".into(),
severity: Severity::Info,
dimension: Dimension::Conciseness,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!(
"Description for '{}' duplicates {} parameter definition(s) already documented in inputSchema: {}.",
tool.name,
repeated_with_type.len(),
repeated_with_type.join(", ")
),
evidence: json!({
"duplicated_parameters": repeated_with_type,
"schema_description_coverage": (tool.schema_description_coverage() * 100.0).round() / 100.0,
}),
fix_hint: format!(
"Remove duplicated parameter listings from '{}' description and rely on inputSchema.properties descriptions to save tokens.",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol016(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL016") {
return;
}
let Some(output_schema) = &tool.output_schema else {
return;
};
if is_empty_output_schema(output_schema) {
out.push(Finding {
code: "VOL016".into(),
slug: "empty-or-untyped-output-schema".into(),
severity: Severity::Warn,
dimension: Dimension::ContextualCompleteness,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/outputSchema", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' declares an empty `outputSchema` stub with no properties or type detail.",
tool.name
),
evidence: json!({ "output_schema": output_schema }),
fix_hint: format!(
"Define typed, described return fields inside '{}' outputSchema.properties (or remove the empty stub).",
tool.name
),
source_location: None,
source_server: None,
});
}
}
fn check_vol017_tool(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL017") {
return;
}
let valid_sep986 = !tool.name.is_empty()
&& tool.name.len() <= 128
&& tool
.name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
if !valid_sep986 {
out.push(Finding {
code: "VOL017".into(),
slug: "inconsistent-naming-convention".into(),
severity: Severity::Warn,
dimension: Dimension::ContextualCompleteness,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/name", escape_pointer(&tool.name)),
message: format!(
"Tool name '{}' violates MCP SEP-986 identifier rules (1-128 ASCII chars: [A-Za-z0-9._-]).",
tool.name
),
evidence: json!({ "name": tool.name, "length": tool.name.len() }),
fix_hint: "Rename the tool using lowercase snake_case ASCII characters matching [a-z0-9_-].".into(),
source_location: None,
source_server: None,
});
}
}
fn check_vol017_catalog(catalog: &Catalog, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL017") || catalog.len() < 4 {
return;
}
let mut style_buckets: BTreeMap<&'static str, Vec<String>> = BTreeMap::new();
for tool in catalog.tools() {
if let Some(style) = classify_name_style(&tool.name) {
style_buckets
.entry(style)
.or_default()
.push(tool.name.clone());
}
}
if style_buckets.len() >= 2 {
let styles: Vec<&str> = style_buckets.keys().copied().collect();
out.push(Finding {
code: "VOL017".into(),
slug: "inconsistent-naming-convention".into(),
severity: Severity::Warn,
dimension: Dimension::ContextualCompleteness,
tool: "<catalog>".into(),
related_tool: None,
json_pointer: "/tools".into(),
message: format!(
"Catalog mixes {} naming conventions across tools ({}).",
styles.len(),
styles.join(", ")
),
evidence: json!({ "styles": style_buckets }),
fix_hint: "Standardize all tool names in this server onto one convention (recommended: verb-first snake_case, e.g. `list_issues`).".into(),
source_location: None,
source_server: None,
});
}
}
fn classify_name_style(name: &str) -> Option<&'static str> {
let has_underscore = name.contains('_');
let has_hyphen = name.contains('-');
let has_upper = name.chars().any(|c| c.is_ascii_uppercase());
let has_lower = name.chars().any(|c| c.is_ascii_lowercase());
if has_underscore && !has_hyphen && !has_upper {
Some("snake_case")
} else if has_hyphen && !has_underscore && !has_upper {
Some("kebab-case")
} else if has_upper && has_lower && !has_underscore && !has_hyphen {
Some("camelCase")
} else if (has_underscore && has_hyphen) || ((has_underscore || has_hyphen) && has_upper) {
Some("mixed")
} else {
None
}
}
fn check_vol018(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL018") {
return;
}
const COLLECTION_VERBS: &[&str] = &["list", "search", "find", "query"];
let name_tokens = tokenize_raw(&tool.name);
let is_collection_tool = leading_name_verb(&tool.name, COLLECTION_VERBS).is_some()
|| name_tokens.iter().any(|t| t == "history" || t == "search");
if !is_collection_tool {
return;
}
const TINY_EXEMPT_NOUNS: &[&str] = &[
"allowed", "tables", "rules", "rule", "catalog", "crates", "tools", "scopes",
];
if name_tokens
.iter()
.any(|t| TINY_EXEMPT_NOUNS.contains(&t.as_str()))
{
return;
}
const BOUND_PARAM_SUBSTRS: &[&str] = &[
"limit", "max", "count", "page", "cursor", "offset", "head", "tail", "top", "depth",
"since", "until", "size", "per_page",
];
let params = collect_schema_params(&tool.input_schema);
let has_bound_param = params.iter().any(|p| {
let lower = p.name.to_lowercase();
BOUND_PARAM_SUBSTRS.iter().any(|k| lower.contains(k))
});
if has_bound_param {
return;
}
let desc_lower = tool
.description
.as_deref()
.unwrap_or_default()
.to_lowercase();
const BOUND_PROSE_CUES: &[&str] = &[
"limit",
"max ",
"maximum",
"at most",
"up to ",
"paginat",
"cursor",
"capped",
"truncated",
"bounded",
];
if BOUND_PROSE_CUES.iter().any(|c| desc_lower.contains(c)) {
return;
}
out.push(Finding {
code: "VOL018".into(),
slug: "unbounded-list-or-search".into(),
severity: Severity::Warn,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/inputSchema", escape_pointer(&tool.name)),
message: format!(
"Collection tool '{}' declares no pagination/limit parameter and states no result cap (risk of context-window overflow).",
tool.name
),
evidence: json!({
"parameter_count": params.len(),
"has_bound_param": false,
}),
fix_hint: format!(
"Add an optional `limit` or `cursor` parameter with a sensible default to '{}', or document the server-side result cap in its description.",
tool.name
),
source_location: None,
source_server: None,
});
}
fn check_vol019(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL019") {
return;
}
let mut texts_to_scan: Vec<(&str, String)> = Vec::new();
if let Some(desc) = &tool.description {
texts_to_scan.push(("description", desc.clone()));
}
if let Some(title) = &tool.title {
texts_to_scan.push(("title", title.clone()));
}
for param in collect_schema_params(&tool.input_schema) {
if let Some(d) = param.schema.get("description").and_then(Value::as_str) {
texts_to_scan.push(("inputSchema", d.to_string()));
}
}
const HIDDEN_TAG_PATTERNS: &[&str] = &[
"<!--",
"<important>",
"<system>",
"<instructions>",
"<instruction>",
"</system>",
"</important>",
];
const COERCIVE_PHRASES: &[&str] = &[
"ignore previous instructions",
"ignore all previous",
"disregard previous",
"override system",
"always call this tool",
"must call this tool first",
"do not call any other tool",
"never call any other tool",
"exfiltrate",
"secretly send",
];
let mut triggers: Vec<String> = Vec::new();
let mut trigger_field = "description";
for (field, text) in &texts_to_scan {
if text.chars().any(is_suspicious_invisible_char) {
triggers.push("invisible/BiDi control character".into());
trigger_field = field;
}
let lower = text.to_lowercase();
for pat in HIDDEN_TAG_PATTERNS {
if lower.contains(pat) {
triggers.push(format!("hidden tag `{pat}`"));
trigger_field = field;
}
}
for phrase in COERCIVE_PHRASES {
if lower.contains(phrase) {
triggers.push(format!("coercive directive \"{phrase}\""));
trigger_field = field;
}
}
}
triggers.sort();
triggers.dedup();
if triggers.is_empty() {
return;
}
out.push(Finding {
code: "VOL019".into(),
slug: "coercive-routing-or-hidden-directive".into(),
severity: Severity::Error,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/{}", escape_pointer(&tool.name), trigger_field),
message: format!(
"Tool '{}' contains suspicious routing-hijack or hidden directive signal(s): {}.",
tool.name,
triggers.join(", ")
),
evidence: json!({
"signals": triggers,
"field": trigger_field,
}),
fix_hint: format!(
"Remove invisible Unicode/BiDi characters, hidden XML/HTML tags, and imperative override phrases from '{}'. Describe capabilities neutrally.",
tool.name
),
source_location: None,
source_server: None,
});
}
fn is_suspicious_invisible_char(c: char) -> bool {
matches!(
c,
'\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' )
}
fn check_vol020_vol021_vol023(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
let integrity = inspect_schema_integrity(&tool.input_schema);
if !disabled.contains("VOL020")
&& (integrity.root_not_object
|| integrity.root_combinator.is_some()
|| !integrity.broken_refs.is_empty())
{
let mut reasons = Vec::new();
if integrity.root_not_object {
reasons.push("root `inputSchema` does not declare `\"type\": \"object\"`".to_string());
}
if let Some(comb) = integrity.root_combinator {
reasons.push(format!(
"root `inputSchema` uses top-level `{comb}` (rejected by strict LLM tool compilers)"
));
}
if !integrity.broken_refs.is_empty() {
reasons.push(format!(
"unresolvable or external `$ref`: {}",
integrity.broken_refs.join(", ")
));
}
out.push(Finding {
code: "VOL020".into(),
slug: "incompatible-or-broken-input-schema".into(),
severity: Severity::Error,
dimension: Dimension::ParameterSemantics,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/inputSchema", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' has an incompatible or broken `inputSchema`: {}.",
tool.name,
reasons.join("; ")
),
evidence: json!({
"root_not_object": integrity.root_not_object,
"root_combinator": integrity.root_combinator,
"broken_refs": integrity.broken_refs,
}),
fix_hint: format!(
"Ensure '{}' declares `\"type\": \"object\"` at `inputSchema` root, avoids top-level `oneOf`/`anyOf`/`allOf`, and resolves every `$ref` locally under `#/$defs`.",
tool.name
),
source_location: None,
source_server: None,
});
}
if !disabled.contains("VOL021")
&& (!integrity.dangling_required.is_empty() || !integrity.invalid_constraints.is_empty())
{
let mut details = Vec::new();
if !integrity.dangling_required.is_empty() {
let names: Vec<String> = integrity
.dangling_required
.iter()
.map(|(_, prop)| prop.clone())
.collect();
details.push(format!(
"`required` references undeclared property/properties: {}",
names.join(", ")
));
}
for (path, reason) in &integrity.invalid_constraints {
details.push(format!("`{path}` has {reason}"));
}
out.push(Finding {
code: "VOL021".into(),
slug: "unsatisfiable-schema-constraint".into(),
severity: Severity::Error,
dimension: Dimension::ParameterSemantics,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/inputSchema", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' declares unsatisfiable `inputSchema` constraint(s): {}.",
tool.name,
details.join("; ")
),
evidence: json!({
"dangling_required": integrity.dangling_required.iter().map(|(p, n)| json!({"pointer": p, "property": n})).collect::<Vec<_>>(),
"invalid_constraints": integrity.invalid_constraints.iter().map(|(p, r)| json!({"path": p, "reason": r})).collect::<Vec<_>>(),
}),
fix_hint: format!(
"Fix schema inconsistencies on '{}': declare every `required` field in `properties`, remove empty `enum` lists, and ensure `minimum <= maximum`.",
tool.name
),
source_location: None,
source_server: None,
});
}
if !disabled.contains("VOL023") {
let param_count = collect_schema_params(&tool.input_schema).len();
if param_count > 12 || integrity.max_nesting_depth > 4 {
out.push(Finding {
code: "VOL023".into(),
slug: "excessive-schema-complexity".into(),
severity: Severity::Warn,
dimension: Dimension::Conciseness,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/inputSchema", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' has excessive input schema complexity ({} parameters, nesting depth {}; recommended <=12 params and depth <=4).",
tool.name, param_count, integrity.max_nesting_depth
),
evidence: json!({
"parameter_count": param_count,
"max_nesting_depth": integrity.max_nesting_depth,
"max_recommended_params": 12,
"max_recommended_depth": 4,
}),
fix_hint: format!(
"Split '{}' into smaller focused tools or flatten deeply nested objects to improve LLM argument-filling accuracy.",
tool.name
),
source_location: None,
source_server: None,
});
}
}
}
fn check_vol022_tool(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL022") {
return;
}
let Some(desc) = tool.description.as_deref() else {
return;
};
let lower = desc.to_lowercase();
let words: Vec<&str> = lower
.split(|c: char| !c.is_alphanumeric() && c != '_')
.filter(|w| !w.is_empty())
.collect();
let mut matched = Vec::new();
for marker in ["todo", "tbd", "fixme", "xxx"] {
if words.contains(&marker) {
matched.push(marker.to_uppercase());
}
}
for sub in ["lorem ipsum", "{{", "<placeholder>", "[placeholder]"] {
if lower.contains(sub) {
matched.push(sub.to_string());
}
}
if matched.is_empty() {
return;
}
out.push(Finding {
code: "VOL022".into(),
slug: "duplicate-or-placeholder-description".into(),
severity: Severity::Warn,
dimension: Dimension::ContextualCompleteness,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/description", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' contains unfinished placeholder token(s) in its description: {}.",
tool.name,
matched.join(", ")
),
evidence: json!({ "placeholders": matched }),
fix_hint: format!(
"Replace placeholder markers in '{}' with a concrete description of the tool's action, target, and output.",
tool.name
),
source_location: None,
source_server: None,
});
}
fn check_vol022_catalog(catalog: &Catalog, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL022") || catalog.len() < 2 {
return;
}
let mut by_desc: BTreeMap<String, Vec<String>> = BTreeMap::new();
for tool in catalog.tools() {
let Some(desc) = tool.description.as_deref() else {
continue;
};
let norm: String = desc
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase();
if norm.len() >= 12 {
let entry = by_desc.entry(norm).or_default();
if !entry.contains(&tool.name) {
entry.push(tool.name.clone());
}
}
}
for (_norm, mut names) in by_desc {
if names.len() < 2 {
continue;
}
names.sort();
let primary = names[0].clone();
let others = &names[1..];
for dup in others {
out.push(Finding {
code: "VOL022".into(),
slug: "duplicate-or-placeholder-description".into(),
severity: Severity::Warn,
dimension: Dimension::ContextualCompleteness,
tool: dup.clone(),
related_tool: Some(primary.clone()),
json_pointer: format!("/tools/{}/description", escape_pointer(dup)),
message: format!(
"Tool '{}' duplicates the exact description prose of '{}' verbatim.",
dup, primary
),
evidence: json!({
"duplicate_of": primary,
"group": names,
}),
fix_hint: format!(
"Write a distinct description for '{}' explaining how its behavior differs from '{}'.",
dup, primary
),
source_location: None,
source_server: None,
});
}
}
}
fn check_vol024(tool: &ToolSpec, disabled: &BTreeSet<&str>, out: &mut Vec<Finding>) {
if disabled.contains("VOL024") {
return;
}
if let Some(os) = &tool.output_schema {
if !is_empty_output_schema(os) {
return;
}
}
let Some(desc) = tool.description.as_deref() else {
return;
};
if desc.trim().is_empty() {
return;
}
let lower = desc.to_lowercase();
const RETURN_CONTRACT_CUES: &[&str] = &[
"return",
"output",
"yield",
"respond",
"response",
"produce",
"emit",
"result",
"confirm",
"status",
"summary",
"report",
"list",
"array",
"object",
"json",
"text",
"markdown",
"content",
"detail",
"metadata",
"count",
"boolean",
"diff",
"history",
"log",
"graph",
"tree",
"table",
"row",
"match",
"snippet",
"screenshot",
"image",
"message",
"issue",
"pull request",
"branch",
"commit",
"file",
"director",
"path",
"url",
"id",
"time",
"elevation",
"place",
"direction",
"distance",
"thought",
"patch",
"plan",
"score",
"metric",
"rule",
"schema",
"info",
"data",
"value",
"record",
"entry",
"item",
"node",
"entit",
"relation",
"user",
"channel",
"search",
"query",
"key",
"repository",
"repo",
"comment",
"review",
"crate",
"health",
];
if RETURN_CONTRACT_CUES.iter().any(|cue| lower.contains(cue)) {
return;
}
out.push(Finding {
code: "VOL024".into(),
slug: "missing-return-contract".into(),
severity: Severity::Info,
dimension: Dimension::BehavioralTransparency,
tool: tool.name.clone(),
related_tool: None,
json_pointer: format!("/tools/{}/outputSchema", escape_pointer(&tool.name)),
message: format!(
"Tool '{}' declares no typed `outputSchema` and does not indicate what its response contains.",
tool.name
),
evidence: json!({
"has_typed_output_schema": false,
}),
fix_hint: format!(
"Attach a typed `outputSchema` to '{}' or append a short clause stating what it returns (e.g., \"Returns a JSON status object with...\").",
tool.name
),
source_location: None,
source_server: None,
});
}
fn strip_redirection_clauses(description: &str) -> String {
let mut kept = Vec::new();
for clause in description.split(['.', ';', '\n']) {
let lower = clause.trim().to_lowercase();
if lower.is_empty() {
continue;
}
let is_redirection = lower.contains("instead of")
|| lower.contains("instead")
|| lower.contains("do not use")
|| lower.contains("don't use")
|| lower.contains("not for ")
|| lower.contains("unlike ")
|| lower.contains("prefer ")
|| ((lower.starts_with("to ") || lower.starts_with("for "))
&& (lower.contains(" use ") || lower.contains(" call ")));
if !is_redirection {
kept.push(lower);
}
}
kept.join(" . ")
}
fn clause_opening_mutating_verb(self_prose_lower: &str, verbs: &[&str]) -> Option<String> {
const SUBJECT_OR_MODIFIER: &[&str] = &[
"this",
"tool",
"function",
"endpoint",
"action",
"it",
"will",
"can",
"may",
"also",
"directly",
"automatically",
"immediately",
"permanently",
"safely",
"silently",
"optionally",
"always",
"to",
];
for clause in self_prose_lower.split(['.', ';', '\n']) {
let words: Vec<&str> = clause
.split(|c: char| !c.is_alphanumeric() && c != '-' && c != '\'')
.filter(|w| !w.is_empty())
.collect();
let mut idx = 0;
while idx < words.len() && idx < 4 && SUBJECT_OR_MODIFIER.contains(&words[idx]) {
idx += 1;
}
if let Some(&main_word) = words.get(idx) {
if let Some(&verb) = verbs.iter().find(|&&v| {
main_word == v
|| (v.len() >= 4 && main_word.starts_with(v))
|| stem_token(main_word) == stem_token(v)
}) {
return Some(verb.to_string());
}
}
}
None
}
fn escape_pointer(segment: &str) -> String {
segment.replace('~', "~0").replace('/', "~1")
}