返回 CodeWhale
external_import.rs
根目录 / crates / engine / src / mcp / external_import.rs
1 //! Consent-gated external MCP imports.
2 //!
3 //! Discovery can scan `~/.claude.json`, project `.mcp.json`, and marketplace
4 //! manifests. Import approval saves connectors OFF; a separate enable action
5 //! is required before any connection. Provenance
6 //! (source path + content hash) is shown before import. `enabled=false` and
7 //! `disabled=true` on a source entry are hard blocks — those candidates never
8 //! become managed connectors even after a blanket approval.
9 //!
10 //! Design (Kimi session_a75a393a-a984-4f35-98d0-b78cfbdcf23f): keep discovery
11 //! pure and independent of the TUI; merge approved servers through the same
12 //! config write path as `/mcp add`.
13
14 use std::collections::HashMap;
15 #[cfg(test)]
16 use std::fs;
17 use std::path::{Path, PathBuf};
18
19 use serde::{Deserialize, Serialize};
20 use serde_json::Value;
21 use sha2::{Digest, Sha256};
22
23 use codewhale_mcp::config::{McpConfig, McpServerConfig};
24
25 /// Where an import candidate came from.
26 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27 #[serde(rename_all = "snake_case")]
28 pub enum ExternalMcpSourceKind {
29 ClaudeJson,
30 ProjectMcpJson,
31 Marketplace,
32 }
33
34 impl ExternalMcpSourceKind {
35 #[must_use]
36 pub fn as_str(&self) -> &'static str {
37 match self {
38 Self::ClaudeJson => "claude.json",
39 Self::ProjectMcpJson => ".mcp.json",
40 Self::Marketplace => "marketplace",
41 }
42 }
43 }
44
45 /// One discovered server before consent.
46 #[derive(Debug, Clone, Serialize, Deserialize)]
47 pub struct ImportCandidate {
48 pub name: String,
49 pub source_kind: ExternalMcpSourceKind,
50 pub source_path: PathBuf,
51 /// Hex sha256 of this server's name and entry as parsed from the source.
52 /// It covers exactly what an approval imports, so review tokens and
53 /// decisions survive unrelated rewrites of the same file (Claude Code
54 /// rewrites `~/.claude.json` on nearly every run).
55 pub content_hash: String,
56 pub summary: String,
57 /// When true the entry is present but must never connect.
58 pub hard_blocked: bool,
59 pub block_reason: Option<String>,
60 pub server: McpServerConfig,
61 }
62
63 /// User decision for one candidate.
64 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65 #[serde(rename_all = "snake_case")]
66 pub enum ImportDecision {
67 Approve,
68 Decline,
69 Skip,
70 }
71
72 /// Durable consent / decline record keyed by source path + hash.
73 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
74 pub struct ImportConsentStore {
75 #[serde(default)]
76 pub entries: HashMap<String, ConsentEntry>,
77 }
78
79 #[derive(Debug, Clone, Serialize, Deserialize)]
80 pub struct ConsentEntry {
81 pub source_path: String,
82 pub content_hash: String,
83 pub decision: ImportDecision,
84 pub decided_at_unix: u64,
85 pub servers: Vec<String>,
86 }
87
88 fn consent_key(path: &Path, hash: &str) -> String {
89 format!("{}::{hash}", path.display())
90 }
91
92 /// Discover candidates from well-known external locations. Never connects.
93 pub fn discover_external_sources(
94 home: &Path,
95 workspace: &Path,
96 marketplace_paths: &[PathBuf],
97 ) -> Vec<ImportCandidate> {
98 let mut out = Vec::new();
99 let claude = home.join(".claude.json");
100 if claude.is_file() {
101 out.extend(discover_from_json_file(
102 &claude,
103 ExternalMcpSourceKind::ClaudeJson,
104 ));
105 }
106 let project_mcp = workspace.join(".mcp.json");
107 if project_mcp.is_file() {
108 out.extend(discover_from_json_file(
109 &project_mcp,
110 ExternalMcpSourceKind::ProjectMcpJson,
111 ));
112 }
113 for path in marketplace_paths {
114 if path.is_file() {
115 out.extend(discover_from_json_file(
116 path,
117 ExternalMcpSourceKind::Marketplace,
118 ));
119 }
120 }
121 out
122 }
123
124 fn discover_from_json_file(path: &Path, kind: ExternalMcpSourceKind) -> Vec<ImportCandidate> {
125 match checked_source(path, kind) {
126 Ok((candidates, problems)) => {
127 for problem in &problems {
128 tracing::warn!(target: "mcp", source = %path.display(), %problem, "skipping MCP import entry");
129 }
130 candidates
131 }
132 Err(error) => {
133 tracing::warn!(target: "mcp", source = %path.display(), %error, "skipping MCP import source");
134 Vec::new()
135 }
136 }
137 }
138
139 /// Most per-entry problems reported for one source; the rest are counted.
140 const MAX_PROBLEMS_PER_SOURCE: usize = 20;
141
142 /// Read one source. A file-level failure is an `Err`; an entry that fails
143 /// validation is reported in the second list (content-free) and skipped, so
144 /// one unsupported entry cannot hide its valid siblings. At most
145 /// [`MAX_PROBLEMS_PER_SOURCE`] entries are named, then one summary line.
146 fn checked_source(
147 path: &Path,
148 kind: ExternalMcpSourceKind,
149 ) -> anyhow::Result<(Vec<ImportCandidate>, Vec<String>)> {
150 super::validate_mcp_config_path(path)?;
151 // `~/.claude.json` is Claude Code's whole state file (project history,
152 // caches), routinely past the 1 MiB MCP config bound. Use the bound
153 // `/import-claude` already reads it with.
154 let max_bytes = match kind {
155 ExternalMcpSourceKind::ClaudeJson => codewhale_net::import_claude::MAX_SOURCE_BYTES,
156 _ => super::MAX_MCP_CONFIG_BYTES,
157 };
158 let Some(raw) = super::read_bounded_mcp_config_file(path, max_bytes)? else {
159 return Ok((Vec::new(), Vec::new()));
160 };
161 let value: Value = serde_json::from_str(&raw)
162 .map_err(|_| anyhow::anyhow!("Source is not valid JSON; contents omitted"))?;
163 anyhow::ensure!(
164 value
165 .get("mcpServers")
166 .or_else(|| value.get("servers"))
167 .is_some_and(Value::is_object)
168 || value.is_array(),
169 "Source has no supported MCP server map"
170 );
171 let mut out = Vec::new();
172 let mut problems = Vec::new();
173 let mut unreported = 0usize;
174 let mut report = |problem: String| {
175 if problems.len() < MAX_PROBLEMS_PER_SOURCE {
176 problems.push(problem);
177 } else {
178 unreported += 1;
179 }
180 };
181 for (name, config) in extract_servers_map(&value) {
182 if !(super::mcp_name_is_command_safe(&name) && name.len() <= 128) {
183 report("An entry with an unsupported server name was skipped".to_string());
184 continue;
185 }
186 let hash = entry_hash(&name, &config);
187 let server = match checked_entry(config, value.is_array()) {
188 Ok(server) => server,
189 Err(error) => {
190 report(format!("Server '{name}' was skipped: {error}"));
191 continue;
192 }
193 };
194 let hard_blocked = !server.is_enabled();
195 out.push(ImportCandidate {
196 summary: server_summary(&name, &server),
197 name,
198 source_kind: kind.clone(),
199 source_path: path.to_path_buf(),
200 content_hash: hash,
201 hard_blocked,
202 block_reason: hard_blocked.then(|| "Disabled at its source; cannot import".into()),
203 server,
204 });
205 }
206 if unreported > 0 {
207 problems.push(format!("{unreported} more entries were skipped"));
208 }
209 Ok((out, problems))
210 }
211
212 fn entry_hash(name: &str, entry: &Value) -> String {
213 let mut bytes = name.as_bytes().to_vec();
214 bytes.push(0);
215 bytes.extend(entry.to_string().into_bytes());
216 hex_sha256(&bytes)
217 }
218
219 /// Validate one server entry. Error messages never echo entry contents.
220 fn checked_entry(mut config: Value, from_array: bool) -> anyhow::Result<McpServerConfig> {
221 if let Some(map) = config.as_object_mut() {
222 if from_array {
223 map.remove("name");
224 }
225 translate_entry_type(map)?;
226 }
227 let fields = config
228 .as_object()
229 .ok_or_else(|| anyhow::anyhow!("Invalid MCP entry; contents omitted"))?;
230 const ALLOWED: &[&str] = &[
231 "command",
232 "args",
233 "env",
234 "cwd",
235 "url",
236 "allow_private_network",
237 "transport",
238 "connect_timeout",
239 "execute_timeout",
240 "read_timeout",
241 "disabled",
242 "enabled",
243 "required",
244 "enabled_tools",
245 "disabled_tools",
246 "headers",
247 "env_headers",
248 "env_http_headers",
249 "bearer_token_env_var",
250 "scopes",
251 "oauth",
252 "oauth_resource",
253 ];
254 anyhow::ensure!(
255 fields.keys().all(|key| ALLOWED.contains(&key.as_str())),
256 "Entry contains unsupported MCP fields; review it at its source"
257 );
258 if let Some(oauth) = fields.get("oauth").filter(|v| !v.is_null()) {
259 anyhow::ensure!(
260 oauth.as_object().is_some_and(|map| map
261 .keys()
262 .all(|key| matches!(key.as_str(), "client_id" | "issuer" | "client_metadata_url"))),
263 "Entry contains unsupported OAuth fields"
264 );
265 }
266 let server: McpServerConfig = serde_json::from_value(config)
267 .map_err(|_| anyhow::anyhow!("Invalid MCP entry; contents omitted"))?;
268 anyhow::ensure!(
269 server.command.is_some() != server.url.is_some(),
270 "MCP entry must have one target"
271 );
272 if let Some(command) = &server.command {
273 anyhow::ensure!(
274 !command.trim().is_empty() && !command.chars().any(char::is_control),
275 "Invalid MCP command"
276 );
277 }
278 if let Some(url) = &server.url {
279 let parsed = reqwest::Url::parse(url).map_err(|_| anyhow::anyhow!("Invalid MCP URL"))?;
280 anyhow::ensure!(
281 matches!(parsed.scheme(), "http" | "https")
282 && parsed.host_str().is_some()
283 && parsed.username().is_empty()
284 && parsed.password().is_none(),
285 "Unsupported MCP URL"
286 );
287 }
288 super::validate_mcp_transport(server.transport.as_deref())
289 .map_err(|_| anyhow::anyhow!("Unsupported MCP transport"))?;
290 Ok(server)
291 }
292
293 /// Claude Code writes `"type": "stdio" | "http" | "sse"` on every entry. Fold
294 /// it into Codewhale's shape: the target field already selects stdio versus
295 /// HTTP, and only legacy SSE needs an explicit `transport`. A `type` that
296 /// contradicts the entry's target or transport is refused, never guessed.
297 fn translate_entry_type(map: &mut serde_json::Map<String, Value>) -> anyhow::Result<()> {
298 let Some(kind) = map.remove("type") else {
299 return Ok(());
300 };
301 let kind = kind
302 .as_str()
303 .map(|kind| kind.trim().to_ascii_lowercase())
304 .ok_or_else(|| anyhow::anyhow!("Unsupported MCP entry type"))?;
305 let transport = map
306 .get("transport")
307 .map(|transport| transport.as_str().map(str::trim));
308 let is_sse = transport.is_some_and(|t| t.is_some_and(|t| t.eq_ignore_ascii_case("sse")));
309 match kind.as_str() {
310 "stdio" => anyhow::ensure!(
311 map.contains_key("command") && transport.is_none(),
312 "MCP entry type does not match its target"
313 ),
314 "http" | "streamable-http" => anyhow::ensure!(
315 map.contains_key("url") && !is_sse,
316 "MCP entry type does not match its target"
317 ),
318 "sse" => {
319 anyhow::ensure!(
320 map.contains_key("url") && (transport.is_none() || is_sse),
321 "MCP entry type does not match its target"
322 );
323 map.insert("transport".to_string(), Value::String("sse".to_string()));
324 }
325 _ => anyhow::bail!("Unsupported MCP entry type"),
326 }
327 Ok(())
328 }
329
330 fn extract_servers_map(value: &Value) -> Vec<(String, Value)> {
331 // Claude / team: { "mcpServers": { name: {...} } }
332 // Marketplace catalog: { "servers": { name: {...} } } or array of {name, ...}
333 if let Some(map) = value
334 .get("mcpServers")
335 .or_else(|| value.get("servers"))
336 .and_then(|v| v.as_object())
337 {
338 return map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
339 }
340 if let Some(arr) = value.as_array() {
341 let mut out = Vec::new();
342 for item in arr {
343 let Some(name) = item.get("name").and_then(|v| v.as_str()) else {
344 continue;
345 };
346 out.push((name.to_string(), item.clone()));
347 }
348 return out;
349 }
350 Vec::new()
351 }
352
353 fn destination(server: &McpServerConfig) -> String {
354 if let Some(url) = &server.url {
355 return reqwest::Url::parse(url)
356 .map(|url| url.origin().ascii_serialization())
357 .unwrap_or_else(|_| "Invalid URL".into());
358 }
359 server
360 .command
361 .as_deref()
362 .and_then(|command| Path::new(command).file_name())
363 .map(|name| name.to_string_lossy().into_owned())
364 .unwrap_or_else(|| "Unknown command".into())
365 }
366
367 fn server_summary(name: &str, server: &McpServerConfig) -> String {
368 format!(
369 "{name} — {} ({} arguments; credential values hidden)",
370 destination(server),
371 server.args.len()
372 )
373 }
374
375 fn hex_sha256(bytes: &[u8]) -> String {
376 let digest = Sha256::digest(bytes);
377 digest.iter().map(|b| format!("{b:02x}")).collect()
378 }
379
380 /// Record decisions against the latest consent document under the shared
381 /// process lock. Malformed history is never silently replaced with empty state.
382 pub fn persist_decisions(
383 path: &Path,
384 candidates: &[ImportCandidate],
385 decisions: &HashMap<String, ImportDecision>,
386 now_unix: u64,
387 ) -> anyhow::Result<()> {
388 super::validate_mcp_config_path(path)?;
389 codewhale_config::with_config_write_lock(path, |path| {
390 let original = super::read_mcp_config_file(path)?;
391 let mut raw: Value = match original.as_deref() {
392 Some(raw) => serde_json::from_str(raw)
393 .map_err(|_| anyhow::anyhow!("Invalid MCP consent history; contents omitted"))?,
394 None => serde_json::json!({}),
395 };
396 anyhow::ensure!(raw.is_object(), "MCP consent history must be an object");
397 let mut store: ImportConsentStore = if original.is_none() {
398 ImportConsentStore::default()
399 } else {
400 serde_json::from_value(raw.clone())
401 .map_err(|_| anyhow::anyhow!("Invalid MCP consent history; contents omitted"))?
402 };
403 let before = serde_json::to_value(&store)?;
404 record_decisions(&mut store, candidates, decisions, now_unix);
405 let after = serde_json::to_value(&store)?;
406 super::apply_json_delta(&mut raw, &before, &after);
407 let rendered = serde_json::to_vec_pretty(&raw)?;
408 if rendered.len() as u64 > super::MAX_MCP_CONFIG_BYTES {
409 anyhow::bail!("MCP consent history exceeds size limit");
410 }
411 codewhale_util::utils::write_atomic(path, &rendered)?;
412 Ok(())
413 })
414 }
415
416 /// Apply approvals: returns servers to merge into user mcp.json.
417 /// Hard-blocked candidates are never returned even if decision is Approve.
418 #[cfg(any(test, feature = "test-support"))]
419 pub fn apply_approved(
420 candidates: &[ImportCandidate],
421 decisions: &HashMap<String, ImportDecision>,
422 ) -> Vec<(String, McpServerConfig, ImportCandidate)> {
423 let mut out = Vec::new();
424 for candidate in candidates {
425 let decision = decisions
426 .get(&candidate.name)
427 .copied()
428 .unwrap_or(ImportDecision::Skip);
429 if decision != ImportDecision::Approve {
430 continue;
431 }
432 if candidate.hard_blocked {
433 continue;
434 }
435 out.push((
436 candidate.name.clone(),
437 candidate.server.clone(),
438 candidate.clone(),
439 ));
440 }
441 out
442 }
443
444 /// Record decisions in the consent store (including declines).
445 pub fn record_decisions(
446 store: &mut ImportConsentStore,
447 candidates: &[ImportCandidate],
448 decisions: &HashMap<String, ImportDecision>,
449 now_unix: u64,
450 ) {
451 // Group by source path + entry hash: one record per reviewed entry.
452 let mut by_source: HashMap<(PathBuf, String), Vec<(&ImportCandidate, ImportDecision)>> =
453 HashMap::new();
454 for candidate in candidates {
455 let decision = decisions
456 .get(&candidate.name)
457 .copied()
458 .unwrap_or(ImportDecision::Skip);
459 if decision == ImportDecision::Skip {
460 continue;
461 }
462 by_source
463 .entry((
464 candidate.source_path.clone(),
465 candidate.content_hash.clone(),
466 ))
467 .or_default()
468 .push((candidate, decision));
469 }
470 for ((path, hash), group) in by_source {
471 // If any approval exists, record Approve with the approved names;
472 // pure decline groups record Decline.
473 let any_approve = group.iter().any(|(_, d)| *d == ImportDecision::Approve);
474 let decision = if any_approve {
475 ImportDecision::Approve
476 } else {
477 ImportDecision::Decline
478 };
479 let servers: Vec<String> = group
480 .iter()
481 .filter(|(_, d)| *d == ImportDecision::Approve)
482 .filter(|(c, _)| !c.hard_blocked)
483 .map(|(c, _)| c.name.clone())
484 .collect();
485 let key = consent_key(&path, &hash);
486 store.entries.insert(
487 key,
488 ConsentEntry {
489 source_path: path.display().to_string(),
490 content_hash: hash,
491 decision,
492 decided_at_unix: now_unix,
493 servers,
494 },
495 );
496 }
497 }
498
499 /// Merge approved servers into an existing McpConfig. Does not touch
500 /// hard-blocked entries. Returns names that were newly inserted.
501 #[cfg(any(test, feature = "test-support"))]
502 pub fn merge_approved_into_config(
503 config: &mut McpConfig,
504 approved: &[(String, McpServerConfig, ImportCandidate)],
505 ) -> Vec<String> {
506 let mut inserted = Vec::new();
507 for (name, server, _) in approved {
508 if config.servers.contains_key(name) {
509 continue;
510 }
511 // Defense in depth: never insert disabled servers.
512 if !server.is_enabled() {
513 continue;
514 }
515 let mut server = server.clone();
516 server.enabled = false;
517 server.disabled = true;
518 config.servers.insert(name.clone(), server);
519 inserted.push(name.clone());
520 }
521 inserted
522 }
523
524 /// Human-readable provenance block for the selector / status panel.
525 #[cfg(any(test, feature = "test-support"))]
526 pub fn format_candidates_for_display(candidates: &[ImportCandidate]) -> String {
527 if candidates.is_empty() {
528 return "No external MCP sources found (or all already decided for current content)."
529 .to_string();
530 }
531 let mut lines = vec![
532 "External MCP import candidates (nothing is installed until you approve):".to_string(),
533 String::new(),
534 ];
535 for (idx, c) in candidates.iter().enumerate() {
536 let status = if c.hard_blocked { "BLOCKED" } else { "pending" };
537 lines.push(format!(
538 " {}. [{}] {} — provenance: {} ({})",
539 idx + 1,
540 status,
541 c.summary,
542 c.source_kind.as_str(),
543 c.source_path.display()
544 ));
545 lines.push(format!(
546 " content_hash: {}",
547 &c.content_hash[..12.min(c.content_hash.len())]
548 ));
549 if let Some(reason) = &c.block_reason {
550 lines.push(format!(" {reason}"));
551 }
552 }
553 lines.push(String::new());
554 lines.push(
555 "Run /mcp import for a current reviewed approval token. Imports stay off until enabled separately."
556 .to_string(),
557 );
558 lines.join("\n")
559 }
560
561 /// One authority shared by the native API and terminal import UI. Sources are
562 /// selected here; callers cannot supply arbitrary source paths to the API.
563 pub struct ImportContext<'a> {
564 pub workspace: &'a Path,
565 pub mcp_path: &'a Path,
566 pub plugins: &'a codewhale_plugins::PluginRegistry,
567 pub home: PathBuf,
568 pub codewhale_home: PathBuf,
569 }
570 impl<'a> ImportContext<'a> {
571 pub fn new(
572 workspace: &'a Path,
573 mcp_path: &'a Path,
574 plugins: &'a codewhale_plugins::PluginRegistry,
575 ) -> anyhow::Result<Self> {
576 Ok(Self {
577 workspace,
578 mcp_path,
579 plugins,
580 home: codewhale_paths::user_home()
581 .ok_or_else(|| anyhow::anyhow!("Home directory unavailable"))?,
582 codewhale_home: codewhale_config::codewhale_home()?,
583 })
584 }
585 fn discover(&self) -> (Vec<ImportCandidate>, Vec<ImportProblem>) {
586 let sources = [
587 (
588 self.home.join(".claude.json"),
589 ExternalMcpSourceKind::ClaudeJson,
590 ),
591 (
592 self.workspace.join(".mcp.json"),
593 ExternalMcpSourceKind::ProjectMcpJson,
594 ),
595 (
596 self.codewhale_home.join("mcp-marketplace.json"),
597 ExternalMcpSourceKind::Marketplace,
598 ),
599 ];
600 let mut candidates = Vec::new();
601 let mut problems = Vec::new();
602 for (path, kind) in sources {
603 match checked_source(&path, kind.clone()) {
604 Ok((found, skipped)) => {
605 candidates.extend(found);
606 problems.extend(skipped.into_iter().map(|message| ImportProblem {
607 source_kind: kind.clone(),
608 message,
609 }));
610 }
611 Err(_) => problems.push(ImportProblem { source_kind: kind,
612 message: "Source could not be safely read or contains unsupported configuration; review it at its source".into() }),
613 }
614 }
615 (candidates, problems)
616 }
617 fn merged(&self) -> anyhow::Result<McpConfig> {
618 super::load_config_with_workspace_and_plugins(self.mcp_path, self.workspace, self.plugins)
619 }
620 }
621
622 #[derive(Debug, Serialize)]
623 pub struct ImportProblem {
624 pub source_kind: ExternalMcpSourceKind,
625 pub message: String,
626 }
627 #[derive(Debug, Serialize)]
628 pub struct ReviewedImport {
629 pub id: String,
630 pub name: String,
631 pub source_kind: ExternalMcpSourceKind,
632 pub source_path: PathBuf,
633 pub content_hash: String,
634 pub transport: &'static str,
635 pub destination: String,
636 pub argument_count: usize,
637 pub env_keys: Vec<String>,
638 pub header_keys: Vec<String>,
639 pub credential_configured: bool,
640 pub hard_blocked: bool,
641 pub conflict: bool,
642 pub review_token: String,
643 }
644 #[derive(Debug, Serialize)]
645 pub struct ImportPreview {
646 pub revision: String,
647 pub candidates: Vec<ReviewedImport>,
648 pub problems: Vec<ImportProblem>,
649 }
650 #[derive(Debug, Serialize)]
651 pub struct ImportReceipt {
652 pub name: String,
653 pub decision: ImportDecision,
654 pub imported: bool,
655 pub enabled: bool,
656 pub revision: String,
657 pub consent_recorded: bool,
658 pub warning: Option<String>,
659 }
660 fn candidate_id(candidate: &ImportCandidate) -> String {
661 hex_sha256(
662 format!(
663 "{}\0{}\0{}",
664 candidate.source_kind.as_str(),
665 candidate.source_path.display(),
666 candidate.name
667 )
668 .as_bytes(),
669 )
670 }
671 fn source_blocked(context: &ImportContext<'_>, candidate: &ImportCandidate) -> bool {
672 candidate.hard_blocked
673 || (candidate.source_kind == ExternalMcpSourceKind::ProjectMcpJson
674 && !codewhale_runtime::config::is_workspace_trusted(context.workspace))
675 }
676
677 pub fn preview_imports(context: &ImportContext<'_>) -> anyhow::Result<ImportPreview> {
678 codewhale_config::with_config_write_lock(context.mcp_path, |path| {
679 let revision = super::read_config_revision(path)?;
680 let merged = context.merged()?;
681 let (candidates, problems) = context.discover();
682 let candidates = candidates
683 .into_iter()
684 .map(|candidate| {
685 let id = candidate_id(&candidate);
686 let server = &candidate.server;
687 let mut env_keys: Vec<_> = server.env.keys().cloned().collect();
688 env_keys.sort();
689 let mut header_keys: Vec<_> = server
690 .headers
691 .keys()
692 .chain(server.env_headers.keys())
693 .cloned()
694 .collect();
695 header_keys.sort();
696 header_keys.dedup();
697 ReviewedImport {
698 review_token: format!(
699 "mcp-import-v1:{id}:{}:{revision}",
700 candidate.content_hash
701 ),
702 id,
703 transport: if server.url.is_some() {
704 "http"
705 } else {
706 "stdio"
707 },
708 destination: destination(server),
709 argument_count: server.args.len(),
710 env_keys,
711 header_keys,
712 credential_configured: !server.env.is_empty()
713 || !server.headers.is_empty()
714 || !server.env_headers.is_empty()
715 || server.bearer_token_env_var.is_some()
716 || server.oauth.is_some()
717 || server.oauth_resource.is_some(),
718 hard_blocked: source_blocked(context, &candidate),
719 conflict: merged.servers.contains_key(&candidate.name),
720 name: candidate.name,
721 source_kind: candidate.source_kind,
722 source_path: candidate.source_path,
723 content_hash: candidate.content_hash,
724 }
725 })
726 .collect();
727 Ok(ImportPreview {
728 revision,
729 candidates,
730 problems,
731 })
732 })
733 }
734
735 /// Re-read exact reviewed bytes inside the same config transaction as insertion.
736 /// Nothing connects here. Consent follows a successful write and cannot turn a
737 /// completed import into a false failed-write receipt.
738 pub fn apply_reviewed_import(
739 context: &ImportContext<'_>,
740 id: &str,
741 hash: &str,
742 revision: &str,
743 decision: ImportDecision,
744 ) -> anyhow::Result<ImportReceipt> {
745 anyhow::ensure!(
746 matches!(decision, ImportDecision::Approve | ImportDecision::Decline),
747 "Choose approve or decline"
748 );
749 let (candidate, revision) = super::mutate_config(context.mcp_path, Some(revision), |config| {
750 let (candidates, _) = context.discover();
751 let candidate = candidates
752 .into_iter()
753 .find(|candidate| candidate_id(candidate) == id)
754 .ok_or_else(|| {
755 anyhow::anyhow!("Reviewed source is unavailable; refresh the import preview")
756 })?;
757 anyhow::ensure!(
758 candidate.content_hash == hash,
759 "Source changed; refresh the import preview"
760 );
761 if decision == ImportDecision::Approve {
762 anyhow::ensure!(
763 !source_blocked(context, &candidate),
764 "Source is disabled or its workspace is untrusted"
765 );
766 anyhow::ensure!(
767 !context.merged()?.servers.contains_key(&candidate.name)
768 && !config.servers.contains_key(&candidate.name),
769 "A managed, project or plugin connector already uses this name"
770 );
771 let mut server = candidate.server.clone();
772 server.enabled = false;
773 server.disabled = true;
774 config.servers.insert(candidate.name.clone(), server);
775 }
776 Ok(candidate)
777 })?;
778 let decisions = HashMap::from([(candidate.name.clone(), decision)]);
779 let now = std::time::SystemTime::now()
780 .duration_since(std::time::UNIX_EPOCH)
781 .map_or(0, |time| time.as_secs());
782 let consent_recorded = persist_decisions(
783 &context.codewhale_home.join("mcp-import-consent.json"),
784 std::slice::from_ref(&candidate),
785 &decisions,
786 now,
787 )
788 .is_ok();
789 Ok(ImportReceipt { name: candidate.name, decision, imported: decision == ImportDecision::Approve,
790 enabled: false, revision, consent_recorded,
791 warning: (!consent_recorded).then(|| "The decision could not be added to import history; the configuration receipt above is authoritative".into()),
792 })
793 }
794
795 pub fn parse_review_token(token: &str) -> anyhow::Result<(&str, &str, &str)> {
796 let parts: Vec<_> = token.split(':').collect();
797 anyhow::ensure!(
798 parts.len() == 4
799 && parts[0] == "mcp-import-v1"
800 && parts[1..3]
801 .iter()
802 .all(|value| value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit()))
803 && (parts[3] == "mcp-v1-absent"
804 || parts[3].strip_prefix("mcp-v1-").is_some_and(
805 |hash| hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit())
806 )),
807 "Approval needs a reviewed token, not a name. Run /mcp import and copy its approve or decline command"
808 );
809 Ok((parts[1], parts[2], parts[3]))
810 }
811
812 #[cfg(test)]
813 mod tests {
814 use super::*;
815 use tempfile::tempdir;
816
817 fn write_claude_json(dir: &Path, body: &str) -> PathBuf {
818 let path = dir.join(".claude.json");
819 fs::write(&path, body).unwrap();
820 path
821 }
822
823 fn with_import_context(test: impl FnOnce(&ImportContext<'_>)) {
824 let _env = crate::test_support::lock_test_env();
825 let root = tempdir().unwrap();
826 let home = root.path().join("home");
827 let workspace = root.path().join("workspace");
828 let state = root.path().join("state");
829 for path in [&home, &workspace, &state] {
830 fs::create_dir_all(path).unwrap();
831 }
832 let path = state.join("mcp.json");
833 let plugins = codewhale_plugins::PluginRegistry::empty(&workspace);
834 test(&ImportContext {
835 workspace: &workspace,
836 mcp_path: &path,
837 plugins: &plugins,
838 home,
839 codewhale_home: state,
840 });
841 }
842
843 #[test]
844 fn reviewed_import_rejects_changed_source_and_stale_revision() {
845 with_import_context(|context| {
846 let source =
847 write_claude_json(&context.home, r#"{"mcpServers":{"x":{"command":"echo"}}}"#);
848 let preview = preview_imports(context).unwrap();
849 let row = &preview.candidates[0];
850 fs::write(&source, r#"{"mcpServers":{"x":{"command":"changed"}}}"#).unwrap();
851 assert!(
852 apply_reviewed_import(
853 context,
854 &row.id,
855 &row.content_hash,
856 &preview.revision,
857 ImportDecision::Approve
858 )
859 .unwrap_err()
860 .to_string()
861 .contains("Source changed")
862 );
863 assert!(!context.mcp_path.exists());
864 let preview = preview_imports(context).unwrap();
865 let row = &preview.candidates[0];
866 fs::write(context.mcp_path, r#"{"servers":{}}"#).unwrap();
867 assert!(
868 apply_reviewed_import(
869 context,
870 &row.id,
871 &row.content_hash,
872 &preview.revision,
873 ImportDecision::Approve
874 )
875 .unwrap_err()
876 .is::<super::super::McpRevisionConflict>()
877 );
878 });
879 }
880
881 #[test]
882 fn reviewed_import_is_off_and_reports_history_failure_after_commit() {
883 with_import_context(|context| {
884 write_claude_json(
885 &context.home,
886 r#"{"mcpServers":{"x":{"command":"never-launch-this"}}}"#,
887 );
888 let preview = preview_imports(context).unwrap();
889 let row = &preview.candidates[0];
890 fs::write(
891 context.codewhale_home.join("mcp-import-consent.json"),
892 "invalid history",
893 )
894 .unwrap();
895 let receipt = apply_reviewed_import(
896 context,
897 &row.id,
898 &row.content_hash,
899 &preview.revision,
900 ImportDecision::Approve,
901 )
902 .unwrap();
903 assert!(receipt.imported);
904 assert!(!receipt.enabled);
905 assert!(!receipt.consent_recorded);
906 assert!(receipt.warning.is_some());
907 assert!(
908 !super::super::load_config(context.mcp_path).unwrap().servers["x"].is_enabled()
909 );
910 let next = preview_imports(context).unwrap();
911 assert!(next.candidates[0].conflict);
912 assert!(
913 apply_reviewed_import(
914 context,
915 &row.id,
916 &row.content_hash,
917 &next.revision,
918 ImportDecision::Approve
919 )
920 .is_err()
921 );
922 });
923 }
924
925 #[test]
926 fn reviewed_decline_does_not_create_config_and_preview_hides_values() {
927 with_import_context(|context| {
928 write_claude_json(
929 &context.home,
930 r#"{"mcpServers":{"x":{"url":"https://example.test/private-secret?key=secret-value","headers":{"Authorization":"header-secret"},"env":{"TOKEN":"env-secret"}}}}"#,
931 );
932 let preview = preview_imports(context).unwrap();
933 let rendered = serde_json::to_string(&preview).unwrap();
934 for secret in [
935 "private-secret",
936 "secret-value",
937 "header-secret",
938 "env-secret",
939 ] {
940 assert!(!rendered.contains(secret));
941 }
942 let row = &preview.candidates[0];
943 assert_eq!(row.destination, "https://example.test");
944 assert!(row.credential_configured);
945 assert!(parse_review_token(&row.review_token).is_ok());
946 assert!(parse_review_token("x").is_err());
947 let receipt = apply_reviewed_import(
948 context,
949 &row.id,
950 &row.content_hash,
951 &preview.revision,
952 ImportDecision::Decline,
953 )
954 .unwrap();
955 assert!(!receipt.imported);
956 assert!(receipt.consent_recorded);
957 assert_eq!(receipt.revision, preview.revision);
958 assert!(!context.mcp_path.exists());
959 });
960 }
961
962 #[test]
963 fn reviewed_import_blocks_disabled_and_untrusted_project_sources() {
964 with_import_context(|context| {
965 write_claude_json(
966 &context.home,
967 r#"{"mcpServers":{"disabled":{"command":"echo","disabled":true}}}"#,
968 );
969 fs::write(
970 context.workspace.join(".mcp.json"),
971 r#"{"mcpServers":{"project":{"command":"echo"}}}"#,
972 )
973 .unwrap();
974 let preview = preview_imports(context).unwrap();
975 assert_eq!(preview.candidates.len(), 2);
976 for row in preview.candidates {
977 assert!(row.hard_blocked);
978 assert!(
979 apply_reviewed_import(
980 context,
981 &row.id,
982 &row.content_hash,
983 &preview.revision,
984 ImportDecision::Approve
985 )
986 .is_err()
987 );
988 }
989 assert!(!context.mcp_path.exists());
990 });
991 }
992
993 #[test]
994 fn reviewed_discovery_rejects_oversize_and_symlink_sources() {
995 with_import_context(|context| {
996 let path = context.home.join(".claude.json");
997 fs::write(
998 &path,
999 vec![b' '; codewhale_net::import_claude::MAX_SOURCE_BYTES as usize + 1],
1000 )
1001 .unwrap();
1002 let preview = preview_imports(context).unwrap();
1003 assert!(preview.candidates.is_empty());
1004 assert_eq!(preview.problems.len(), 1);
1005 #[cfg(unix)]
1006 {
1007 fs::remove_file(&path).unwrap();
1008 let target = context.home.join("target.json");
1009 fs::write(&target, r#"{"mcpServers":{"x":{"command":"echo"}}}"#).unwrap();
1010 std::os::unix::fs::symlink(&target, &path).unwrap();
1011 let preview = preview_imports(context).unwrap();
1012 assert!(preview.candidates.is_empty());
1013 assert_eq!(preview.problems.len(), 1);
1014 }
1015 });
1016 }
1017
1018 #[test]
1019 fn claude_code_entries_with_type_import_and_bad_siblings_are_skipped_alone() {
1020 with_import_context(|context| {
1021 write_claude_json(
1022 &context.home,
1023 r#"{"mcpServers":{
1024 "local":{"type":"stdio","command":"npx","args":["-y","pkg"]},
1025 "remote":{"type":"http","url":"https://mcp.example.test/mcp"},
1026 "legacy":{"type":"sse","url":"https://sse.example.test/sse"},
1027 "odd":{"type":"sse","command":"npx"},
1028 "extra":{"command":"echo","unknownField":"secret-value"}
1029 }}"#,
1030 );
1031 let preview = preview_imports(context).unwrap();
1032 let mut names: Vec<_> = preview.candidates.iter().map(|c| c.name.as_str()).collect();
1033 names.sort_unstable();
1034 assert_eq!(names, ["legacy", "local", "remote"]);
1035 let messages: Vec<_> = preview
1036 .problems
1037 .iter()
1038 .map(|p| p.message.as_str())
1039 .collect();
1040 assert_eq!(messages.len(), 2, "{messages:?}");
1041 assert!(messages.iter().any(|m| m.contains("'odd'")));
1042 assert!(messages.iter().any(|m| m.contains("'extra'")));
1043 assert!(
1044 !serde_json::to_string(&preview)
1045 .unwrap()
1046 .contains("secret-value")
1047 );
1048
1049 let candidates = discover_external_sources(&context.home, context.workspace, &[]);
1050 let legacy = candidates.iter().find(|c| c.name == "legacy").unwrap();
1051 assert_eq!(legacy.server.transport.as_deref(), Some("sse"));
1052 let remote = candidates.iter().find(|c| c.name == "remote").unwrap();
1053 assert_eq!(remote.server.transport, None);
1054 });
1055 }
1056
1057 #[test]
1058 fn skipped_entries_from_one_source_are_capped() {
1059 with_import_context(|context| {
1060 let entries: Vec<String> = (0..MAX_PROBLEMS_PER_SOURCE + 5)
1061 .map(|i| format!(r#""bad{i}":{{"x":1}}"#))
1062 .collect();
1063 write_claude_json(
1064 &context.home,
1065 &format!(
1066 r#"{{"mcpServers":{{{},"ok":{{"command":"echo"}}}}}}"#,
1067 entries.join(",")
1068 ),
1069 );
1070 let preview = preview_imports(context).unwrap();
1071 assert_eq!(preview.candidates.len(), 1);
1072 assert_eq!(preview.problems.len(), MAX_PROBLEMS_PER_SOURCE + 1);
1073 assert_eq!(
1074 preview.problems.last().unwrap().message,
1075 "5 more entries were skipped"
1076 );
1077 });
1078 }
1079
1080 #[test]
1081 fn unrelated_source_rewrites_keep_review_tokens() {
1082 with_import_context(|context| {
1083 let source = write_claude_json(
1084 &context.home,
1085 r#"{"numStartups":1,"mcpServers":{"x":{"command":"echo"},"y":{"command":"echo"}}}"#,
1086 );
1087 let preview = preview_imports(context).unwrap();
1088 // Claude Code rewrites its state file on every run.
1089 fs::write(
1090 &source,
1091 r#"{"numStartups":2,"mcpServers":{"x":{"command":"echo"},"y":{"command":"echo"}}}"#,
1092 )
1093 .unwrap();
1094 let row = preview.candidates.iter().find(|c| c.name == "x").unwrap();
1095 let receipt = apply_reviewed_import(
1096 context,
1097 &row.id,
1098 &row.content_hash,
1099 &preview.revision,
1100 ImportDecision::Approve,
1101 )
1102 .unwrap();
1103 assert!(receipt.imported);
1104 });
1105 }
1106
1107 #[test]
1108 fn claude_json_larger_than_the_mcp_config_bound_is_discovered() {
1109 with_import_context(|context| {
1110 let padding = "x".repeat(super::super::MAX_MCP_CONFIG_BYTES as usize * 3 / 2);
1111 write_claude_json(
1112 &context.home,
1113 &format!(r#"{{"history":"{padding}","mcpServers":{{"x":{{"command":"echo"}}}}}}"#),
1114 );
1115 let preview = preview_imports(context).unwrap();
1116 assert!(preview.problems.is_empty());
1117 assert_eq!(preview.candidates.len(), 1);
1118 assert_eq!(preview.candidates[0].name, "x");
1119 });
1120 }
1121
1122 #[test]
1123 fn consent_transaction_preserves_other_sources_and_unknown_fields() {
1124 let dir = tempdir().unwrap();
1125 let path = dir.path().join("consent.json");
1126 fs::write(&path, r#"{"entries":{},"extension":{"owner":"external"}}"#).unwrap();
1127 for name in ["first", "second"] {
1128 let source = dir.path().join(format!("{name}.json"));
1129 fs::write(
1130 &source,
1131 format!(r#"{{"mcpServers":{{"{name}":{{"command":"echo"}}}}}}"#),
1132 )
1133 .unwrap();
1134 let candidates = discover_from_json_file(&source, ExternalMcpSourceKind::ClaudeJson);
1135 let decisions = HashMap::from([(name.to_string(), ImportDecision::Approve)]);
1136 persist_decisions(&path, &candidates, &decisions, 1).unwrap();
1137 }
1138 let raw: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
1139 assert_eq!(raw["extension"]["owner"], "external");
1140 assert_eq!(raw["entries"].as_object().unwrap().len(), 2);
1141 fs::write(&path, "malformed-sensitive-history").unwrap();
1142 let error = persist_decisions(&path, &[], &HashMap::new(), 2).unwrap_err();
1143 assert!(!error.to_string().contains("malformed-sensitive-history"));
1144 assert_eq!(
1145 fs::read_to_string(&path).unwrap(),
1146 "malformed-sensitive-history"
1147 );
1148 }
1149
1150 #[test]
1151 fn disabled_imported_server_never_merges() {
1152 let dir = tempdir().unwrap();
1153 let body = r#"{
1154 "mcpServers": {
1155 "ok": { "command": "npx", "args": ["-y", "good"], "enabled": true },
1156 "blocked": { "command": "npx", "args": ["-y", "bad"], "enabled": false }
1157 }
1158 }"#;
1159 write_claude_json(dir.path(), body);
1160 let candidates = discover_external_sources(dir.path(), dir.path(), &[]);
1161 assert_eq!(candidates.len(), 2);
1162 let blocked = candidates.iter().find(|c| c.name == "blocked").unwrap();
1163 assert!(blocked.hard_blocked);
1164
1165 let mut decisions = HashMap::new();
1166 decisions.insert("ok".into(), ImportDecision::Approve);
1167 decisions.insert("blocked".into(), ImportDecision::Approve);
1168 let approved = apply_approved(&candidates, &decisions);
1169 assert_eq!(approved.len(), 1);
1170 assert_eq!(approved[0].0, "ok");
1171
1172 let mut config = McpConfig::default();
1173 let inserted = merge_approved_into_config(&mut config, &approved);
1174 assert_eq!(inserted, vec!["ok".to_string()]);
1175 assert!(!config.servers.contains_key("blocked"));
1176 assert!(!config.servers["ok"].is_enabled());
1177 }
1178
1179 #[test]
1180 fn provenance_display_includes_source_and_hash() {
1181 let dir = tempdir().unwrap();
1182 write_claude_json(
1183 dir.path(),
1184 r#"{"mcpServers":{"hf":{"url":"https://example.com/mcp","enabled":true}}}"#,
1185 );
1186 let candidates = discover_external_sources(dir.path(), dir.path(), &[]);
1187 let text = format_candidates_for_display(&candidates);
1188 assert!(text.contains("provenance:"));
1189 assert!(text.contains("claude.json"));
1190 assert!(text.contains("content_hash:"));
1191 assert!(text.contains("nothing is installed until you approve"));
1192 }
1193
1194 #[test]
1195 fn project_mcp_json_and_marketplace_are_discovered() {
1196 let home = tempdir().unwrap();
1197 let workspace = tempdir().unwrap();
1198 fs::write(
1199 workspace.path().join(".mcp.json"),
1200 r#"{"mcpServers":{"team":{"command":"uvx","args":["team-mcp"]}}}"#,
1201 )
1202 .unwrap();
1203 let market = home.path().join("market.json");
1204 fs::write(
1205 &market,
1206 r#"{"servers":{"shop":{"url":"https://market.example/mcp"}}}"#,
1207 )
1208 .unwrap();
1209 let candidates = discover_external_sources(home.path(), workspace.path(), &[market]);
1210 let names: Vec<_> = candidates.iter().map(|c| c.name.as_str()).collect();
1211 assert!(names.contains(&"team"));
1212 assert!(names.contains(&"shop"));
1213 }
1214 }
1215
1215 lines RUST