use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::auditor::{AuditConfig, Auditor};
use crate::error::{Error, Result};
use crate::model::{round2, AuditReport, Catalog, Tier, ToolSpec, SCHEMA_VERSION};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServerTokenShare {
pub server: String,
pub tool_count: usize,
pub estimated_tokens: usize,
pub token_share_pct: f32,
pub estimated_200_turn_usd: f32,
pub standalone_score: f32,
pub standalone_errors: usize,
pub standalone_warnings: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrossServerCollision {
pub server_a: String,
pub tool_a: String,
pub server_b: String,
pub tool_b: String,
pub exact_name_duplicate: bool,
pub similarity: f32,
pub fix_hint: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeferralRecommendation {
pub server: String,
pub tool_count: usize,
pub tokens_saved: usize,
pub session_usd_saved: f32,
pub rationale: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ComposeReport {
pub schema_version: String,
pub server_count: usize,
pub total_tools: usize,
pub total_estimated_tokens: usize,
pub total_200_turn_uncached_usd: f32,
pub total_200_turn_cached_usd: f32,
pub combined_score: f32,
pub combined_tier: Tier,
pub cross_server_exact_duplicates: usize,
pub cross_server_semantic_collisions: usize,
pub score_if_namespaced: f32,
pub exact_duplicates_if_namespaced: usize,
pub servers: Vec<ServerTokenShare>,
pub cross_server_collisions: Vec<CrossServerCollision>,
pub deferral_recommendations: Vec<DeferralRecommendation>,
pub combined_audit: AuditReport,
}
impl ComposeReport {
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)?)
}
pub fn to_text(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"mcp-vol compose: {} servers | {} tools | score {:.2}/5.00 (Tier {}) | ~{} tokens (~${:.2}/200t uncached, ~${:.2} cached)\n",
self.server_count,
self.total_tools,
self.combined_score,
self.combined_tier,
self.total_estimated_tokens,
self.total_200_turn_uncached_usd,
self.total_200_turn_cached_usd,
));
out.push_str(&format!(
"cross-server collisions: {} exact duplicate(s), {} semantic overlap(s) | if namespaced: score {:.2}/5.00 ({} exact duplicates)\n",
self.cross_server_exact_duplicates,
self.cross_server_semantic_collisions,
self.score_if_namespaced,
self.exact_duplicates_if_namespaced,
));
out.push_str("\nPer-server breakdown:\n");
for s in &self.servers {
out.push_str(&format!(
" {:20} {:3} tools | ~{:5} tok ({:5.1}%) | ~${:.2}/200t | score {:.2}\n",
s.server,
s.tool_count,
s.estimated_tokens,
s.token_share_pct,
s.estimated_200_turn_usd,
s.standalone_score,
));
}
if !self.cross_server_collisions.is_empty() {
out.push_str("\nCross-server collisions:\n");
for c in self.cross_server_collisions.iter().take(20) {
let kind = if c.exact_name_duplicate {
"EXACT DUP"
} else {
"OVERLAP"
};
out.push_str(&format!(
" [{}] {}::{} <-> {}::{} (sim={:.2})\n",
kind, c.server_a, c.tool_a, c.server_b, c.tool_b, c.similarity
));
}
}
if !self.deferral_recommendations.is_empty() {
out.push_str("\nOn-demand deferral recommendations:\n");
for rec in &self.deferral_recommendations {
out.push_str(&format!(
" [DEFER] {} ({} tools, saves ~{} tok / ~${:.2}/200t): {}\n",
rec.server,
rec.tool_count,
rec.tokens_saved,
rec.session_usd_saved,
rec.rationale
));
}
}
out
}
pub fn to_markdown(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"### `mcp-vol` Multi-Server Composition Audit — **{} Servers / {} Tools** (Score **{:.2}/5.00**, Tier **{}**)\n\n",
self.server_count, self.total_tools, self.combined_score, self.combined_tier
));
out.push_str(&format!(
"- **Context Payload:** ~{} tokens (~${:.2} / 200-turn uncached, ~${:.2} cached)\n",
self.total_estimated_tokens,
self.total_200_turn_uncached_usd,
self.total_200_turn_cached_usd
));
out.push_str(&format!(
"- **Cross-Server Collisions:** **{} exact duplicate(s)**, **{} semantic overlap(s)**\n",
self.cross_server_exact_duplicates, self.cross_server_semantic_collisions
));
out.push_str(&format!(
"- **Namespace Prefix Simulation (`<server>_`):** Score **{:.2} → {:.2}**, exact duplicates **{} → {}**\n\n",
self.combined_score,
self.score_if_namespaced,
self.cross_server_exact_duplicates,
self.exact_duplicates_if_namespaced
));
out.push_str("#### Per-Server Token & Quality Attribution\n\n");
out.push_str("| Server | Tools | Est. Tokens | Share | Est. $/200t | Standalone Score | Errors | Warnings |\n");
out.push_str("|---|---:|---:|---:|---:|---:|---:|---:|\n");
for s in &self.servers {
out.push_str(&format!(
"| `{}` | {} | ~{} | {:.1}% | ${:.2} | {:.2} | {} | {} |\n",
s.server,
s.tool_count,
s.estimated_tokens,
s.token_share_pct,
s.estimated_200_turn_usd,
s.standalone_score,
s.standalone_errors,
s.standalone_warnings
));
}
if !self.cross_server_collisions.is_empty() {
out.push_str("\n#### Cross-Server Collisions\n\n");
out.push_str("| Type | Server A | Server B | Similarity |\n|---|---|---|---:|\n");
for c in self.cross_server_collisions.iter().take(25) {
let kind = if c.exact_name_duplicate {
"**Exact Duplicate**"
} else {
"Semantic Overlap"
};
out.push_str(&format!(
"| {} | `{}`::`{}` | `{}`::`{}` | `{:.2}` |\n",
kind, c.server_a, c.tool_a, c.server_b, c.tool_b, c.similarity
));
}
}
if !self.deferral_recommendations.is_empty() {
out.push_str("\n#### On-Demand Tool Deferral Recommendations\n\n");
for rec in &self.deferral_recommendations {
out.push_str(&format!(
"- Defer `{}` ({} tools, saves ~{} tokens / ~${:.2} per 200-turn session): {}\n",
rec.server, rec.tool_count, rec.tokens_saved, rec.session_usd_saved, rec.rationale
));
}
}
out
}
}
#[must_use]
pub fn compose_catalogs(servers: &[(String, Catalog)], config: &AuditConfig) -> ComposeReport {
let auditor = Auditor::new(config.clone());
let mut merged_tools: Vec<ToolSpec> = Vec::new();
let mut namespaced_tools: Vec<ToolSpec> = Vec::new();
let mut tool_to_servers: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut raw_shares: Vec<(String, usize, usize, f32, usize, usize)> = Vec::new();
for (srv_name, cat) in servers {
let tagged = cat.with_source_server(srv_name);
let standalone = auditor.audit(&tagged);
let tokens = tagged.estimated_total_tokens();
raw_shares.push((
srv_name.clone(),
tagged.len(),
tokens,
standalone.summary.overall_score,
standalone.summary.error_count,
standalone.summary.warning_count,
));
for tool in tagged.tools() {
tool_to_servers
.entry(tool.name.clone())
.or_default()
.push(srv_name.clone());
merged_tools.push(tool.clone());
}
let prefix = sanitize_prefix(srv_name);
let prefixed = tagged.with_namespace_prefix(&prefix);
namespaced_tools.extend(prefixed.tools().iter().cloned());
}
let combined_catalog = Catalog::new(merged_tools);
let combined_audit = auditor.audit(&combined_catalog);
let namespaced_catalog = Catalog::new(namespaced_tools);
let namespaced_audit = auditor.audit(&namespaced_catalog);
let total_tokens = combined_audit.summary.estimated_catalog_tokens;
let total_tokens_f = total_tokens.max(1) as f32;
let mut server_shares: Vec<ServerTokenShare> = raw_shares
.into_iter()
.map(
|(
server,
tool_count,
estimated_tokens,
standalone_score,
standalone_errors,
standalone_warnings,
)| {
let share_pct = round2((estimated_tokens as f32 / total_tokens_f) * 100.0);
let session_usd = round2(
(estimated_tokens as f32 / 1_000_000.0)
* config.input_price_per_million_usd
* 200.0,
);
ServerTokenShare {
server,
tool_count,
estimated_tokens,
token_share_pct: share_pct,
estimated_200_turn_usd: session_usd,
standalone_score,
standalone_errors,
standalone_warnings,
}
},
)
.collect();
server_shares.sort_by(|a, b| {
b.estimated_tokens
.cmp(&a.estimated_tokens)
.then_with(|| a.server.cmp(&b.server))
});
let mut cross_server_collisions: Vec<CrossServerCollision> = Vec::new();
for (tool_name, owners) in &tool_to_servers {
if owners.len() < 2 {
continue;
}
for i in 0..owners.len() {
for j in (i + 1)..owners.len() {
if owners[i] == owners[j] {
continue;
}
let (sa, sb) = if owners[i] <= owners[j] {
(&owners[i], &owners[j])
} else {
(&owners[j], &owners[i])
};
cross_server_collisions.push(CrossServerCollision {
server_a: sa.clone(),
tool_a: tool_name.clone(),
server_b: sb.clone(),
tool_b: tool_name.clone(),
exact_name_duplicate: true,
similarity: 1.0,
fix_hint: format!(
"Namespace both servers before exposing to an agent: `{}{}` and `{}{}`.",
sanitize_prefix(sa),
tool_name,
sanitize_prefix(sb),
tool_name
),
});
}
}
}
for pair in &combined_audit.collisions {
if pair.tool_a == pair.tool_b || pair.score < config.sibling_disambiguation_threshold {
continue;
}
let owners_a = tool_to_servers.get(&pair.tool_a);
let owners_b = tool_to_servers.get(&pair.tool_b);
if let (Some(oa), Some(ob)) = (owners_a, owners_b) {
for sa in oa {
for sb in ob {
if sa != sb {
cross_server_collisions.push(CrossServerCollision {
server_a: sa.clone(),
tool_a: pair.tool_a.clone(),
server_b: sb.clone(),
tool_b: pair.tool_b.clone(),
exact_name_duplicate: false,
similarity: pair.score,
fix_hint: format!(
"Clarify domain boundaries between `{sa}::{}` and `{sb}::{}` or namespace tools per server.",
pair.tool_a, pair.tool_b
),
});
}
}
}
}
}
cross_server_collisions.sort_by(|a, b| {
b.exact_name_duplicate
.cmp(&a.exact_name_duplicate)
.then_with(|| b.similarity.total_cmp(&a.similarity))
.then_with(|| a.server_a.cmp(&b.server_a))
.then_with(|| a.tool_a.cmp(&b.tool_a))
});
cross_server_collisions.dedup_by(|a, b| {
a.server_a == b.server_a
&& a.tool_a == b.tool_a
&& a.server_b == b.server_b
&& a.tool_b == b.tool_b
});
let cross_server_exact_duplicates = cross_server_collisions
.iter()
.filter(|c| c.exact_name_duplicate)
.count();
let cross_server_semantic_collisions = cross_server_collisions
.len()
.saturating_sub(cross_server_exact_duplicates);
let exact_duplicates_if_namespaced = namespaced_audit
.collisions
.iter()
.filter(|c| c.tool_a == c.tool_b)
.count();
let mut deferral_recommendations = Vec::new();
let budget_ceiling = config.max_catalog_tokens;
if total_tokens > budget_ceiling || (servers.len() >= 4 && total_tokens > 8_000) {
let mut remaining = total_tokens;
let target = budget_ceiling.min(8_000);
let min_server_tokens = (target / 5).clamp(1, 1_000);
for s in &server_shares {
if remaining <= target {
break;
}
if s.estimated_tokens >= min_server_tokens {
deferral_recommendations.push(DeferralRecommendation {
server: s.server.clone(),
tool_count: s.tool_count,
tokens_saved: s.estimated_tokens,
session_usd_saved: s.estimated_200_turn_usd,
rationale: format!(
"Consumes {:.1}% of total tool context; load on-demand via BM25 tool search (`rmcp::ToolSearchServer` / `defer_loading`).",
s.token_share_pct
),
});
remaining = remaining.saturating_sub(s.estimated_tokens);
}
}
}
ComposeReport {
schema_version: SCHEMA_VERSION.into(),
server_count: servers.len(),
total_tools: combined_audit.summary.tool_count,
total_estimated_tokens: total_tokens,
total_200_turn_uncached_usd: combined_audit.summary.estimated_200_turn_session_usd,
total_200_turn_cached_usd: combined_audit.summary.estimated_200_turn_cached_usd,
combined_score: combined_audit.summary.overall_score,
combined_tier: combined_audit.summary.tier,
cross_server_exact_duplicates,
cross_server_semantic_collisions,
score_if_namespaced: namespaced_audit.summary.overall_score,
exact_duplicates_if_namespaced,
servers: server_shares,
cross_server_collisions,
deferral_recommendations,
combined_audit,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct McpServerLaunch {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub stdio_command: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
pub fn parse_mcp_client_config(json: &str) -> Result<Vec<McpServerLaunch>> {
let root: Value = serde_json::from_str(json)?;
let map = root
.get("mcpServers")
.or_else(|| root.get("servers"))
.and_then(Value::as_object)
.ok_or_else(|| {
Error::InvalidCatalogFormat(
"expected an MCP client config containing a top-level `mcpServers` or `servers` object".into(),
)
})?;
let mut launches = Vec::new();
for (name, cfg) in map {
let Some(obj) = cfg.as_object() else {
continue;
};
let url = obj.get("url").and_then(Value::as_str).map(str::to_string);
let stdio_command = obj.get("command").and_then(Value::as_str).map(|cmd| {
let mut parts = vec![quote_if_needed(cmd)];
if let Some(args) = obj.get("args").and_then(Value::as_array) {
for arg in args.iter().filter_map(Value::as_str) {
parts.push(quote_if_needed(arg));
}
}
parts.join(" ")
});
if stdio_command.is_some() || url.is_some() {
launches.push(McpServerLaunch {
name: name.clone(),
stdio_command,
url,
});
}
}
launches.sort_by(|a, b| a.name.cmp(&b.name));
Ok(launches)
}
fn sanitize_prefix(server_name: &str) -> String {
let clean: String = server_name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'_'
}
})
.collect();
let trimmed = clean.trim_matches('_');
if trimmed.is_empty() {
String::new()
} else {
format!("{trimmed}_")
}
}
fn quote_if_needed(arg: &str) -> String {
if arg.contains(char::is_whitespace) {
format!("\"{}\"", arg.replace('"', "\\\""))
} else {
arg.to_string()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn compose_detects_cross_server_duplicates_and_prefix_remediation() {
let mk = |name: &str, desc: &str| {
ToolSpec::new(
name,
Some(desc),
json!({"type": "object", "properties": {"title": {"type": "string", "description": "Issue title."}}})
.as_object()
.unwrap()
.clone(),
)
};
let github = Catalog::new([mk(
"create_issue",
"Creates a GitHub issue in a repository and returns its URL.",
)]);
let gitlab = Catalog::new([mk(
"create_issue",
"Creates a GitLab issue in a project and returns its URL.",
)]);
let report = compose_catalogs(
&[("github".into(), github), ("gitlab".into(), gitlab)],
&AuditConfig::default(),
);
assert_eq!(report.server_count, 2);
assert_eq!(report.cross_server_exact_duplicates, 1);
assert_eq!(report.exact_duplicates_if_namespaced, 0);
assert!(report.score_if_namespaced > report.combined_score);
assert!(report.to_markdown().contains("Namespace Prefix Simulation"));
}
#[test]
fn parses_standard_claude_and_cursor_mcp_configs() {
let cfg = r#"{
"mcpServers": {
"memory": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"] },
"remote": { "url": "http://localhost:3000/mcp" }
}
}"#;
let parsed = parse_mcp_client_config(cfg).unwrap();
assert_eq!(parsed.len(), 2);
assert_eq!(parsed[0].name, "memory");
assert_eq!(
parsed[0].stdio_command.as_deref(),
Some("npx -y @modelcontextprotocol/server-memory")
);
assert_eq!(parsed[1].url.as_deref(), Some("http://localhost:3000/mcp"));
}
}