tsafe-mcp 0.1.0

First-party MCP server for tsafe — exposes action-shaped tools to MCP-aware hosts over stdio JSON-RPC.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! `tsafe_run` tool — execute a command with explicitly-allowed keys injected
//! as environment variables.
//!
//! Design §4.3 + §7:
//! - `allowed_keys` MUST be literal key names; globs at request time are
//!   rejected with `-32602 InvalidParams` to prevent widening.
//! - Each key in `allowed_keys` MUST also be in the bound startup scope —
//!   out-of-scope keys return `-32003 KeyOutOfScope`.
//! - Secret VALUES never appear in the response — only `injected_keys`.
//! - Timeout is enforced via a watchdog thread + `wait_timeout` pattern.

use std::collections::HashMap;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};

use serde_json::{json, Value};

use crate::audit::{audit_call, CallStatus};
use crate::backend;
use crate::errors::{McpError, McpErrorKind};
use crate::session::{looks_like_glob, Session};

const DEFAULT_TIMEOUT_SECS: u64 = 60;
const MIN_TIMEOUT_SECS: u64 = 1;
const MAX_TIMEOUT_SECS: u64 = 600;

#[derive(Debug)]
struct RunArgs {
    command: String,
    args: Vec<String>,
    allowed_keys: Vec<String>,
    cwd: Option<String>,
    timeout_secs: u64,
}

pub fn call(session: &Session, raw: Value) -> Result<Value, McpError> {
    let args = parse_args(&raw)?;

    // Validate scope for every requested key before we open the vault.
    for key in &args.allowed_keys {
        if looks_like_glob(key) {
            let err = McpError::new(
                McpErrorKind::InvalidParams,
                format!(
                    "allowed_keys entry '{key}' contains glob characters; only literal key names are accepted"
                ),
            );
            audit_failure(session, &args.allowed_keys, &err);
            return Err(err);
        }
        if !session.is_in_scope(key) {
            let err = McpError::new(
                McpErrorKind::KeyOutOfScope,
                format!("key '{key}' is outside the configured scope for this server"),
            )
            .with_data(json!({"key": key}));
            audit_failure(session, &args.allowed_keys, &err);
            return Err(err);
        }
    }

    // Resolve every requested key against the vault. Hold values in a
    // Zeroizing wrapper so the process strings clear on drop.
    let vault = match backend::open_vault(session) {
        Ok(v) => v,
        Err(e) => {
            audit_failure(session, &args.allowed_keys, &e);
            return Err(e);
        }
    };

    let mut secrets: HashMap<String, String> = HashMap::new();
    for key in &args.allowed_keys {
        match backend::lookup_key(&vault, key) {
            Ok(value) => {
                // value is Zeroizing<String>; clone into the env map (will
                // be dropped after spawn).
                secrets.insert(key.clone(), value.as_str().to_string());
            }
            Err(e) => {
                audit_failure(session, &args.allowed_keys, &e);
                return Err(e);
            }
        }
    }

    drop(vault);

    // Run the child.
    let started_at = Instant::now();
    let outcome = spawn_with_timeout(&args, &secrets);
    let duration_ms = started_at.elapsed().as_millis() as u64;

    // Wipe the local copy of secrets we built for env injection. Zeroizing
    // does not directly support HashMap, so wrap each value String and
    // forget the map.
    for (_, mut v) in secrets {
        use zeroize::Zeroize;
        v.zeroize();
    }

    match outcome {
        Ok(child_outcome) => {
            audit_call(
                session,
                "tsafe_run",
                None,
                args.allowed_keys.clone(),
                Some(child_outcome.exit_code),
                Some(duration_ms),
                CallStatus::Success,
                None,
            );
            Ok(json!({
                "stdout": child_outcome.stdout,
                "stderr": child_outcome.stderr,
                "exit_code": child_outcome.exit_code,
                "duration_ms": duration_ms,
                "injected_keys": args.allowed_keys,
            }))
        }
        Err(e) => {
            audit_call(
                session,
                "tsafe_run",
                None,
                args.allowed_keys.clone(),
                None,
                Some(duration_ms),
                CallStatus::Failure,
                Some(&e.message),
            );
            Err(e)
        }
    }
}

fn audit_failure(session: &Session, injected: &[String], err: &McpError) {
    audit_call(
        session,
        "tsafe_run",
        None,
        injected.to_vec(),
        None,
        None,
        CallStatus::Failure,
        Some(&err.message),
    );
}

