From c4808e4715734c5b58aa26f1708e35c4f2a6d540 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Mon, 2 Nov 2026 13:57:48 +0000 Subject: [PATCH] MCP: clean up empty scratch folders on shutdown (#7836) (#7929) * claim: #7836 * fix(mcp): remove empty scratch directories on command exit --- apps/solidcraft-cli/src/main.rs | 6 +- apps/solidcraft-cli/tests/mcp_connect.rs | 107 +++++++++++++++++++++++ crates/mcp/src/lib.rs | 44 ++++++---- docs/mcp.md | 3 + 4 files changed, 143 insertions(+), 17 deletions(-) diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index b210b63a9..0473010ed 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -172,7 +172,11 @@ fn main() -> ExitCode { Some("oracle") => oracle::run(&args[1..]), Some("fuzz") => fuzz::run(&args[1..]), Some("fuzz-one") => fuzz::one(&args[1..]), - Some("mcp") => cmd_mcp(&args[1..]), + Some("mcp") => { + let result = cmd_mcp(&args[1..]); + solidcraft_mcp::cleanup_scratch_dir(); + result + } Some("crashes") => crashes::run(&args[1..]), Some("icon") => cmd_icon(&args[1..]), Some("licences" | "licenses") => { diff --git a/apps/solidcraft-cli/tests/mcp_connect.rs b/apps/solidcraft-cli/tests/mcp_connect.rs index 1475f40d7..26e1ffb16 100644 --- a/apps/solidcraft-cli/tests/mcp_connect.rs +++ b/apps/solidcraft-cli/tests/mcp_connect.rs @@ -263,3 +263,110 @@ mod setup { assert!(json_of(&pkg.join("claude_desktop_config.json"))["mcpServers"]["solidcraft"].is_object()); } } + +/// Scratch files belong to the CLI process; exercise real startup, requests and shutdown. +mod scratch_cleanup { + use super::*; + use std::path::{Path, PathBuf}; + + fn command(case: &str) -> (PathBuf, Command) { + let dir = std::env::temp_dir().join(format!("solidcraft-mcp-lifecycle-{case}-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli")); + command + .args(["mcp", "--headless"]) + .env("TMPDIR", &dir) + .env("TMP", &dir) + .env("TEMP", &dir) + .env("SOLIDCRAFT_RECOVERY_DIR", dir.join("recovery")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + (dir, command) + } + + fn scratch_folders(dir: &Path) -> Vec { + std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.file_name().unwrap().to_string_lossy().starts_with("solidcraft-mcp-")) + .collect() + } + + fn initialize() -> Value { + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}) + } + + fn run(mut command: Command, request: Value) -> std::process::Output { + let mut child = command.spawn().unwrap(); + writeln!(child.stdin.take().unwrap(), "{request}").unwrap(); + child.wait_with_output().unwrap() + } + + #[test] + fn eof_removes_only_the_process_scratch_folder() { + let (dir, command) = command("eof"); + let unrelated = dir.join("solidcraft-mcp-unrelated"); + std::fs::create_dir(&unrelated).unwrap(); + let out = run(command, initialize()); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let reply: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert!(reply.get("result").is_some(), "{reply}"); + assert_eq!(scratch_folders(&dir), vec![unrelated]); + assert!(dir.join("recovery").is_dir(), "cleanup must leave the recovery folder alone"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn startup_error_removes_the_process_scratch_folder() { + let (dir, mut command) = command("startup-error"); + let out = command.args(["--param-check", "invalid"]).stdin(Stdio::null()).output().unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success()); + assert!(stderr.contains("--param-check wants off, warn or strict"), "{stderr}"); + assert!(scratch_folders(&dir).is_empty(), "startup error left a scratch folder in {dir:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn shutdown_preserves_nonempty_scratch_folder() { + let (dir, mut command) = command("nonempty"); + let mut child = command.spawn().unwrap(); + let mut input = child.stdin.take().unwrap(); + writeln!(input, "{}", initialize()).unwrap(); + let mut reply = String::new(); + BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap(); + let reply: Value = serde_json::from_str(&reply).unwrap(); + assert!(reply.get("result").is_some(), "{reply}"); + let scratch = scratch_folders(&dir); + assert_eq!(scratch.len(), 1); + let saved = scratch[0].join("keep.txt"); + std::fs::write(&saved, "saved output").unwrap(); + drop(input); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(std::fs::read_to_string(saved).unwrap(), "saved output"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn failed_screenshot_scratch_folder_is_removed_without_a_path_scope() { + let (dir, mut command) = command("screenshot"); + command.arg("--allow-any-path"); + // A headless server cannot capture a window. The request still allocates a scratch + // path before the backend refuses it, without relying on a GPU or installed renderer. + let out = run( + command, + json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "screenshot", "arguments": {"source": "window"}}, + }), + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let reply: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(reply["result"]["isError"], true, "{reply}"); + assert!(reply["result"]["content"][0]["text"].as_str().unwrap().contains("the window gave no picture"), "{reply}"); + assert!(scratch_folders(&dir).is_empty(), "failed screenshot left a scratch folder in {dir:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index f3e3c5407..f416daa29 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -48,25 +48,37 @@ pub fn agent_scope_with(recovery: Option, allowed: impl IntoIterator> = std::sync::OnceLock::new(); + /// This server's own folder for screenshots it reads back and deletes (`screenshot` without a -/// `path`): a new `/solidcraft-mcp--` made on first use (never one that was there -/// already, which could be someone else's), private to the user on Unix. `` is spelled with -/// long names (`vfs::temp_dir`), since the scope refuses short (8.3) ones. +/// `path`): a new `/solidcraft-mcp--` made when the path scope is built, or on the +/// first screenshot without a scope. Never reuse an existing folder, which could be someone +/// else's. It is private to the user on Unix. `` is spelled with long names (`vfs::temp_dir`), +/// since the scope refuses short (8.3) ones. pub fn scratch_dir() -> Option { - static DIR: std::sync::OnceLock> = std::sync::OnceLock::new(); - DIR.get_or_init(|| { - let b = std::fs::DirBuilder::new(); - #[cfg(unix)] - let mut b = b; - #[cfg(unix)] - std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); - let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0); - (0..16u32).find_map(|i| { - let d = vfs::temp_dir().join(format!("solidcraft-mcp-{}-{:x}", std::process::id(), seed.wrapping_add(i))); - b.create(&d).ok().map(|()| d) + SCRATCH_DIR + .get_or_init(|| { + let b = std::fs::DirBuilder::new(); + #[cfg(unix)] + let mut b = b; + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); + let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0); + (0..16u32).find_map(|i| { + let d = vfs::temp_dir().join(format!("solidcraft-mcp-{}-{:x}", std::process::id(), seed.wrapping_add(i))); + b.create(&d).ok().map(|()| d) + }) }) - }) - .clone() + .clone() +} + +/// Best-effort cleanup at process shutdown, after all MCP activity has stopped. Only remove +/// this process's empty scratch folder: saved files, other processes' folders and the recovery +/// folder must survive. Looking up the cached path never creates a folder just to clean it up. +pub fn cleanup_scratch_dir() { + if let Some(Some(dir)) = SCRATCH_DIR.get() { + let _ = std::fs::remove_dir(dir); + } } #[cfg(test)] diff --git a/docs/mcp.md b/docs/mcp.md index a12f8f442..c8e093f7d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -107,6 +107,9 @@ Tool calls read, write and delete files only inside the server's folders: - every `--allow-path DIR` (repeat it for more). A folder named here is reached in full, hidden files included. +The CLI removes its own scratch folder if it is empty when the MCP command returns, including +after a startup error. A nonempty scratch folder is kept, so saved files are not deleted. + The working folder the server was started in does not count by itself, so `~/.ssh`, `~/.aws`, `~/.bashrc` and other dotfiles are never in reach by default. stderr lists the folders at start-up and says when the `--in` design's folder was left out; `--allow-path` adds it back.