1use std::path::{Path, PathBuf};
4
5use serde_json::{Map, Value, json};
6
7use super::args::{self, NOTHING_DONE};
8use super::client_approval;
9
10const MAX_RESULT: usize = 8_000;
12
13pub trait Runner {
15 fn run(&self, args: &[String], cwd: &Path) -> (Option<i32>, String);
18 fn home(&self) -> PathBuf;
19 fn cwd(&self) -> PathBuf;
20}
21
22pub struct Spawn;
24
25impl Runner for Spawn {
26 fn run(&self, args: &[String], cwd: &Path) -> (Option<i32>, String) {
27 let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("safe-chains"));
28 match std::process::Command::new(exe)
29 .args(args)
30 .current_dir(cwd)
31 .env("SAFE_CHAINS_SURFACE", "mcp")
32 .output()
33 {
34 Ok(out) => {
35 let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
36 text.push_str(&String::from_utf8_lossy(&out.stderr));
37 (out.status.code(), text.trim_end().to_string())
38 }
39 Err(e) => (None, format!("safe-chains could not start itself to answer: {e}. {NOTHING_DONE}")),
40 }
41 }
42
43 fn home(&self) -> PathBuf {
44 crate::process_home::var_os().map(PathBuf::from).unwrap_or_default()
45 }
46
47 fn cwd(&self) -> PathBuf {
48 std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"))
49 }
50}
51
52struct Tool {
53 name: &'static str,
54 description: &'static str,
55 schema: Value,
56 edits: bool,
57}
58
59fn object(properties: Value, required: &[&str]) -> Value {
60 let mut schema = json!({ "type": "object", "properties": properties, "additionalProperties": false });
61 if !required.is_empty() {
62 schema["required"] = json!(required);
63 }
64 schema
65}
66
67fn registry() -> Vec<Tool> {
68 vec![
69 Tool {
70 name: "check_command",
71 description: "Check whether safe-chains would let a shell command run without asking a person, and if not, \
72 what would change that. Start here. Pass the command exactly as it would run, and cwd, the \
73 directory it would run in (default: the server's own). The answer ends with a Fix line: add an \
74 entry (add_command_entry), grant a path (grant_path), or nothing, because a built-in rule \
75 refused it. Changes nothing. Example: {\"command\": \"mytool sync --dry-run\", \"cwd\": \"~/work/app\"}",
76 schema: object(
77 json!({
78 "command": { "type": "string", "description": "The shell command, exactly as it would run." },
79 "cwd": { "type": "string", "description": "The directory it would run in. Default: the server's own." }
80 }),
81 &["command"],
82 ),
83 edits: false,
84 },
85 Tool {
86 name: "list_rules",
87 description: "List every rule safe-chains reads from a file, with the file it came from. That covers entries and grants \
88 in ~/.config/safe-chains.toml, a project's .safe-chains.toml, and rules borrowed from Claude \
89 Code's settings. Use it to find a rule's name or path. It changes nothing: to take a rule out, call remove_rule.",
90 schema: object(json!({}), &[]),
91 edits: false,
92 },
93 Tool {
94 name: "add_command_entry",
95 description: "Add an entry so safe-chains approves a command it has no entry for. The entry goes in \
96 ~/.config/safe-chains.toml and covers the command used the way it is in command: the same \
97 subcommand and flags, and up to as many other arguments. Use it only when the user asked for \
98 this, after check_command says an entry is the fix. It changes what runs without asking, so \
99 the client must ask the user first. It refuses \
100 a built-in command and a command that runs an AI agent. level is inert, safe-read or \
101 safe-write (default safe-write).",
102 schema: object(
103 json!({
104 "command": { "type": "string", "description": "The command as it should be approved, e.g. \"mytool sync --dry-run\"." },
105 "level": { "type": "string", "enum": ["inert", "safe-read", "safe-write"], "default": "safe-write",
106 "description": "inert: reads and changes nothing. safe-read: reads files in the project. safe-write: also writes them." }
107 }),
108 &["command"],
109 ),
110 edits: true,
111 },
112 Tool {
113 name: "grant_path",
114 description: "Let commands read or write a folder outside the places safe-chains approves by default. It \
115 adds a grant to ~/.config/safe-chains.toml. Use it only when the user asked for this, after \
116 check_command says a grant is the fix. access is read, write or read_write. It refuses \
117 credential stores, the settings safe-chains and coding agents read, shell startup files, \
118 folders on PATH, system login files, devices, / and the home folder itself. It changes what \
119 runs without asking, so the client must ask the user first. Example: {\"path\": \"~/notes\", \
120 \"access\": \"read\"}",
121 schema: object(
122 json!({
123 "path": { "type": "string", "description": "The folder or file: a full path, or one starting with ~/." },
124 "access": { "type": "string", "enum": ["read", "write", "read_write"], "description": "What commands may do there." }
125 }),
126 &["path", "access"],
127 ),
128 edits: true,
129 },
130 Tool {
131 name: "remove_rule",
132 description: "Remove a command entry or a grant from ~/.config/safe-chains.toml. kind is command (name is the \
133 command's name) or grant (name is the grant's path). list_rules shows both. Removing can also \
134 widen what runs, when the entry removed was refusing a command, so the client must ask the user \
135 first.",
136 schema: object(
137 json!({
138 "kind": { "type": "string", "enum": ["command", "grant"], "description": "command or grant." },
139 "name": { "type": "string", "description": "The command's name, or the grant's path." }
140 }),
141 &["kind", "name"],
142 ),
143 edits: true,
144 },
145 ]
146}
147
148pub fn listing() -> Vec<Value> {
150 registry()
151 .into_iter()
152 .map(|t| {
153 json!({
154 "name": t.name,
155 "description": t.description,
156 "inputSchema": t.schema,
157 "annotations": {
158 "readOnlyHint": !t.edits,
159 "destructiveHint": t.edits,
160 "idempotentHint": !t.edits,
161 "openWorldHint": false,
162 },
163 })
164 })
165 .collect()
166}
167
168pub fn call(runner: &dyn Runner, params: &Value) -> Value {
170 let name = params.get("name").and_then(Value::as_str).unwrap_or_default();
171 let tools = registry();
172 let outcome = match tools.iter().find(|t| t.name == name) {
173 Some(tool) => {
174 args::check(tool.name, &tool.schema, params.get("arguments").unwrap_or(&Value::Null)).and_then(|args| run(runner, tool, &args))
175 }
176 None => {
177 let names: Vec<&str> = tools.iter().map(|t| t.name).collect();
178 Err(format!("There is no tool {name:?}. The tools are: {}. {NOTHING_DONE}", names.join(", ")))
179 }
180 };
181 let (text, is_error) = match outcome {
182 Ok(text) => (text, false),
183 Err(text) => (text, true),
184 };
185 json!({ "content": [{ "type": "text", "text": capped(&text) }], "isError": is_error })
186}
187
188fn text<'a>(args: &'a Map<String, Value>, key: &str) -> &'a str {
189 args.get(key).and_then(Value::as_str).unwrap_or_default()
190}
191
192fn run(runner: &dyn Runner, tool: &Tool, args: &Map<String, Value>) -> Result<String, String> {
193 let cwd = runner.cwd();
194 if tool.edits
195 && let Some(why) = client_approval::auto_approval(&runner.home(), &cwd)
196 {
197 return Err(format!(
198 "safe-chains will not make this change from here: this client runs {} without asking anyone, because {why}. \
199 An agent could then approve its own commands. Remove that setting so the client asks first, or ask the \
200 user to run `safe-chains config` themselves. {NOTHING_DONE}",
201 tool.name
202 ));
203 }
204 let mut note = String::new();
205 let owned = |v: &[&str]| v.iter().map(|s| (*s).to_string()).collect::<Vec<String>>();
206 let (argv, dir) = match tool.name {
207 "check_command" => {
208 let dir = match args.get("cwd").and_then(Value::as_str).map(|d| expand_home(d, &runner.home())) {
212 Some(dir) if dir.is_dir() => dir,
213 Some(missing) => {
214 note = format!(
215 "(cwd {} does not exist, so this was checked from {} instead. That matters only for relative \
216 paths in the command.)\n",
217 missing.display(),
218 cwd.display()
219 );
220 cwd
221 }
222 None => cwd,
223 };
224 let shown = dir.to_string_lossy().into_owned();
225 (owned(&["--explain", "--cwd", &shown, "--", text(args, "command")]), dir)
226 }
227 "list_rules" => (owned(&["config", "list"]), cwd),
228 "add_command_entry" => {
229 let level = args.get("level").and_then(Value::as_str).unwrap_or("safe-write");
230 (owned(&["config", "add", "--level", level, "--", text(args, "command")]), cwd)
231 }
232 "grant_path" => {
233 let flags: &[&str] = match text(args, "access") {
234 "read" => &["--read"],
235 "write" => &["--write"],
236 _ => &["--read", "--write"],
237 };
238 let mut argv = owned(&["config", "grant"]);
239 argv.extend(owned(flags));
240 argv.extend(owned(&["--", text(args, "path")]));
241 (argv, cwd)
242 }
243 _ => (owned(&["config", "remove", text(args, "kind"), "--", text(args, "name")]), cwd),
244 };
245 let (code, out) = runner.run(&argv, &dir);
246 let answered = code == Some(0) || tool.name == "check_command" && code == Some(1);
249 if answered {
250 Ok(format!("{note}{out}"))
251 } else {
252 Err(if out.is_empty() { format!("safe-chains stopped without an answer. {NOTHING_DONE}") } else { out })
253 }
254}
255
256fn expand_home(dir: &str, home: &Path) -> PathBuf {
257 match dir.strip_prefix("~") {
258 Some(rest) if rest.is_empty() || rest.starts_with('/') => home.join(rest.trim_start_matches('/')),
259 _ => PathBuf::from(dir),
260 }
261}
262
263fn capped(text: &str) -> String {
264 if text.len() <= MAX_RESULT {
265 return text.to_string();
266 }
267 let mut cut = MAX_RESULT;
268 while !text.is_char_boundary(cut) {
269 cut -= 1;
270 }
271 let kept = &text[..cut];
272 let kept = &kept[..kept.rfind('\n').unwrap_or(kept.len())];
273 let more = text[kept.len()..].lines().filter(|l| !l.trim().is_empty()).count();
274 format!("{kept}\n… {more} more lines not shown.")
275}
276
277pub fn manifest() -> String {
279 let mut out = String::from(
280 "# Every MCP tool safe-chains lists, with what it can do. Written by the test\n\
281 # `the_tool_manifest_is_what_the_server_lists` (SAFE_CHAINS_WRITE_MCP_MANIFEST=1 rewrites it).\n",
282 );
283 for t in registry() {
284 out.push_str(&format!(
285 "\n[{}]\nread_only = {}\ndestructive = {}\nspends = false\nnetwork = false\nsends = false\n",
286 t.name, !t.edits, t.edits
287 ));
288 }
289 out
290}