Skip to main content

safe_chains/mcp/
mod.rs

1//! `safe-chains mcp`: the CLI's checks and config changes as MCP tools, for an agent that calls
2//! tools rather than running commands. Hand-rolled newline-delimited JSON-RPC 2.0 over stdio, one
3//! request at a time.
4//!
5//! Every tool runs the `safe-chains` binary itself (`Runner`). That keeps the two surfaces equal by
6//! construction, and it is also necessary: the classifier loads the user's rules once per process,
7//! so a long-lived server answering in-process would go on using rules it had just changed.
8//!
9//! The editing tools never approve themselves. They are annotated destructive, so a client that
10//! reads annotations asks before each call, and the server refuses them outright when it can see
11//! that the client is set to run them without asking (`client_approval`).
12
13mod args;
14pub mod client_approval;
15mod tools;
16
17use std::io::{BufRead, Write};
18
19use serde_json::{Value, json};
20
21pub use tools::{Runner, Spawn, manifest};
22
23/// The newest protocol revision this server has been checked against. A client that asks for
24/// another gets its own echoed back, as the house servers do.
25pub const PROTOCOL_VERSION: &str = "2025-11-25";
26
27/// What the client is told about the server, once, at `initialize`. Under 2,000 characters, with
28/// what it is and where to start in the first 500 (`tests/mcp_rules.rs` holds both).
29pub const INSTRUCTIONS: &str = "safe-chains decides which shell commands an AI agent may run without \
30asking a person. This server checks commands and changes the user's rules for that, kept in \
31~/.config/safe-chains.toml. Start with check_command: it says whether a command would run without \
32asking and, if not, what would change that.
33
34check_command ends with one of three fixes. Add an entry, for a command safe-chains has no entry \
35for (add_command_entry). Grant a path, when a known command reached a folder outside the approved \
36places (grant_path). Or nothing: a built-in rule refused an option or a protected path, no rule can \
37change that, and a person approves the command each time it runs.
38
39The three editing tools (add_command_entry, grant_path, remove_rule) change what runs without a \
40person's approval. Use them only when the user asked for that change, never to get your own \
41command approved. A client should ask the user before every call to them, and the server refuses \
42them when it can see the client approves them automatically. They never replace a built-in \
43command, and never grant a credential store or the settings files safe-chains and coding agents \
44read.
45
46Each change applies from the next command on. list_rules shows every rule and the file it came \
47from.";
48
49/// Serve until stdin closes.
50pub fn serve(runner: &dyn Runner) -> std::io::Result<()> {
51    let stdin = std::io::stdin();
52    let stdout = std::io::stdout();
53    let mut out = stdout.lock();
54    for line in stdin.lock().lines() {
55        let line = line?;
56        if let Some(reply) = handle_line(runner, &line) {
57            writeln!(out, "{reply}")?;
58            out.flush()?;
59        }
60    }
61    Ok(())
62}
63
64/// One message in, at most one reply out. A notification (no `id`) gets none.
65pub fn handle_line(runner: &dyn Runner, line: &str) -> Option<String> {
66    if line.trim().is_empty() {
67        return None;
68    }
69    let message: Value = match serde_json::from_str(line) {
70        Ok(v) => v,
71        Err(e) => return Some(error(Value::Null, -32700, &format!("Parse error: {e}"))),
72    };
73    let Some(object) = message.as_object() else {
74        return Some(error(Value::Null, -32600, "Invalid request: expected a JSON object"));
75    };
76    let id = object.get("id").cloned()?;
77    let method = object.get("method").and_then(Value::as_str).unwrap_or_default();
78    let params = object.get("params").cloned().unwrap_or(Value::Null);
79    let mut result = match method {
80        "initialize" => initialize(&params),
81        "server/discover" => {
82            json!({ "supportedVersions": SUPPORTED, "capabilities": { "tools": {} }, "serverInfo": server_info(), "instructions": INSTRUCTIONS })
83        }
84        "ping" => json!({}),
85        "tools/list" => json!({ "tools": tools::listing(), "ttlMs": 3_600_000, "cacheScope": "private" }),
86        "tools/call" => tools::call(runner, &params),
87        other => return Some(error(id, -32601, &format!("Method not found: {other}"))),
88    };
89    // Revision 2026-07-28 requires `resultType` on every result, and Claude Code shows no tools at
90    // all from a server whose `tools/list` lacks it. Earlier revisions ignore the field.
91    result["resultType"] = json!("complete");
92    Some(json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string())
93}
94
95fn initialize(params: &Value) -> Value {
96    let asked = params.get("protocolVersion").and_then(Value::as_str);
97    let version = asked.filter(|v| SUPPORTED.contains(v)).unwrap_or(PROTOCOL_VERSION);
98    json!({
99        "protocolVersion": version,
100        "capabilities": { "tools": {} },
101        "serverInfo": server_info(),
102        "instructions": INSTRUCTIONS,
103    })
104}
105
106fn error(id: Value, code: i64, message: &str) -> String {
107    json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }).to_string()
108}
109
110#[cfg(test)]
111mod tests;
112
113/// The revisions this server answers to, for `server/discover`.
114const SUPPORTED: &[&str] = &["2025-06-18", "2025-11-25", "2026-07-28"];
115
116fn server_info() -> Value {
117    json!({ "name": "safe-chains", "version": env!("CARGO_PKG_VERSION") })
118}