kintsugi-intercept 0.4.0

Kintsugi interception adapters: the $PATH shim, the Claude Code hook bridge, and the kintsugi-exec MCP server. All normalize to one ProposedCommand.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! The `kintsugi-exec` MCP server.
//!
//! Tool-calling agents (Cursor CLI, Codex CLI, Qwen Code, Gemini CLI, and any
//! custom MCP client) that speak the Model Context Protocol can call the
//! `kintsugi-exec` tool to run a shell command *through*
//! Kintsugi instead of shelling out raw. Each call is normalized to a
//! [`ProposedCommand`], sent to the daemon, and — on allow — executed, with the
//! command's output returned to the agent. Every call is recorded. An allowed
//! command that fetches remote content (`curl`/`wget` GET, `git clone`) is also
//! observed as a provenance taint source, exactly like the hook path; the
//! fetched output itself is returned to the agent and never stored (spine #6).
//!
//! Transport: newline-delimited JSON-RPC 2.0 over stdio (the MCP stdio
//! transport). Implemented by hand to avoid pulling an MCP framework dependency.

use std::path::{Path, PathBuf};
use std::process::Command;

use kintsugi_core::{shell, Decision, ObservedIngest, ProposedCommand};
use kintsugi_daemon::Client;
use serde_json::{json, Value};

use crate::observe;

/// Default protocol version advertised when the client doesn't pin one.
const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05";
/// Tool name agents call.
pub const TOOL_NAME: &str = "kintsugi-exec";

/// Handle one JSON-RPC message line. Returns the response line, or `None` for
/// notifications (which get no reply).
pub fn handle_message(line: &str) -> Option<String> {
    let req: Value = match serde_json::from_str(line) {
        Ok(v) => v,
        Err(e) => {
            return Some(error_response(
                Value::Null,
                -32700,
                &format!("parse error: {e}"),
            ));
        }
    };

    let id = req.get("id").cloned();
    let method = req.get("method").and_then(Value::as_str).unwrap_or("");

    // Notifications (no id) are acknowledged silently (`?` yields None).
    let id = id?;

    match method {
        "initialize" => Some(initialize_response(id, &req)),
        "tools/list" => Some(tools_list_response(id)),
        "tools/call" => Some(tools_call_response(id, &req)),
        "ping" => Some(result_response(id, json!({}))),
        other => Some(error_response(
            id,
            -32601,
            &format!("method not found: {other}"),
        )),
    }
}

fn initialize_response(id: Value, req: &Value) -> String {
    let protocol = req
        .get("params")
        .and_then(|p| p.get("protocolVersion"))
        .and_then(Value::as_str)
        .unwrap_or(DEFAULT_PROTOCOL_VERSION)
        .to_string();

    result_response(
        id,
        json!({
            "protocolVersion": protocol,
            "capabilities": { "tools": {} },
            "serverInfo": { "name": "kintsugi-exec", "version": crate::VERSION },
            "instructions": "Run shell commands via the kintsugi-exec tool so Kintsugi can guard and record them."
        }),
    )
}

fn tools_list_response(id: Value) -> String {
    result_response(
        id,
        json!({
            "tools": [{
                "name": TOOL_NAME,
                "description": "Run a shell command guarded and recorded by Kintsugi. \
                    Use this instead of shelling out directly so dangerous commands \
                    are held and everything is logged to the tamper-evident audit log.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "command": { "type": "string", "description": "The shell command to run." },
                        "cwd": { "type": "string", "description": "Working directory (optional)." },
                        "agent": { "type": "string", "description": "Calling agent name, e.g. 'qwen' or 'codex' (optional)." },
                        "session": { "type": "string", "description": "Session id for grouping in the timeline (optional)." }
                    },
                    "required": ["command"]
                }
            }]
        }),
    )
}

fn tools_call_response(id: Value, req: &Value) -> String {
    let params = req.get("params").cloned().unwrap_or(Value::Null);
    let name = params.get("name").and_then(Value::as_str).unwrap_or("");
    if name != TOOL_NAME {
        return error_response(id, -32602, &format!("unknown tool: {name}"));
    }
    let args = params.get("arguments").cloned().unwrap_or(json!({}));
    let command = match args.get("command").and_then(Value::as_str) {
        Some(c) if !c.trim().is_empty() => c.to_string(),
        _ => return error_response(id, -32602, "missing required argument: command"),
    };
    let agent = args
        .get("agent")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .unwrap_or("mcp")
        .to_string();
    let cwd = args
        .get("cwd")
        .and_then(Value::as_str)
        .map(PathBuf::from)
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
    // One session per server process (a client connection), overridable per call.
    let session = args
        .get("session")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| format!("mcp-{}", std::process::id()));

    let outcome = exec_through_kintsugi(&agent, cwd, &session, &command);
    result_response(
        id,
        json!({
            "content": [{ "type": "text", "text": outcome.text }],
            "isError": outcome.is_error,
        }),
    )
}

