1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::auditor::{AuditConfig, Auditor};
7use crate::error::{Error, Result};
8use crate::model::{round2, AuditReport, Catalog, Tier, ToolSpec, SCHEMA_VERSION};
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct ServerTokenShare {
13 pub server: String,
15 pub tool_count: usize,
17 pub estimated_tokens: usize,
19 pub token_share_pct: f32,
21 pub estimated_200_turn_usd: f32,
23 pub standalone_score: f32,
25 pub standalone_errors: usize,
27 pub standalone_warnings: usize,
29}
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub struct CrossServerCollision {
35 pub server_a: String,
37 pub tool_a: String,
39 pub server_b: String,
41 pub tool_b: String,
43 pub exact_name_duplicate: bool,
45 pub similarity: f32,
47 pub fix_hint: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub struct DeferralRecommendation {
55 pub server: String,
57 pub tool_count: usize,
59 pub tokens_saved: usize,
61 pub session_usd_saved: f32,
63 pub rationale: String,
65}
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub struct ComposeReport {
70 pub schema_version: String,
72 pub server_count: usize,
74 pub total_tools: usize,
76 pub total_estimated_tokens: usize,
78 pub total_200_turn_uncached_usd: f32,
80 pub total_200_turn_cached_usd: f32,
82 pub combined_score: f32,
84 pub combined_tier: Tier,
86 pub cross_server_exact_duplicates: usize,
88 pub cross_server_semantic_collisions: usize,
90 pub score_if_namespaced: f32,
92 pub exact_duplicates_if_namespaced: usize,
94 pub servers: Vec<ServerTokenShare>,
96 pub cross_server_collisions: Vec<CrossServerCollision>,
98 pub deferral_recommendations: Vec<DeferralRecommendation>,
100 pub combined_audit: AuditReport,
102}
103
104impl ComposeReport {
105 pub fn to_json_pretty(&self) -> Result<String> {
107 Ok(serde_json::to_string_pretty(self)?)
108 }
109
110 pub fn to_json_compact(&self) -> Result<String> {
112 Ok(serde_json::to_string(self)?)
113 }
114
115 pub fn to_text(&self) -> String {
117 let mut out = String::new();
118 out.push_str(&format!(
119 "mcp-vol compose: {} servers | {} tools | score {:.2}/5.00 (Tier {}) | ~{} tokens (~${:.2}/200t uncached, ~${:.2} cached)\n",
120 self.server_count,
121 self.total_tools,
122 self.combined_score,
123 self.combined_tier,
124 self.total_estimated_tokens,
125 self.total_200_turn_uncached_usd,
126 self.total_200_turn_cached_usd,
127 ));
128 out.push_str(&format!(
129 "cross-server collisions: {} exact duplicate(s), {} semantic overlap(s) | if namespaced: score {:.2}/5.00 ({} exact duplicates)\n",
130 self.cross_server_exact_duplicates,
131 self.cross_server_semantic_collisions,
132 self.score_if_namespaced,
133 self.exact_duplicates_if_namespaced,
134 ));
135 out.push_str("\nPer-server breakdown:\n");
136 for s in &self.servers {
137 out.push_str(&format!(
138 " {:20} {:3} tools | ~{:5} tok ({:5.1}%) | ~${:.2}/200t | score {:.2}\n",
139 s.server,
140 s.tool_count,
141 s.estimated_tokens,
142 s.token_share_pct,
143 s.estimated_200_turn_usd,
144 s.standalone_score,
145 ));
146 }
147 if !self.cross_server_collisions.is_empty() {
148 out.push_str("\nCross-server collisions:\n");
149 for c in self.cross_server_collisions.iter().take(20) {
150 let kind = if c.exact_name_duplicate {
151 "EXACT DUP"
152 } else {
153 "OVERLAP"
154 };
155 out.push_str(&format!(
156 " [{}] {}::{} <-> {}::{} (sim={:.2})\n",
157 kind, c.server_a, c.tool_a, c.server_b, c.tool_b, c.similarity
158 ));
159 }
160 }
161 if !self.deferral_recommendations.is_empty() {
162 out.push_str("\nOn-demand deferral recommendations:\n");
163 for rec in &self.deferral_recommendations {
164 out.push_str(&format!(
165 " [DEFER] {} ({} tools, saves ~{} tok / ~${:.2}/200t): {}\n",
166 rec.server,
167 rec.tool_count,
168 rec.tokens_saved,
169 rec.session_usd_saved,
170 rec.rationale
171 ));
172 }
173 }
174 out
175 }
176
177 pub fn to_markdown(&self) -> String {
179 let mut out = String::new();
180 out.push_str(&format!(
181 "### `mcp-vol` Multi-Server Composition Audit — **{} Servers / {} Tools** (Score **{:.2}/5.00**, Tier **{}**)\n\n",
182 self.server_count, self.total_tools, self.combined_score, self.combined_tier
183 ));
184 out.push_str(&format!(
185 "- **Context Payload:** ~{} tokens (~${:.2} / 200-turn uncached, ~${:.2} cached)\n",
186 self.total_estimated_tokens,
187 self.total_200_turn_uncached_usd,
188 self.total_200_turn_cached_usd
189 ));
190 out.push_str(&format!(
191 "- **Cross-Server Collisions:** **{} exact duplicate(s)**, **{} semantic overlap(s)**\n",
192 self.cross_server_exact_duplicates, self.cross_server_semantic_collisions
193 ));
194 out.push_str(&format!(
195 "- **Namespace Prefix Simulation (`<server>_`):** Score **{:.2} → {:.2}**, exact duplicates **{} → {}**\n\n",
196 self.combined_score,
197 self.score_if_namespaced,
198 self.cross_server_exact_duplicates,
199 self.exact_duplicates_if_namespaced
200 ));
201
202 out.push_str("#### Per-Server Token & Quality Attribution\n\n");
203 out.push_str("| Server | Tools | Est. Tokens | Share | Est. $/200t | Standalone Score | Errors | Warnings |\n");
204 out.push_str("|---|---:|---:|---:|---:|---:|---:|---:|\n");
205 for s in &self.servers {
206 out.push_str(&format!(
207 "| `{}` | {} | ~{} | {:.1}% | ${:.2} | {:.2} | {} | {} |\n",
208 s.server,
209 s.tool_count,
210 s.estimated_tokens,
211 s.token_share_pct,
212 s.estimated_200_turn_usd,
213 s.standalone_score,
214 s.standalone_errors,
215 s.standalone_warnings
216 ));
217 }
218
219 if !self.cross_server_collisions.is_empty() {
220 out.push_str("\n#### Cross-Server Collisions\n\n");
221 out.push_str("| Type | Server A | Server B | Similarity |\n|---|---|---|---:|\n");
222 for c in self.cross_server_collisions.iter().take(25) {
223 let kind = if c.exact_name_duplicate {
224 "**Exact Duplicate**"
225 } else {
226 "Semantic Overlap"
227 };
228 out.push_str(&format!(
229 "| {} | `{}`::`{}` | `{}`::`{}` | `{:.2}` |\n",
230 kind, c.server_a, c.tool_a, c.server_b, c.tool_b, c.similarity
231 ));
232 }
233 }
234
235 if !self.deferral_recommendations.is_empty() {
236 out.push_str("\n#### On-Demand Tool Deferral Recommendations\n\n");
237 for rec in &self.deferral_recommendations {
238 out.push_str(&format!(
239 "- Defer `{}` ({} tools, saves ~{} tokens / ~${:.2} per 200-turn session): {}\n",
240 rec.server, rec.tool_count, rec.tokens_saved, rec.session_usd_saved, rec.rationale
241 ));
242 }
243 }
244 out
245 }
246}
247
248#[must_use]
262pub fn compose_catalogs(servers: &[(String, Catalog)], config: &AuditConfig) -> ComposeReport {
263 let auditor = Auditor::new(config.clone());
264
265 let mut merged_tools: Vec<ToolSpec> = Vec::new();
266 let mut namespaced_tools: Vec<ToolSpec> = Vec::new();
267 let mut tool_to_servers: BTreeMap<String, Vec<String>> = BTreeMap::new();
268 let mut raw_shares: Vec<(String, usize, usize, f32, usize, usize)> = Vec::new();
269
270 for (srv_name, cat) in servers {
271 let tagged = cat.with_source_server(srv_name);
272 let standalone = auditor.audit(&tagged);
273 let tokens = tagged.estimated_total_tokens();
274 raw_shares.push((
275 srv_name.clone(),
276 tagged.len(),
277 tokens,
278 standalone.summary.overall_score,
279 standalone.summary.error_count,
280 standalone.summary.warning_count,
281 ));
282
283 for tool in tagged.tools() {
284 tool_to_servers
285 .entry(tool.name.clone())
286 .or_default()
287 .push(srv_name.clone());
288 merged_tools.push(tool.clone());
289 }
290
291 let prefix = sanitize_prefix(srv_name);
292 let prefixed = tagged.with_namespace_prefix(&prefix);
293 namespaced_tools.extend(prefixed.tools().iter().cloned());
294 }
295
296 let combined_catalog = Catalog::new(merged_tools);
297 let combined_audit = auditor.audit(&combined_catalog);
298
299 let namespaced_catalog = Catalog::new(namespaced_tools);
300 let namespaced_audit = auditor.audit(&namespaced_catalog);
301
302 let total_tokens = combined_audit.summary.estimated_catalog_tokens;
303 let total_tokens_f = total_tokens.max(1) as f32;
304
305 let mut server_shares: Vec<ServerTokenShare> = raw_shares
306 .into_iter()
307 .map(
308 |(
309 server,
310 tool_count,
311 estimated_tokens,
312 standalone_score,
313 standalone_errors,
314 standalone_warnings,
315 )| {
316 let share_pct = round2((estimated_tokens as f32 / total_tokens_f) * 100.0);
317 let session_usd = round2(
318 (estimated_tokens as f32 / 1_000_000.0)
319 * config.input_price_per_million_usd
320 * 200.0,
321 );
322 ServerTokenShare {
323 server,
324 tool_count,
325 estimated_tokens,
326 token_share_pct: share_pct,
327 estimated_200_turn_usd: session_usd,
328 standalone_score,
329 standalone_errors,
330 standalone_warnings,
331 }
332 },
333 )
334 .collect();
335
336 server_shares.sort_by(|a, b| {
337 b.estimated_tokens
338 .cmp(&a.estimated_tokens)
339 .then_with(|| a.server.cmp(&b.server))
340 });
341
342 let mut cross_server_collisions: Vec<CrossServerCollision> = Vec::new();
344 for (tool_name, owners) in &tool_to_servers {
345 if owners.len() < 2 {
346 continue;
347 }
348 for i in 0..owners.len() {
349 for j in (i + 1)..owners.len() {
350 if owners[i] == owners[j] {
351 continue;
352 }
353 let (sa, sb) = if owners[i] <= owners[j] {
354 (&owners[i], &owners[j])
355 } else {
356 (&owners[j], &owners[i])
357 };
358 cross_server_collisions.push(CrossServerCollision {
359 server_a: sa.clone(),
360 tool_a: tool_name.clone(),
361 server_b: sb.clone(),
362 tool_b: tool_name.clone(),
363 exact_name_duplicate: true,
364 similarity: 1.0,
365 fix_hint: format!(
366 "Namespace both servers before exposing to an agent: `{}{}` and `{}{}`.",
367 sanitize_prefix(sa),
368 tool_name,
369 sanitize_prefix(sb),
370 tool_name
371 ),
372 });
373 }
374 }
375 }
376
377 for pair in &combined_audit.collisions {
378 if pair.tool_a == pair.tool_b || pair.score < config.sibling_disambiguation_threshold {
379 continue;
380 }
381 let owners_a = tool_to_servers.get(&pair.tool_a);
382 let owners_b = tool_to_servers.get(&pair.tool_b);
383 if let (Some(oa), Some(ob)) = (owners_a, owners_b) {
384 for sa in oa {
385 for sb in ob {
386 if sa != sb {
387 cross_server_collisions.push(CrossServerCollision {
388 server_a: sa.clone(),
389 tool_a: pair.tool_a.clone(),
390 server_b: sb.clone(),
391 tool_b: pair.tool_b.clone(),
392 exact_name_duplicate: false,
393 similarity: pair.score,
394 fix_hint: format!(
395 "Clarify domain boundaries between `{sa}::{}` and `{sb}::{}` or namespace tools per server.",
396 pair.tool_a, pair.tool_b
397 ),
398 });
399 }
400 }
401 }
402 }
403 }
404
405 cross_server_collisions.sort_by(|a, b| {
406 b.exact_name_duplicate
407 .cmp(&a.exact_name_duplicate)
408 .then_with(|| b.similarity.total_cmp(&a.similarity))
409 .then_with(|| a.server_a.cmp(&b.server_a))
410 .then_with(|| a.tool_a.cmp(&b.tool_a))
411 });
412 cross_server_collisions.dedup_by(|a, b| {
413 a.server_a == b.server_a
414 && a.tool_a == b.tool_a
415 && a.server_b == b.server_b
416 && a.tool_b == b.tool_b
417 });
418
419 let cross_server_exact_duplicates = cross_server_collisions
420 .iter()
421 .filter(|c| c.exact_name_duplicate)
422 .count();
423 let cross_server_semantic_collisions = cross_server_collisions
424 .len()
425 .saturating_sub(cross_server_exact_duplicates);
426
427 let exact_duplicates_if_namespaced = namespaced_audit
428 .collisions
429 .iter()
430 .filter(|c| c.tool_a == c.tool_b)
431 .count();
432
433 let mut deferral_recommendations = Vec::new();
435 let budget_ceiling = config.max_catalog_tokens;
436 if total_tokens > budget_ceiling || (servers.len() >= 4 && total_tokens > 8_000) {
437 let mut remaining = total_tokens;
438 let target = budget_ceiling.min(8_000);
439 let min_server_tokens = (target / 5).clamp(1, 1_000);
440 for s in &server_shares {
441 if remaining <= target {
442 break;
443 }
444 if s.estimated_tokens >= min_server_tokens {
445 deferral_recommendations.push(DeferralRecommendation {
446 server: s.server.clone(),
447 tool_count: s.tool_count,
448 tokens_saved: s.estimated_tokens,
449 session_usd_saved: s.estimated_200_turn_usd,
450 rationale: format!(
451 "Consumes {:.1}% of total tool context; load on-demand via BM25 tool search (`rmcp::ToolSearchServer` / `defer_loading`).",
452 s.token_share_pct
453 ),
454 });
455 remaining = remaining.saturating_sub(s.estimated_tokens);
456 }
457 }
458 }
459
460 ComposeReport {
461 schema_version: SCHEMA_VERSION.into(),
462 server_count: servers.len(),
463 total_tools: combined_audit.summary.tool_count,
464 total_estimated_tokens: total_tokens,
465 total_200_turn_uncached_usd: combined_audit.summary.estimated_200_turn_session_usd,
466 total_200_turn_cached_usd: combined_audit.summary.estimated_200_turn_cached_usd,
467 combined_score: combined_audit.summary.overall_score,
468 combined_tier: combined_audit.summary.tier,
469 cross_server_exact_duplicates,
470 cross_server_semantic_collisions,
471 score_if_namespaced: namespaced_audit.summary.overall_score,
472 exact_duplicates_if_namespaced,
473 servers: server_shares,
474 cross_server_collisions,
475 deferral_recommendations,
476 combined_audit,
477 }
478}
479
480#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
483pub struct McpServerLaunch {
484 pub name: String,
486 #[serde(skip_serializing_if = "Option::is_none")]
488 pub stdio_command: Option<String>,
489 #[serde(skip_serializing_if = "Option::is_none")]
491 pub url: Option<String>,
492}
493
494pub fn parse_mcp_client_config(json: &str) -> Result<Vec<McpServerLaunch>> {
497 let root: Value = serde_json::from_str(json)?;
498 let map = root
499 .get("mcpServers")
500 .or_else(|| root.get("servers"))
501 .and_then(Value::as_object)
502 .ok_or_else(|| {
503 Error::InvalidCatalogFormat(
504 "expected an MCP client config containing a top-level `mcpServers` or `servers` object".into(),
505 )
506 })?;
507
508 let mut launches = Vec::new();
509 for (name, cfg) in map {
510 let Some(obj) = cfg.as_object() else {
511 continue;
512 };
513 let url = obj.get("url").and_then(Value::as_str).map(str::to_string);
514 let stdio_command = obj.get("command").and_then(Value::as_str).map(|cmd| {
515 let mut parts = vec![quote_if_needed(cmd)];
516 if let Some(args) = obj.get("args").and_then(Value::as_array) {
517 for arg in args.iter().filter_map(Value::as_str) {
518 parts.push(quote_if_needed(arg));
519 }
520 }
521 parts.join(" ")
522 });
523 if stdio_command.is_some() || url.is_some() {
524 launches.push(McpServerLaunch {
525 name: name.clone(),
526 stdio_command,
527 url,
528 });
529 }
530 }
531 launches.sort_by(|a, b| a.name.cmp(&b.name));
532 Ok(launches)
533}
534
535fn sanitize_prefix(server_name: &str) -> String {
536 let clean: String = server_name
537 .chars()
538 .map(|c| {
539 if c.is_ascii_alphanumeric() {
540 c.to_ascii_lowercase()
541 } else {
542 '_'
543 }
544 })
545 .collect();
546 let trimmed = clean.trim_matches('_');
547 if trimmed.is_empty() {
548 String::new()
549 } else {
550 format!("{trimmed}_")
551 }
552}
553
554fn quote_if_needed(arg: &str) -> String {
555 if arg.contains(char::is_whitespace) {
556 format!("\"{}\"", arg.replace('"', "\\\""))
557 } else {
558 arg.to_string()
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use serde_json::json;
565
566 use super::*;
567
568 #[test]
569 fn compose_detects_cross_server_duplicates_and_prefix_remediation() {
570 let mk = |name: &str, desc: &str| {
571 ToolSpec::new(
572 name,
573 Some(desc),
574 json!({"type": "object", "properties": {"title": {"type": "string", "description": "Issue title."}}})
575 .as_object()
576 .unwrap()
577 .clone(),
578 )
579 };
580 let github = Catalog::new([mk(
581 "create_issue",
582 "Creates a GitHub issue in a repository and returns its URL.",
583 )]);
584 let gitlab = Catalog::new([mk(
585 "create_issue",
586 "Creates a GitLab issue in a project and returns its URL.",
587 )]);
588
589 let report = compose_catalogs(
590 &[("github".into(), github), ("gitlab".into(), gitlab)],
591 &AuditConfig::default(),
592 );
593 assert_eq!(report.server_count, 2);
594 assert_eq!(report.cross_server_exact_duplicates, 1);
595 assert_eq!(report.exact_duplicates_if_namespaced, 0);
596 assert!(report.score_if_namespaced > report.combined_score);
597 assert!(report.to_markdown().contains("Namespace Prefix Simulation"));
598 }
599
600 #[test]
601 fn parses_standard_claude_and_cursor_mcp_configs() {
602 let cfg = r#"{
603 "mcpServers": {
604 "memory": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"] },
605 "remote": { "url": "http://localhost:3000/mcp" }
606 }
607 }"#;
608 let parsed = parse_mcp_client_config(cfg).unwrap();
609 assert_eq!(parsed.len(), 2);
610 assert_eq!(parsed[0].name, "memory");
611 assert_eq!(
612 parsed[0].stdio_command.as_deref(),
613 Some("npx -y @modelcontextprotocol/server-memory")
614 );
615 assert_eq!(parsed[1].url.as_deref(), Some("http://localhost:3000/mcp"));
616 }
617}