fn parse_args(raw: &Value) -> Result<RunArgs, McpError> {
    let obj = raw
        .as_object()
        .ok_or_else(|| McpError::new(McpErrorKind::InvalidParams, "expected an object"))?;

    // Reject unknown fields per the schema's additionalProperties=false.
    for k in obj.keys() {
        if !matches!(
            k.as_str(),
            "command" | "args" | "allowed_keys" | "cwd" | "timeout_secs"
        ) {
            return Err(McpError::new(
                McpErrorKind::InvalidParams,
                format!("unknown field '{k}'"),
            ));
        }
    }

    let command = obj
        .get("command")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::new(McpErrorKind::InvalidParams, "missing 'command'"))?
        .to_string();
    if command.is_empty() {
        return Err(McpError::new(
            McpErrorKind::InvalidParams,
            "'command' must be non-empty",
        ));
    }

    let args = obj
        .get("args")
        .map(|v| -> Result<Vec<String>, McpError> {
            let arr = v.as_array().ok_or_else(|| {
                McpError::new(
                    McpErrorKind::InvalidParams,
                    "'args' must be an array of strings",
                )
            })?;
            arr.iter()
                .map(|x| {
                    x.as_str().map(str::to_string).ok_or_else(|| {
                        McpError::new(
                            McpErrorKind::InvalidParams,
                            "'args' entries must be strings",
                        )
                    })
                })
                .collect()
        })
        .transpose()?
        .unwrap_or_default();

    let allowed_keys = obj
        .get("allowed_keys")
        .ok_or_else(|| McpError::new(McpErrorKind::InvalidParams, "missing 'allowed_keys'"))?;
    let allowed_keys_arr = allowed_keys.as_array().ok_or_else(|| {
        McpError::new(
            McpErrorKind::InvalidParams,
            "'allowed_keys' must be an array",
        )
    })?;
    if allowed_keys_arr.is_empty() {
        return Err(McpError::new(
            McpErrorKind::InvalidParams,
            "'allowed_keys' must have minItems=1",
        ));
    }
    let allowed_keys: Vec<String> = allowed_keys_arr
        .iter()
        .map(|v| {
            v.as_str().map(str::to_string).ok_or_else(|| {
                McpError::new(
                    McpErrorKind::InvalidParams,
                    "'allowed_keys' entries must be strings",
                )
            })
        })
        .collect::<Result<_, _>>()?;

    let cwd = obj
        .get("cwd")
        .map(|v| {
            v.as_str()
                .map(str::to_string)
                .ok_or_else(|| McpError::new(McpErrorKind::InvalidParams, "'cwd' must be a string"))
        })
        .transpose()?;

    let timeout_secs = match obj.get("timeout_secs") {
        Some(v) => {
            let n = v.as_u64().ok_or_else(|| {
                McpError::new(
                    McpErrorKind::InvalidParams,
                    "'timeout_secs' must be a positive integer",
                )
            })?;
            if !(MIN_TIMEOUT_SECS..=MAX_TIMEOUT_SECS).contains(&n) {
                return Err(McpError::new(
                    McpErrorKind::InvalidParams,
                    format!(
                        "'timeout_secs' must be between {MIN_TIMEOUT_SECS} and {MAX_TIMEOUT_SECS}"
                    ),
                ));
            }
            n
        }
        None => DEFAULT_TIMEOUT_SECS,
    };

    Ok(RunArgs {
        command,
        args,
        allowed_keys,
        cwd,
        timeout_secs,
    })
}

#[derive(Debug)]
struct ChildOutcome {
    stdout: String,
    stderr: String,
    exit_code: i32,
}