struct ToolOutcome {
    text: String,
    is_error: bool,
}

/// The full guarded-execution path: propose → decide → (allow) run → report.
fn exec_through_kintsugi(agent: &str, cwd: PathBuf, session: &str, command: &str) -> ToolOutcome {
    let argv = shell::split(command);
    let proposed = ProposedCommand::new(agent, cwd.clone(), argv.clone(), command.to_string())
        .with_session(Some(session.to_string()));

    let id = proposed.id.to_string();
    let decision = match Client::send(&proposed) {
        // A held command waits (bounded) for a human to approve/deny so the agent
        // can proceed in the same call. See `approval_timeout`.
        Ok(verdict) if verdict.decision == Decision::Hold => wait_for_approval(&id),
        Ok(verdict) => verdict.decision,
        Err(e) => {
            // Daemon down: locally classify so a catastrophic command is still
            // refused (fail-closed for the hard floor), even though it can't be
            // recorded. Non-catastrophic honors the fail-open default.
            if kintsugi_core::classify(&proposed).class == kintsugi_core::Class::Catastrophic {
                return ToolOutcome {
                    text: format!(
                        "Kintsugi daemon unreachable; catastrophic command refused (fail-closed): {e}"
                    ),
                    is_error: true,
                };
            }
            if fail_closed() {
                return ToolOutcome {
                    text: format!(
                        "Kintsugi daemon unreachable; refusing to run (fail-closed): {e}"
                    ),
                    is_error: true,
                };
            }
            // Fail-open: run unguarded but say so.
            eprintln!("kintsugi-mcp: warning: daemon unreachable; running unguarded: {e}");
            Decision::Allow
        }
    };

    let short = &id[..id.len().min(8)];
    match decision {
        Decision::Allow => {
            let outcome = run_command(&cwd, command);
            // Ingest parity with the hook path: an ALLOWED command that fetches
            // remote content taints the session for FUTURE commands. Emitted
            // after the exec and before the output is returned, so the label is
            // in place before the agent can act on the fetched bytes — while the
            // fetch itself was still judged against prior taint state.
            observe_shell_ingest(agent, &argv, session, &cwd);
            outcome
        }
        Decision::Deny => ToolOutcome {
            text: format!("Kintsugi blocked this command: {command}"),
            is_error: true,
        },
        Decision::Hold => ToolOutcome {
            text: format!(
                "Kintsugi is holding this command for human approval (id {short}). It was not run. \
                 A human can approve it with `kintsugi approve {short}` (then re-run), or you can \
                 proceed with a different approach."
            ),
            is_error: true,
        },
    }
}

/// How long the MCP tool waits for a human to resolve a held command, in seconds.
/// `0` (default) means do not wait — return "pending" immediately. Set
/// `KINTSUGI_APPROVAL_TIMEOUT` to enable in-band wait-for-approval.
fn approval_timeout() -> std::time::Duration {
    let secs = std::env::var("KINTSUGI_APPROVAL_TIMEOUT")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(0);
    std::time::Duration::from_secs(secs)
}

/// Observe an ALLOWED shell command that ingests remote content (`curl`/`wget`
/// GET, `git clone`) — the MCP twin of the hook path's `observe_shell_ingest`
/// (`crate::hook`). Same contract:
///
/// - **Identifier only (spine #6).** The source id is the URL / remote taken
///   from the command itself; the fetched stdout/stderr is returned to the
///   calling agent and never stored or logged anywhere. The daemon redacts the
///   id at its single ingest boundary (`Daemon::apply_taint`).
/// - **Observation never blocks.** Best-effort and silent: an unreachable
///   daemon or an IPC error must never change the tool result.
/// - **Allow only.** A denied or held command did not fetch anything, so it
///   labels nothing.
fn observe_shell_ingest(agent: &str, argv: &[String], session: &str, cwd: &Path) {
    let Some(src) = observe::classify_shell_ingest(argv) else {
        return;
    };
    let observed = ObservedIngest::now(src.kind, src.id, agent, session, cwd);
    let _ = Client::ingest(&observed);
}

