返回 CodeWhale
runtime_mcp.rs
根目录 / crates / engine / src / tools / runtime_mcp.rs
1 //! Runtime MCP server management.
2 //!
3 //! Provides `StartRuntimeMcpServer` — the entry tool for LLM to dynamically
4 //! connect to MCP servers from conversation context. Also contains parsing
5 //! and naming helpers used by the tool.
6
7 use std::collections::HashMap;
8 use std::sync::Arc;
9
10 use anyhow::Result;
11 use serde_json::{Value, json};
12 use tokio::sync::Mutex as AsyncMutex;
13
14 use crate::mcp::McpPool;
15 use crate::tools::spec::{
16 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
17 };
18 use codewhale_mcp::config::McpServerConfig;
19
20 // === Parsing Functions ===
21
22 #[derive(Debug, Clone)]
23 pub struct ParsedMcpServer {
24 pub name: String,
25 pub config: McpServerConfig,
26 }
27
28 /// Parse a command string or URL into an MCP server configuration.
29 ///
30 /// - Local command: `npx @modelcontextprotocol/server-filesystem /tmp`
31 /// - Remote URL: `https://huggingface.co/mcp`
32 pub fn parse_mcp_command(input: &str) -> Result<ParsedMcpServer> {
33 let input = input.trim();
34 if input.is_empty() {
35 anyhow::bail!("MCP command cannot be empty");
36 }
37
38 if input.starts_with("http://") || input.starts_with("https://") {
39 let name = extract_name_from_url(input)?;
40 return Ok(ParsedMcpServer {
41 name,
42 config: McpServerConfig {
43 command: None,
44 args: Vec::new(),
45 env: HashMap::new(),
46 cwd: None,
47 url: Some(input.to_string()),
48 transport: None,
49 connect_timeout: None,
50 execute_timeout: None,
51 read_timeout: None,
52 disabled: false,
53 enabled: true,
54 required: false,
55 lazy: false,
56 enabled_tools: Vec::new(),
57 disabled_tools: Vec::new(),
58 always_allow_tools: Vec::new(),
59 headers: HashMap::new(),
60 env_headers: HashMap::new(),
61 bearer_token_env_var: None,
62 scopes: Vec::new(),
63 oauth: None,
64 oauth_resource: None,
65 reviewed_plugin: None,
66 runtime_added: false,
67 allow_private_network: false,
68 },
69 });
70 }
71
72 let parts: Vec<String> = shell_words::split(input).unwrap_or_default();
73 if parts.is_empty() {
74 anyhow::bail!("MCP command cannot be empty");
75 }
76
77 let command = parts[0].clone();
78 let args: Vec<String> = parts[1..].to_vec();
79 let name = infer_server_name(&command, &args)?;
80
81 Ok(ParsedMcpServer {
82 name,
83 config: McpServerConfig {
84 command: Some(command),
85 args,
86 env: HashMap::new(),
87 cwd: None,
88 url: None,
89 transport: None,
90 connect_timeout: None,
91 execute_timeout: None,
92 read_timeout: None,
93 disabled: false,
94 enabled: true,
95 required: false,
96 lazy: false,
97 enabled_tools: Vec::new(),
98 disabled_tools: Vec::new(),
99 always_allow_tools: Vec::new(),
100 headers: HashMap::new(),
101 env_headers: HashMap::new(),
102 bearer_token_env_var: None,
103 scopes: Vec::new(),
104 oauth: None,
105 oauth_resource: None,
106 reviewed_plugin: None,
107 runtime_added: false,
108 allow_private_network: false,
109 },
110 })
111 }
112
113 pub fn extract_name_from_url(url: &str) -> Result<String> {
114 let parsed = reqwest::Url::parse(url)?;
115 let host = parsed.host_str().unwrap_or("remote");
116 let path = parsed.path().trim_matches('/');
117
118 // Replace dots with dashes in hostname for better readability
119 let host_part = host.replace('.', "-");
120
121 // Combine host and path, replacing slashes with underscores
122 let name = if path.is_empty() {
123 host_part
124 } else {
125 format!("{}_{}", host_part, path.replace('/', "_"))
126 };
127
128 Ok(sanitize_name(&name))
129 }
130
131 fn infer_server_name(command: &str, args: &[String]) -> Result<String> {
132 let cmd_path = std::path::Path::new(command);
133 let cmd_base = cmd_path.file_stem().unwrap_or_default().to_string_lossy();
134
135 // Windows cmd /c prefix: skip "cmd /c" and recurse on the remaining args
136 // e.g. ["cmd", "/c", "npx", "-y", "@modelcontextprotocol/server-memory"]
137 if cmd_base.as_ref() == "cmd"
138 && args.len() >= 2
139 && (args[0] == "/c" || args[0] == "/C" || args[0] == "/k" || args[0] == "/K")
140 {
141 let inner_cmd = &args[1];
142 let inner_args: Vec<String> = args[2..].to_vec();
143 return infer_server_name(inner_cmd, &inner_args);
144 }
145
146 // Package managers: extract the package name (first non-flag arg)
147 if matches!(
148 cmd_base.as_ref(),
149 "npx" | "npm" | "pnpm" | "yarn" | "bunx" | "bun"
150 ) {
151 for arg in args {
152 if !arg.starts_with('-') && arg != "exec" && arg != "run" && arg != "start" {
153 // e.g. "@modelcontextprotocol/server-filesystem" → "filesystem"
154 if let Some(name) = arg.split('/').next_back() {
155 if let Some(short) = name.strip_prefix("server-") {
156 return Ok(sanitize_name(short));
157 }
158 return Ok(sanitize_name(name));
159 }
160 }
161 }
162 }
163
164 // Script interpreters: extract the script path (first non-flag arg)
165 if matches!(
166 cmd_base.as_ref(),
167 "node" | "python" | "python3" | "uvx" | "uv" | "ruby" | "deno"
168 ) && let Some(script) = args.iter().find(|a| !a.starts_with('-'))
169 {
170 let script_path = std::path::Path::new(script);
171 if let Some(stem) = script_path.file_stem() {
172 return Ok(sanitize_name(&stem.to_string_lossy()));
173 }
174 }
175
176 // Fallback: first non-flag argument (script or file)
177 if let Some(script) = args.iter().find(|a| !a.starts_with('-')) {
178 let script_path = std::path::Path::new(script);
179 if let Some(stem) = script_path.file_stem() {
180 return Ok(sanitize_name(&stem.to_string_lossy()));
181 }
182 }
183
184 // Last resort: command name itself
185 Ok(sanitize_name(&cmd_base))
186 }
187
188 pub fn sanitize_name(name: &str) -> String {
189 name.chars()
190 .map(|c| {
191 if c.is_ascii_alphanumeric() || c == '-' {
192 c
193 } else {
194 '-'
195 }
196 })
197 .collect::<String>()
198 .trim_matches('-')
199 .to_string()
200 }
201
202 // === Tool: StartRuntimeMcpServer ===
203
204 /// Entry tool for dynamically adding MCP servers from conversation context.
205 ///
206 /// LLM calls this to start a local MCP server (stdio) or connect to a remote
207 /// one (HTTP). The server config is added to `McpPool.dynamic_servers` and
208 /// tools are discovered via the existing `McpConnection` / `StdioTransport` flow.
209 pub struct StartRuntimeMcpServer {
210 pool: Arc<AsyncMutex<McpPool>>,
211 }
212
213 impl StartRuntimeMcpServer {
214 pub fn new(pool: Arc<AsyncMutex<McpPool>>) -> Self {
215 Self { pool }
216 }
217 }
218
219 #[async_trait::async_trait]
220 impl ToolSpec for StartRuntimeMcpServer {
221 fn name(&self) -> &str {
222 "start_mcp_server"
223 }
224
225 fn description(&self) -> &str {
226 "When a user provides an MCP server command (like 'npx ...') or URL \
227 (like 'https://...'), call this tool immediately to start the server \
228 and register its tools. Do NOT suggest editing config files. \
229 Accepts a local command (stdio) or a remote URL (HTTP/SSE). \
230 To reconnect an existing configured server after login, pass only its exact name \
231 and omit server; this keeps its saved credentials and configuration. \
232 After the server starts, the response lists each tool's callable name. \
233 You MUST copy those exact names when calling the tools. \
234 Do NOT construct or guess tool names yourself."
235 }
236
237 fn input_schema(&self) -> Value {
238 json!({
239 "type": "object",
240 "properties": {
241 "server": {
242 "type": "string",
243 "description": "New MCP server command or URL; omit to reconnect a configured server by name"
244 },
245 "name": {
246 "type": "string",
247 "description": "Exact configured name for reconnect; optional name for a new server"
248 }
249 },
250 "anyOf": [{"required": ["server"]}, {"required": ["name"]}]
251 })
252 }
253
254 fn capabilities(&self) -> Vec<ToolCapability> {
255 vec![ToolCapability::Network, ToolCapability::ExecutesCode]
256 }
257
258 fn approval_requirement(&self) -> ApprovalRequirement {
259 ApprovalRequirement::Required
260 }
261
262 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
263 let custom_name = input.get("name").and_then(|v| v.as_str());
264 if input.get("server").is_none() {
265 let name = custom_name
266 .filter(|name| !name.trim().is_empty())
267 .ok_or_else(|| {
268 ToolError::invalid_input("Provide server or an existing configured name")
269 })?;
270 // The exact configured key owns its credentials and trust. Do not
271 // sanitize it into an alias, replace its config, or reconnect siblings.
272 if McpPool::server_denied_by(&context.disallowed_tools, name) {
273 return Err(ToolError::not_available(format!(
274 "Failed to find MCP server: {name}"
275 )));
276 }
277 let mut pool = self.pool.lock().await;
278 let conn = pool.retry_connection(name).await.map_err(|error| {
279 ToolError::execution_failed(connect_failure_message(name, &error))
280 })?;
281 let transport = if conn.config().url.is_some() {
282 "http"
283 } else {
284 "stdio"
285 };
286 return Ok(connected_result(&pool, name, transport, context));
287 }
288 let server = input
289 .get("server")
290 .and_then(|v| v.as_str())
291 .ok_or_else(|| ToolError::invalid_input("server must be a command or URL string"))?;
292 let mut parsed =
293 parse_mcp_command(server).map_err(|e| ToolError::invalid_input(e.to_string()))?;
294 // Host-supplied override (used by the Registry launcher, whose
295 // packages cold-start via npx/uvx downloads). Not exposed on the
296 // model-facing schema, so the model cannot widen its own timeouts.
297 if let Some(timeout) = input.get("connect_timeout").and_then(Value::as_u64) {
298 parsed.config.connect_timeout = Some(timeout);
299 }
300
301 // Refuse shell wrappers and anything outside the runtime allowlist.
302 if let Some(ref cmd) = parsed.config.command {
303 validate_runtime_command(cmd)?;
304 parsed.config.env.insert(
305 crate::tools::shell::AGENT_PROJECT_ENV.to_string(),
306 context.workspace.to_string_lossy().into_owned(),
307 );
308 }
309
310 // Reject shell metacharacters in arguments to prevent injection.
311 // Extracted to `reject_shell_metacharacters` so it is reachable from
312 // tests: the `reject_metachar_*` tests used to assert only that their
313 // own input string contained the metacharacter and never that this
314 // guard refused it, so deleting the guard left them green
315 // (2026-08-04 audit).
316 reject_shell_metacharacters(&parsed.config.args)?;
317
318 let server_name = custom_name
319 .map(sanitize_name)
320 .unwrap_or(parsed.name)
321 .replace('_', "-");
322 if server_name.is_empty() {
323 return Err(ToolError::invalid_input(
324 "MCP server name must contain at least one ASCII letter, digit or '-'",
325 ));
326 }
327
328 // Underscores in server names would cause tool name collision.
329 // Tool names are formatted as mcp_{server}_{tool}; underscores in
330 // server names would make it ambiguous (server "foo" + tool "bar_x"
331 // vs server "foo_bar" + tool "x" both → mcp_foo_bar_x).
332 // sanitize_name already converts non-alphanumeric chars to hyphens,
333 // but underscores from the original input need explicit conversion.
334
335 let transport = if parsed.config.url.is_some() {
336 "http"
337 } else {
338 "stdio"
339 };
340
341 // Ancestor restrictions stay request-local because children share the pool.
342 if McpPool::server_denied_by(&context.disallowed_tools, &server_name) {
343 return Err(ToolError::not_available(format!(
344 "Failed to find MCP server: {server_name}"
345 )));
346 }
347 // Register server config, connect, and collect tool info
348 let mut pool = self.pool.lock().await;
349 pool.add_runtime_server_config(server_name.clone(), parsed.config)
350 .map_err(ToolError::invalid_input)?;
351 let conn = match pool.get_or_connect(&server_name).await {
352 Ok(conn) => conn,
353 Err(error) => {
354 let message = connect_failure_message(&server_name, &error);
355 pool.remove_runtime_server_config(&server_name);
356 return Err(ToolError::execution_failed(message));
357 }
358 };
359
360 let _ = conn;
361 Ok(connected_result(&pool, &server_name, transport, context))
362 }
363 }
364
365 /// Shared receipt for both new servers and configured-name reconnects.
366 fn connected_result(
367 pool: &McpPool,
368 server_name: &str,
369 transport: &str,
370 context: &ToolContext,
371 ) -> ToolResult {
372 let owners = pool.resolved_tool_servers();
373 let tools_list: Vec<String> = pool
374 .all_tools()
375 .into_iter()
376 .filter(|(name, _)| {
377 owners.get(name).map(String::as_str) == Some(server_name)
378 && !codewhale_execpolicy::tool_rules::tool_matches_any_rule(
379 &context.disallowed_tools,
380 name,
381 )
382 })
383 .map(|(name, tool)| {
384 format!(
385 "- {} → {}",
386 name,
387 tool.description.as_deref().unwrap_or("no description")
388 )
389 })
390 .collect();
391 let result = serde_json::to_string(&json!({
392 "status": "connected",
393 "transport": transport,
394 "server": server_name,
395 "new_tools": tools_list.len(),
396 "total_mcp_tools": pool.all_tools().iter().filter(|(name, _)| !codewhale_execpolicy::tool_rules::tool_matches_any_rule(&context.disallowed_tools, name)).count(),
397 "message": format!(
398 "MCP server '{}' connected via {}. {} tools discovered.\n\nCallable tools (use these exact names):\n{}",
399 server_name, transport, tools_list.len(), tools_list.join("\n")
400 )
401 })).unwrap_or_else(|_| "{}".to_string());
402 let mut output = ToolResult::success(result);
403 output.metadata = Some(json!({ "mcp_catalog_changed": true }));
404 output
405 }
406
407 /// Shell interpreters that would run an arbitrary script as the "server".
408 const SHELL_WRAPPERS: &[&str] = &["bash", "sh", "zsh", "cmd", "powershell"];
409
410 /// Known MCP server runtimes and package managers. Anything else is refused
411 /// to prevent arbitrary execution.
412 const ALLOWED_COMMANDS: &[&str] = &[
413 "npx", "npm", "pnpm", "yarn", "bunx", "bun", "node", "python", "python3", "uvx", "uv", "deno",
414 "ruby", "cargo",
415 ];
416
417 /// Refuse a runtime MCP command that is a shell wrapper or is not a known
418 /// server runtime. Both checks read the command's lowercased file stem, so
419 /// `/bin/zsh` and `powershell.exe` are named for what they are. Kept out of
420 /// `execute` (as [`reject_shell_metacharacters`] is) so tests exercise the
421 /// real guard rather than a copy of its list.
422 fn validate_runtime_command(cmd: &str) -> Result<(), ToolError> {
423 let cmd_base = std::path::Path::new(cmd)
424 .file_stem()
425 .unwrap_or_default()
426 .to_string_lossy()
427 .to_lowercase();
428 if SHELL_WRAPPERS.contains(&cmd_base.as_str()) {
429 return Err(ToolError::invalid_input(format!(
430 "Shell wrapper commands ({cmd}) are not allowed. \
431 Provide the actual MCP server command directly, \
432 e.g. 'npx @modelcontextprotocol/server-filesystem /tmp'"
433 )));
434 }
435 if !ALLOWED_COMMANDS.contains(&cmd_base.as_str()) {
436 return Err(ToolError::invalid_input(format!(
437 "Command '{cmd}' is not in the allowed list. \
438 Permitted commands: {}",
439 ALLOWED_COMMANDS.join(", ")
440 )));
441 }
442 Ok(())
443 }
444
445 /// Refuse MCP server arguments carrying shell metacharacters.
446 ///
447 /// Redirects (`>`), pipes (`|`), chaining (`;`, `&`), subshells (`` ` ``), and
448 /// variable expansion (`$`) are all dangerous in an argv that may reach a
449 /// shell. Kept as a free function rather than inline in `execute` so it is
450 /// directly testable: the `reject_metachar_*` tests previously asserted only
451 /// that their own input contained the metacharacter, so deleting the guard
452 /// left every one of them green (2026-08-04 audit).
453 fn reject_shell_metacharacters(args: &[String]) -> Result<(), ToolError> {
454 for arg in args {
455 if arg.contains(['>', '|', ';', '&', '`', '$']) {
456 return Err(ToolError::invalid_input(format!(
457 "Argument contains shell metacharacters: '{arg}'. \
458 MCP server arguments must not contain redirects, pipes, \
459 command chaining, or variable expansion."
460 )));
461 }
462 }
463 Ok(())
464 }
465
466 /// Build the connect-failure message returned to the model. A spawned
467 /// package that prints its CLI help and exits (the classic
468 /// missing-subcommand case, e.g. `npx -y agentic-mermaid@0.1.2` without
469 /// `mcp`) surfaces as `Stdio transport closed` before the handshake
470 /// completes — a bare transport error gives the model no signal about
471 /// *why*, and it tends to abandon the MCP route after one failed server.
472 /// Classify that early-exit shape, note when the captured output looks
473 /// like usage help, and point recovery at the registry: verify the exact
474 /// structured arguments returned by `registry_sync`, then fall through to
475 /// the next candidate from the search results instead of giving up.
476 fn connect_failure_message(server_name: &str, err: &anyhow::Error) -> String {
477 let text = format!("{err:#}");
478 let base = format!("Failed to connect to MCP server '{server_name}': {text}");
479 let early_exit =
480 text.contains("Stdio transport closed") || text.contains("Stdio transport read error");
481 if !early_exit {
482 return base;
483 }
484 let looks_like_help = text.contains("usage")
485 || text.contains("Usage")
486 || text.contains("--help")
487 || text.contains("Commands:");
488 let help_note = if looks_like_help {
489 " Its output above looks like CLI usage help."
490 } else {
491 ""
492 };
493 format!(
494 "{base}\n\nThe server process exited before completing the MCP handshake.{help_note} The launch arguments are usually incomplete in this case (missing subcommand or required argument). For Registry-discovered servers, verify the structured required_args returned by registry_sync and retry; if this server still will not start, try the next candidate from the Registry catalog."
495 )
496 }
497
498 #[cfg(test)]
499 mod tests {
500 use super::*;
501
502 #[tokio::test]
503 async fn mcp_ceiling_runtime_registration_respects_child_policy_before_connection() {
504 let directory = tempfile::tempdir().unwrap();
505 let pool = Arc::new(AsyncMutex::new(McpPool::new(
506 codewhale_mcp::config::McpConfig::default(),
507 )));
508 let tool = StartRuntimeMcpServer::new(Arc::clone(&pool));
509 let mut context = ToolContext::new(directory.path());
510 context.disallowed_tools = vec!["mcp_private-*".to_string()];
511 // The command would execute if the child ceiling were ignored.
512 let error = tool
513 .execute(
514 json!({"server":"node nonexistent-mcp.js", "name":"private_a"}),
515 &context,
516 )
517 .await
518 .unwrap_err();
519 assert!(
520 error
521 .to_string()
522 .contains("Failed to find MCP server: private-a")
523 );
524 assert!(pool.lock().await.server_names().is_empty());
525 assert!(pool.lock().await.connected_servers().is_empty());
526 }
527
528 #[test]
529 fn parse_command_stdio() {
530 let parsed = parse_mcp_command("npx @modelcontextprotocol/server-filesystem /tmp").unwrap();
531 assert!(parsed.config.command.is_some());
532 assert!(parsed.config.url.is_none());
533 }
534
535 #[test]
536 fn parse_command_url() {
537 let parsed = parse_mcp_command("https://huggingface.co/mcp").unwrap();
538 assert!(parsed.config.command.is_none());
539 assert!(parsed.config.url.is_some());
540 assert_eq!(parsed.name, "huggingface-co-mcp");
541 }
542
543 #[test]
544 fn parse_command_url_with_subdomain() {
545 let parsed = parse_mcp_command("https://api.example.com/mcp").unwrap();
546 assert!(parsed.config.command.is_none());
547 assert!(parsed.config.url.is_some());
548 assert_eq!(parsed.name, "api-example-com-mcp");
549 }
550
551 #[test]
552 fn parse_command_empty() {
553 assert!(parse_mcp_command("").is_err());
554 assert!(parse_mcp_command(" ").is_err());
555 }
556
557 #[test]
558 fn extract_name_from_url_with_path() {
559 assert_eq!(
560 extract_name_from_url("https://huggingface.co/mcp").unwrap(),
561 "huggingface-co-mcp"
562 );
563 }
564
565 #[test]
566 fn extract_name_from_url_with_subdomain() {
567 assert_eq!(
568 extract_name_from_url("https://api.example.com/mcp").unwrap(),
569 "api-example-com-mcp"
570 );
571 }
572
573 #[test]
574 fn extract_name_from_url_no_path() {
575 assert_eq!(
576 extract_name_from_url("https://example.com").unwrap(),
577 "example-com"
578 );
579 }
580
581 #[test]
582 fn extract_name_from_url_empty_path() {
583 assert_eq!(
584 extract_name_from_url("https://example.com/").unwrap(),
585 "example-com"
586 );
587 }
588
589 #[test]
590 fn connect_failure_message_flags_early_exit_with_help_output() {
591 let err = anyhow::anyhow!(
592 "Stdio transport closed\nMCP server stderr (last 2 lines):\nUsage: agentic-mermaid [OPTIONS] <COMMAND>"
593 );
594 let msg = connect_failure_message("agentic-mermaid", &err);
595 assert!(msg.contains("Failed to connect to MCP server 'agentic-mermaid'"));
596 assert!(msg.contains("exited before completing the MCP handshake"));
597 assert!(msg.contains("looks like CLI usage help"));
598 assert!(msg.contains("required_args"));
599 assert!(msg.contains("next candidate"));
600 }
601
602 #[test]
603 fn connect_failure_message_flags_early_exit_without_help_output() {
604 let err = anyhow::anyhow!("Stdio transport closed");
605 let msg = connect_failure_message("x", &err);
606 assert!(msg.contains("exited before completing the MCP handshake"));
607 assert!(!msg.contains("usage help"));
608 assert!(msg.contains("required_args"));
609 }
610
611 #[test]
612 fn connect_failure_message_passes_other_errors_through() {
613 let err = anyhow::anyhow!("connection refused");
614 let msg = connect_failure_message("x", &err);
615 assert_eq!(
616 msg,
617 "Failed to connect to MCP server 'x': connection refused"
618 );
619 }
620
621 // === shell_words split tests ===
622
623 #[test]
624 fn shell_words_simple() {
625 assert_eq!(
626 shell_words::split("npx server /tmp").unwrap(),
627 vec!["npx", "server", "/tmp"]
628 );
629 }
630
631 #[test]
632 fn shell_words_double_quotes() {
633 assert_eq!(
634 shell_words::split(r#"npx server --env="MY KEY""#).unwrap(),
635 vec!["npx", "server", "--env=MY KEY"]
636 );
637 }
638
639 #[test]
640 fn shell_words_single_quotes() {
641 assert_eq!(
642 shell_words::split("npx server --env='MY KEY'").unwrap(),
643 vec!["npx", "server", "--env=MY KEY"]
644 );
645 }
646
647 #[test]
648 fn shell_words_mixed_quotes() {
649 assert_eq!(
650 shell_words::split(r#"cmd --opt="hello world" --flag 'single'"#).unwrap(),
651 vec!["cmd", "--opt=hello world", "--flag", "single"]
652 );
653 }
654
655 #[test]
656 fn shell_words_escaped_quote() {
657 assert_eq!(
658 shell_words::split(r#"cmd arg\"with\"quotes"#).unwrap(),
659 vec!["cmd", r#"arg"with"quotes"#]
660 );
661 }
662
663 #[test]
664 fn shell_words_empty() {
665 assert!(shell_words::split("").unwrap().is_empty());
666 assert!(shell_words::split(" ").unwrap().is_empty());
667 }
668
669 #[test]
670 fn shell_words_postgres_url() {
671 assert_eq!(
672 shell_words::split(
673 r#"npx -y @modelcontextprotocol/server-postgres "postgresql://user:pass@host/db""#
674 )
675 .unwrap(),
676 vec![
677 "npx",
678 "-y",
679 "@modelcontextprotocol/server-postgres",
680 "postgresql://user:pass@host/db"
681 ]
682 );
683 }
684
685 #[test]
686 fn parse_command_with_quoted_args() {
687 let parsed =
688 parse_mcp_command(r#"npx @modelcontextprotocol/server-filesystem /tmp --env="MY KEY""#)
689 .unwrap();
690 assert_eq!(parsed.config.command, Some("npx".to_string()));
691 assert_eq!(
692 parsed.config.args,
693 vec![
694 "@modelcontextprotocol/server-filesystem",
695 "/tmp",
696 "--env=MY KEY"
697 ]
698 );
699 }
700
701 // === infer_server_name tests ===
702
703 #[test]
704 fn infer_name_npx_package() {
705 let parsed = parse_mcp_command("npx @modelcontextprotocol/server-filesystem /tmp").unwrap();
706 assert_eq!(parsed.name, "filesystem");
707 }
708
709 #[test]
710 fn infer_name_npx_simple() {
711 let parsed = parse_mcp_command("npx my-mcp-server").unwrap();
712 assert_eq!(parsed.name, "my-mcp-server");
713 }
714
715 #[test]
716 fn infer_name_pnpm_exec() {
717 let parsed = parse_mcp_command("pnpm exec @modelcontextprotocol/server-postgres").unwrap();
718 assert_eq!(parsed.name, "postgres");
719 }
720
721 #[test]
722 fn infer_name_node_script() {
723 let parsed = parse_mcp_command("node ./my-mcp-server.js").unwrap();
724 assert_eq!(parsed.name, "my-mcp-server");
725 }
726
727 #[test]
728 fn infer_name_python_script() {
729 let parsed = parse_mcp_command("python3 mcp_server.py").unwrap();
730 assert_eq!(parsed.name, "mcp-server");
731 }
732
733 #[test]
734 fn infer_name_uvx_package() {
735 let parsed = parse_mcp_command("uvx mcp-server-git").unwrap();
736 assert_eq!(parsed.name, "mcp-server-git");
737 }
738
739 #[test]
740 fn infer_name_bare_command() {
741 let parsed = parse_mcp_command("/usr/local/bin/my-server").unwrap();
742 assert_eq!(parsed.name, "my-server");
743 }
744
745 #[test]
746 fn infer_name_windows_cmd_prefix() {
747 let parsed =
748 parse_mcp_command("cmd /c npx -y @modelcontextprotocol/server-memory").unwrap();
749 assert_eq!(parsed.name, "memory");
750 }
751
752 #[test]
753 fn infer_name_windows_cmd_uppercase() {
754 let parsed =
755 parse_mcp_command("cmd /C npx @modelcontextprotocol/server-filesystem /tmp").unwrap();
756 assert_eq!(parsed.name, "filesystem");
757 }
758
759 #[test]
760 fn infer_name_only_command_no_args() {
761 // No args at all — falls through to last resort: command name itself
762 let parsed = parse_mcp_command("my-server").unwrap();
763 assert_eq!(parsed.name, "my-server");
764 }
765
766 #[test]
767 fn infer_name_only_command_no_args_path() {
768 // Absolute path, no args — uses file_stem of command
769 let parsed = parse_mcp_command("/usr/local/bin/my-server").unwrap();
770 assert_eq!(parsed.name, "my-server");
771 }
772
773 // === sanitize_name tests ===
774
775 #[test]
776 fn sanitize_name_preserves_hyphens() {
777 assert_eq!(sanitize_name("my-server"), "my-server");
778 }
779
780 #[test]
781 fn sanitize_name_converts_underscores_to_hyphens() {
782 assert_eq!(sanitize_name("my_server"), "my-server");
783 }
784
785 #[test]
786 fn sanitize_name_converts_special_chars_to_hyphens() {
787 assert_eq!(sanitize_name("my@server!"), "my-server");
788 }
789
790 #[test]
791 fn sanitize_name_trims_leading_trailing_hyphens() {
792 assert_eq!(sanitize_name("_my_server_"), "my-server");
793 }
794
795 #[test]
796 fn sanitize_name_preserves_alphanumeric() {
797 assert_eq!(sanitize_name("server123"), "server123");
798 }
799
800 #[test]
801 fn sanitize_name_empty_input() {
802 assert_eq!(sanitize_name(""), "");
803 }
804
805 // === command validation tests ===
806
807 #[test]
808 fn shell_wrappers_and_unlisted_commands_are_refused() {
809 for (cmd, reason) in [
810 ("bash", "Shell wrapper"),
811 ("sh", "Shell wrapper"),
812 ("/bin/zsh", "Shell wrapper"),
813 ("powershell", "Shell wrapper"),
814 ("PowerShell.exe", "Shell wrapper"),
815 ("curl", "not in the allowed list"),
816 ] {
817 let err =
818 super::validate_runtime_command(cmd).expect_err(&format!("{cmd} must be refused"));
819 assert!(err.to_string().contains(reason), "{cmd}: {err}");
820 }
821 // The parsed command, not the raw string, is what gets checked.
822 let parsed = parse_mcp_command("bash -c 'npx server'").expect("parses");
823 let cmd = parsed.config.command.expect("stdio command");
824 assert!(super::validate_runtime_command(&cmd).is_err());
825 }
826
827 #[test]
828 fn known_runtimes_pass_the_command_guard() {
829 for cmd in ["npx", "/usr/local/bin/node", "python3", "uvx", "cargo"] {
830 assert!(super::validate_runtime_command(cmd).is_ok(), "{cmd}");
831 }
832 }
833
834 /// These used to assert only that their own input string contained the
835 /// metacharacter — never that the guard refused it — so deleting the
836 /// defense left all four green (2026-08-04 audit). They now call the
837 /// guard.
838 #[test]
839 fn shell_metacharacters_in_args_are_refused() {
840 for bad in [
841 "--out>file",
842 "arg|cat",
843 "a;rm -rf /",
844 "a&&b",
845 "`whoami`",
846 "$HOME",
847 ] {
848 let args = vec!["server".to_string(), bad.to_string()];
849 let err = super::reject_shell_metacharacters(&args)
850 .expect_err("metacharacter must be refused: {bad}");
851 assert!(
852 err.to_string().contains("shell metacharacters"),
853 "refusal must name the reason for {bad}: {err}"
854 );
855 }
856 }
857
858 #[test]
859 fn ordinary_args_pass_the_metacharacter_guard() {
860 let args = vec![
861 "@modelcontextprotocol/server-filesystem".to_string(),
862 "/tmp/workspace".to_string(),
863 "--read-only".to_string(),
864 ];
865 assert!(super::reject_shell_metacharacters(&args).is_ok());
866 }
867
868 // === approval-gate contract ===
869
870 #[test]
871 fn start_mcp_server_declares_required_approval() {
872 // Security invariant (#3866): spawning a runtime MCP server is
873 // side-effecting (child process / network connection), so the tool
874 // spec itself must declare `ApprovalRequirement::Required`. Combined
875 // with the engine's non-bypassable gate (see engine tests), this
876 // guarantees an unapproved start is rejected before `execute` runs.
877 let pool = Arc::new(AsyncMutex::new(McpPool::new(
878 codewhale_mcp::config::McpConfig::default(),
879 )));
880 let tool = StartRuntimeMcpServer::new(pool);
881 assert_eq!(tool.name(), "start_mcp_server");
882 assert!(
883 matches!(tool.approval_requirement(), ApprovalRequirement::Required),
884 "start_mcp_server must require approval before spawning"
885 );
886 }
887
888 #[tokio::test]
889 async fn start_mcp_server_rejects_name_sanitizing_to_empty() {
890 let directory = tempfile::tempdir().unwrap();
891 let pool = Arc::new(AsyncMutex::new(McpPool::new(
892 codewhale_mcp::config::McpConfig::default(),
893 )));
894 let tool = StartRuntimeMcpServer::new(Arc::clone(&pool));
895 let context = ToolContext::new(directory.path());
896
897 for bad_name in ["___", "...", "服务"] {
898 let error = tool
899 .execute(
900 json!({
901 "server": "node nonexistent-mcp.js",
902 "name": bad_name,
903 }),
904 &context,
905 )
906 .await
907 .expect_err("name sanitizing to empty must be rejected");
908 assert!(
909 matches!(error, ToolError::InvalidInput { .. }),
910 "expected InvalidInput for {bad_name:?}, got {error:?}"
911 );
912 }
913 assert!(pool.lock().await.server_names().is_empty());
914 }
915
916 #[test]
917 fn add_runtime_server_config_rejects_empty_name() {
918 let pool = McpPool::new(codewhale_mcp::config::McpConfig::default());
919 let parsed = parse_mcp_command("node nonexistent-mcp.js").expect("parses");
920 for bad in ["", " "] {
921 let err = pool
922 .add_runtime_server_config(bad.to_string(), parsed.config.clone())
923 .expect_err("empty runtime server name must be refused");
924 assert!(err.contains("must not be empty"), "{bad:?}: {err}");
925 }
926 assert!(pool.server_names().is_empty());
927 }
928 }
929
929 lines RUST