fn spawn_with_timeout(
    args: &RunArgs,
    secrets: &HashMap<String, String>,
) -> Result<ChildOutcome, McpError> {
    let mut cmd = Command::new(&args.command);
    cmd.args(&args.args);
    cmd.stdin(Stdio::null());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    if let Some(dir) = &args.cwd {
        cmd.current_dir(dir);
    }
    for (k, v) in secrets {
        cmd.env(k, v);
    }

    let mut child = cmd.spawn().map_err(|e| {
        McpError::new(
            McpErrorKind::InternalError,
            format!("failed to spawn '{}': {e}", args.command),
        )
    })?;

    let (tx, rx) = mpsc::channel();
    let pid = child.id();

    // Watchdog thread waits for the process and signals via the channel.
    let stdout_handle = child.stdout.take();
    let stderr_handle = child.stderr.take();

    let join = thread::spawn(move || {
        use std::io::Read;
        let mut out_buf = Vec::new();
        let mut err_buf = Vec::new();
        if let Some(mut so) = stdout_handle {
            let _ = so.read_to_end(&mut out_buf);
        }
        if let Some(mut se) = stderr_handle {
            let _ = se.read_to_end(&mut err_buf);
        }
        let status = child.wait();
        let _ = tx.send((status, out_buf, err_buf));
    });

    let timeout = Duration::from_secs(args.timeout_secs);
    match rx.recv_timeout(timeout) {
        Ok((status, out_buf, err_buf)) => {
            let _ = join.join();
            let status = status.map_err(|e| {
                McpError::new(
                    McpErrorKind::InternalError,
                    format!("child wait failed: {e}"),
                )
            })?;
            Ok(ChildOutcome {
                stdout: String::from_utf8_lossy(&out_buf).into_owned(),
                stderr: String::from_utf8_lossy(&err_buf).into_owned(),
                exit_code: status.code().unwrap_or(-1),
            })
        }
        Err(_) => {
            // Timeout — best-effort kill (the child handle is owned by the
            // thread, so reach via PID on Unix; on Windows, the thread holds
            // the only owner and the child will continue. We let the OS clean
            // up on process exit; the user gets the timeout error.).
            let _ = kill_pid(pid);
            // Detach the worker thread; further i/o from it is harmless.
            drop(join);
            Err(McpError::new(
                McpErrorKind::RunTimeout,
                format!("command exceeded {}s timeout", args.timeout_secs),
            ))
        }
    }
}

#[cfg(unix)]
fn kill_pid(pid: u32) -> std::io::Result<()> {
    use std::process::Command;
    let status = Command::new("kill")
        .arg("-9")
        .arg(pid.to_string())
        .status()?;
    if status.success() {
        Ok(())
    } else {
        Err(std::io::Error::other("kill returned non-zero"))
    }
}

#[cfg(windows)]
fn kill_pid(pid: u32) -> std::io::Result<()> {
    use std::process::Command;
    let status = Command::new("taskkill")
        .args(["/F", "/PID"])
        .arg(pid.to_string())
        .status()?;
    if status.success() {
        Ok(())
    } else {
        Err(std::io::Error::other("taskkill returned non-zero"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::path::PathBuf;

    fn session() -> Session {
        Session {
            profile: "demo".to_string(),
            allowed_globs: vec!["demo/*".to_string()],
            denied_globs: vec![],
            contract: None,
            allow_reveal: false,
            audit_source: "mcp:test:1".to_string(),
            pid: 1,
            require_agent: false,
            vault_path: PathBuf::from("nonexistent"),
        }
    }

    fn isolated<F: FnOnce()>(f: F) {
        let tmp = tempfile::tempdir().unwrap();
        let vault_dir = tmp.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();
        temp_env::with_var("TSAFE_VAULT_DIR", Some(vault_dir.as_os_str()), f);
    }

    #[test]
    fn parse_args_requires_command_and_keys() {
        let err = parse_args(&json!({})).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::InvalidParams);
        let err = parse_args(&json!({"command": "echo"})).unwrap_err();
        assert!(err.message.contains("allowed_keys"));
    }

    #[test]
    fn parse_args_rejects_unknown_field() {
        let err = parse_args(&json!({"command": "x", "allowed_keys": ["k"], "shell": "/bin/sh"}))
            .unwrap_err();
        assert!(err.message.contains("unknown field"));
    }

    #[test]
    fn parse_args_clamps_timeout_range() {
        let err = parse_args(&json!({"command": "x", "allowed_keys": ["k"], "timeout_secs": 0}))
            .unwrap_err();
        assert!(err.message.contains("timeout"));
        let err = parse_args(&json!({"command": "x", "allowed_keys": ["k"], "timeout_secs": 9999}))
            .unwrap_err();
        assert!(err.message.contains("timeout"));
    }

    #[test]
    fn out_of_scope_key_returns_key_out_of_scope() {
        isolated(|| {
            let err = call(
                &session(),
                json!({
                    "command": "echo",
                    "args": ["hi"],
                    "allowed_keys": ["other/forbidden"]
                }),
            )
            .unwrap_err();
            assert_eq!(err.kind, McpErrorKind::KeyOutOfScope);
        });
    }

    #[test]
    fn glob_in_allowed_keys_returns_invalid_params() {
        isolated(|| {
            let err = call(
                &session(),
                json!({
                    "command": "echo",
                    "allowed_keys": ["demo/*"]
                }),
            )
            .unwrap_err();
            assert_eq!(err.kind, McpErrorKind::InvalidParams);
            assert!(err.message.contains("glob"));
        });
    }
}