/// Poll the daemon until a held command is approved/denied, the deadline passes,
/// or it leaves the queue. Returns the resulting decision (`Hold` = still pending).
fn wait_for_approval(id: &str) -> Decision {
    let deadline = std::time::Instant::now() + approval_timeout();
    // Tolerate a few transient connection blips (the daemon is single-threaded and
    // a concurrent connect can momentarily fail), but give up fast if the daemon
    // is actually gone rather than busy-polling a dead socket for the whole timeout.
    let mut consecutive_errors = 0u32;
    loop {
        match Client::pending_status(id) {
            Ok(s) if s == "approved" => return Decision::Allow,
            Ok(s) if s == "denied" => return Decision::Deny,
            Ok(s) if s == "gone" => return Decision::Hold, // resolved/removed elsewhere
            Ok(_) => consecutive_errors = 0,               // "pending" — keep waiting
            Err(_) => {
                consecutive_errors += 1;
                if consecutive_errors >= 5 {
                    return Decision::Hold; // daemon unreachable; don't hang
                }
            }
        }
        if std::time::Instant::now() >= deadline {
            return Decision::Hold;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
}

/// Run the command in a shell, capturing output.
fn run_command(cwd: &PathBuf, command: &str) -> ToolOutcome {
    #[cfg(unix)]
    let mut cmd = {
        let mut c = Command::new("sh");
        c.arg("-c").arg(command);
        c
    };
    #[cfg(not(unix))]
    let mut cmd = {
        let mut c = Command::new("cmd");
        c.arg("/C").arg(command);
        c
    };
    cmd.current_dir(cwd);

    match cmd.output() {
        Ok(out) => {
            let code = out.status.code().unwrap_or(-1);
            let stdout = String::from_utf8_lossy(&out.stdout);
            let stderr = String::from_utf8_lossy(&out.stderr);
            let mut text = format!("exit code: {code}\n");
            if !stdout.is_empty() {
                text.push_str("stdout:\n");
                text.push_str(&stdout);
                if !stdout.ends_with('\n') {
                    text.push('\n');
                }
            }
            if !stderr.is_empty() {
                text.push_str("stderr:\n");
                text.push_str(&stderr);
            }
            ToolOutcome {
                text: text.trim_end().to_string(),
                is_error: !out.status.success(),
            }
        }
        Err(e) => ToolOutcome {
            text: format!("failed to run command: {e}"),
            is_error: true,
        },
    }
}

/// True if the admin-set fail-closed marker is present (an agent can't unset a
/// root-owned marker) OR the `KINTSUGI_FAIL_CLOSED` env var opts in. The marker
/// wins, so `KINTSUGI_FAIL_CLOSED=0` can't re-open the gate.
fn fail_closed() -> bool {
    kintsugi_daemon::is_fail_closed_marked()
        || matches!(
            std::env::var("KINTSUGI_FAIL_CLOSED").ok().as_deref(),
            Some("1") | Some("true") | Some("yes")
        )
}

fn result_response(id: Value, result: Value) -> String {
    json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string()
}

fn error_response(id: Value, code: i64, message: &str) -> String {
    json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }).to_string()
}

/// Run the MCP server: read JSON-RPC lines from stdin, write responses to stdout.
pub fn run() -> anyhow::Result<()> {
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    run_io(stdin.lock(), stdout.lock())
}

/// The server loop over arbitrary reader/writer (testable).
pub fn run_io<R: std::io::BufRead, W: std::io::Write>(
    reader: R,
    mut writer: W,
) -> anyhow::Result<()> {
    for line in reader.lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        if let Some(resp) = handle_message(&line) {
            writeln!(writer, "{resp}")?;
            writer.flush()?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn initialize_reports_server_info() {
        let req = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#;
        let resp: Value = serde_json::from_str(&handle_message(req).unwrap()).unwrap();
        assert_eq!(resp["id"], 1);
        assert_eq!(resp["result"]["serverInfo"]["name"], "kintsugi-exec");
        // Echoes the client's requested protocol version.
        assert_eq!(resp["result"]["protocolVersion"], "2025-06-18");
    }

    #[test]
    fn tools_list_includes_kintsugi_exec() {
        let req = r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#;
        let resp: Value = serde_json::from_str(&handle_message(req).unwrap()).unwrap();
        let tools = resp["result"]["tools"].as_array().unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0]["name"], TOOL_NAME);
        assert!(tools[0]["inputSchema"]["properties"]["command"].is_object());
    }

    #[test]
    fn notification_gets_no_response() {
        let note = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
        assert!(handle_message(note).is_none());
    }

    #[test]
    fn unknown_method_is_an_error() {
        let req = r#"{"jsonrpc":"2.0","id":9,"method":"does/not/exist"}"#;
        let resp: Value = serde_json::from_str(&handle_message(req).unwrap()).unwrap();
        assert_eq!(resp["error"]["code"], -32601);
    }

    #[test]
    fn call_without_command_is_an_error() {
        let req = r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"kintsugi-exec","arguments":{}}}"#;
        let resp: Value = serde_json::from_str(&handle_message(req).unwrap()).unwrap();
        assert_eq!(resp["error"]["code"], -32602);
    }

    #[test]
    fn run_io_responds_to_requests_and_skips_notifications() {
        let input = concat!(
            "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\"}\n",
            "\n",
            "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
            "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}\n",
        );
        let mut out = Vec::new();
        run_io(std::io::Cursor::new(input), &mut out).unwrap();
        let text = String::from_utf8(out).unwrap();
        // Two responses (initialize, tools/list); the notification yields none.
        assert_eq!(text.lines().count(), 2);
        assert!(text.contains("serverInfo"));
        assert!(text.contains(TOOL_NAME));
    }
}