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
//! tsafe-mcp — library entry point exposed for the tsafe meta-crate.
//!
//! Per ADR-006, this crate ships a separately published companion binary that
//! mirrors the publish topology of `tsafe-agent`. The library entry point
//! [`run`] is called both from the standalone `tsafe-mcp` binary
//! (`src/main.rs`) and from the meta-crate shim
//! (`crates/tsafe/src/bin/tsafe_mcp.rs`).
//!
//! The runtime exposes four subcommands per design §5.2:
//! - `tsafe-mcp serve [...]`           — stdio JSON-RPC server (default subcommand)
//! - `tsafe-mcp install <host> [...]`  — write per-host MCP config
//! - `tsafe-mcp uninstall <host> [...]`— remove the entry
//! - `tsafe-mcp status`                — print binary version + resolved scope
//!
//! All other doctrine: thin-MCP stance, ADR-003 agent IPC reuse, ADR-005 module
//! layout. See `docs/architecture/ADR-006-mcp-server.md` and
//! `docs/architecture/mcp-server-design.md`.

pub mod audit;
pub mod backend;
pub mod errors;
pub mod install;
pub mod server;
pub mod session;
pub mod tools;

use crate::errors::{McpError, McpErrorKind};
use crate::install::{InstallOpts, Scope};
use crate::server::MCP_PROTOCOL_VERSION;
use crate::session::{Session, SessionArgs};

/// Top-level subcommand parsed from `std::env::args()`.
#[derive(Debug)]
enum Subcommand {
    /// JSON-RPC server over stdio. Default when no subcommand is given.
    Serve(Vec<String>),
    /// Install / uninstall / status — diagnostic shells, no JSON-RPC.
    Install {
        host: String,
        rest: Vec<String>,
    },
    Uninstall {
        host: String,
        rest: Vec<String>,
    },
    Status,
}

/// Process entry point. Parses argv, dispatches to the matching subcommand,
/// and exits the process with code 1 on error (same shape as
/// `tsafe-agent::run` at `crates/tsafe-agent/src/lib.rs`).
pub fn run() {
    if let Err(e) = run_inner() {
        eprintln!("tsafe-mcp: {e:#}");
        std::process::exit(1);
    }
}

fn run_inner() -> Result<(), McpError> {
    let argv: Vec<String> = std::env::args().collect();
    let sub = parse_subcommand(&argv)?;

    match sub {
        Subcommand::Serve(serve_args) => {
            let session_args = SessionArgs::parse(&serve_args)?;
            let session = Session::from_cli_args(&session_args)?;
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .map_err(|e| {
                    McpError::new(
                        McpErrorKind::InternalError,
                        format!("tokio runtime init failed: {e}"),
                    )
                })?
                .block_on(async {
                    server::serve_stdio(session).await.map_err(|e| {
                        McpError::new(McpErrorKind::InternalError, format!("serve failed: {e}"))
                    })
                })
        }
        Subcommand::Install { host, rest } => {
            let opts = parse_install_opts(&rest, false)?;
            install::dispatch(&host, &opts)
        }
        Subcommand::Uninstall { host, rest } => {
            let opts = parse_install_opts(&rest, true)?;
            install::dispatch(&host, &opts)
        }
        Subcommand::Status => {
            status_diagnostic();
            Ok(())
        }
    }
}

fn parse_subcommand(argv: &[String]) -> Result<Subcommand, McpError> {
    // argv[0] is the binary path. Subcommand is argv[1] when present.
    if argv.len() < 2 {
        // No subcommand → default to `serve` with no additional args. The
        // serve path will still fail-closed if --profile / scope are missing.
        return Ok(Subcommand::Serve(Vec::new()));
    }

    match argv[1].as_str() {
        "serve" => Ok(Subcommand::Serve(argv[2..].to_vec())),
        "install" => {
            if argv.len() < 3 {
                return Err(McpError::new(
                    McpErrorKind::InvalidRequest,
                    "install: missing host argument (claude | cursor | continue | windsurf | codex)",
                ));
            }
            Ok(Subcommand::Install {
                host: argv[2].clone(),
                rest: argv[3..].to_vec(),
            })
        }
        "uninstall" => {
            if argv.len() < 3 {
                return Err(McpError::new(
                    McpErrorKind::InvalidRequest,
                    "uninstall: missing host argument",
                ));
            }
            Ok(Subcommand::Uninstall {
                host: argv[2].clone(),
                rest: argv[3..].to_vec(),
            })
        }
        "status" => Ok(Subcommand::Status),
        // Anything else: treat as forward-compatible `serve` invocation with
        // flags only (matches the bare `tsafe-mcp --profile foo` shape used by
        // most host configs).
        other if other.starts_with("--") => Ok(Subcommand::Serve(argv[1..].to_vec())),
        unknown => Err(McpError::new(
            McpErrorKind::InvalidRequest,
            format!(
                "unknown subcommand '{unknown}'. Use: serve | install <host> | uninstall <host> | status"
            ),
        )),
    }
}

fn parse_install_opts(rest: &[String], uninstall: bool) -> Result<InstallOpts, McpError> {
    let mut profile: Option<String> = None;
    let mut allowed_keys: Vec<String> = Vec::new();
    let mut denied_keys: Vec<String> = Vec::new();
    let mut contract: Option<String> = None;
    let mut allow_reveal = false;
    let mut name: Option<String> = None;
    let mut global = false;
    let mut project_dir: Option<std::path::PathBuf> = None;
    let mut dry_run = false;
    let mut audit_source: Option<String> = None;

    let mut i = 0;
    while i < rest.len() {
        let arg = &rest[i];
        match arg.as_str() {
            "--profile" => {
                i += 1;
                profile = Some(rest.get(i).cloned().ok_or_else(|| {
                    McpError::new(McpErrorKind::InvalidRequest, "--profile requires a value")
                })?);
            }
            "--allowed-keys" => {
                i += 1;
                let raw = rest.get(i).cloned().ok_or_else(|| {
                    McpError::new(
                        McpErrorKind::InvalidRequest,
                        "--allowed-keys requires a value",
                    )
                })?;
                allowed_keys = split_csv(&raw);
            }
            "--denied-keys" => {
                i += 1;
                let raw = rest.get(i).cloned().ok_or_else(|| {
                    McpError::new(
                        McpErrorKind::InvalidRequest,
                        "--denied-keys requires a value",
                    )
                })?;
                denied_keys = split_csv(&raw);
            }
            "--contract" => {
                i += 1;
                contract = Some(rest.get(i).cloned().ok_or_else(|| {
                    McpError::new(McpErrorKind::InvalidRequest, "--contract requires a value")
                })?);
            }
            "--allow-reveal" => allow_reveal = true,
            "--name" => {
                i += 1;
                name = Some(rest.get(i).cloned().ok_or_else(|| {
                    McpError::new(McpErrorKind::InvalidRequest, "--name requires a value")
                })?);
            }
            "--global" => global = true,
            "--project" => {
                i += 1;
                let dir = rest.get(i).cloned().ok_or_else(|| {
                    McpError::new(
                        McpErrorKind::InvalidRequest,
                        "--project requires a directory path",
                    )
                })?;
                project_dir = Some(std::path::PathBuf::from(dir));
            }
            "--dry-run" => dry_run = true,
            "--audit-source" => {
                i += 1;
                audit_source = Some(rest.get(i).cloned().ok_or_else(|| {
                    McpError::new(
                        McpErrorKind::InvalidRequest,
                        "--audit-source requires a value",
                    )
                })?);
            }
            other => {
                return Err(McpError::new(
                    McpErrorKind::InvalidRequest,
                    format!("unknown install flag: '{other}'"),
                ));
            }
        }
        i += 1;
    }

    let scope = match project_dir {
        Some(dir) => Scope::Project { dir },
        None if global => Scope::Global,
        None => Scope::Global, // default
    };

    let profile = profile.ok_or_else(|| {
        McpError::new(
            McpErrorKind::InvalidRequest,
            "install/uninstall: --profile <name> is required",
        )
    })?;

    Ok(InstallOpts {
        profile,
        allowed_keys,
        denied_keys,
        contract,
        allow_reveal,
        name,
        scope,
        dry_run,
        uninstall,
        audit_source,
    })
}

fn split_csv(raw: &str) -> Vec<String> {
    raw.split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

fn status_diagnostic() {
    println!("tsafe-mcp {}", env!("CARGO_PKG_VERSION"));
    println!("protocol: MCP {MCP_PROTOCOL_VERSION}");
    println!();
    println!("Resolve scope at runtime by invoking `tsafe-mcp serve` with one of:");
    println!("  --profile <name>");
    println!("  --allowed-keys <glob,glob>");
    println!("  --contract <name>");
    println!("  --denied-keys <glob,glob>");
    println!("  --allow-reveal");
    println!("  --audit-source <host-label>");
    println!();
    println!("See ADR-006 / docs/architecture/mcp-server-design.md for the full surface.");
}

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

    fn argv(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    /// Default subcommand is `Serve(empty)` when no subcommand is supplied.
    /// The downstream session check still fails-closed without scope.
    #[test]
    fn parse_subcommand_defaults_to_serve_with_no_args() {
        let parsed = parse_subcommand(&argv(&["tsafe-mcp"])).unwrap();
        match parsed {
            Subcommand::Serve(rest) => assert!(rest.is_empty()),
            other => panic!("expected Serve, got {other:?}"),
        }
    }

    /// `tsafe-mcp serve --profile foo` parses to Serve with the rest intact.
    #[test]
    fn parse_subcommand_serve_passes_through_remaining_args() {
        let parsed = parse_subcommand(&argv(&["tsafe-mcp", "serve", "--profile", "demo"])).unwrap();
        match parsed {
            Subcommand::Serve(rest) => {
                assert_eq!(rest, vec!["--profile", "demo"]);
            }
            other => panic!("expected Serve, got {other:?}"),
        }
    }

    /// Bare flag invocation `tsafe-mcp --profile foo` (no `serve` keyword) is
    /// the shape most host configs use; it must still route to Serve.
    #[test]
    fn parse_subcommand_bare_flag_routes_to_serve() {
        let parsed = parse_subcommand(&argv(&["tsafe-mcp", "--profile", "demo"])).unwrap();
        match parsed {
            Subcommand::Serve(rest) => {
                assert_eq!(rest, vec!["--profile", "demo"]);
            }
            other => panic!("expected Serve, got {other:?}"),
        }
    }

    /// `install` without a host argument is InvalidRequest.
    #[test]
    fn parse_subcommand_install_without_host_returns_invalid_request() {
        let err = parse_subcommand(&argv(&["tsafe-mcp", "install"])).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
        assert!(err.message.contains("install"));
    }

    /// `uninstall` mirrors `install`: host required.
    #[test]
    fn parse_subcommand_uninstall_without_host_returns_invalid_request() {
        let err = parse_subcommand(&argv(&["tsafe-mcp", "uninstall"])).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
    }

    /// `status` parses with no further arguments.
    #[test]
    fn parse_subcommand_status_parses_cleanly() {
        let parsed = parse_subcommand(&argv(&["tsafe-mcp", "status"])).unwrap();
        assert!(matches!(parsed, Subcommand::Status));
    }

    /// Unknown subcommand is InvalidRequest with a hint pointing at the
    /// supported set.
    #[test]
    fn parse_subcommand_unknown_returns_invalid_request_with_hint() {
        let err = parse_subcommand(&argv(&["tsafe-mcp", "diagnose"])).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
        assert!(
            err.message.contains("serve")
                && err.message.contains("install")
                && err.message.contains("status"),
            "hint should list supported subcommands: {}",
            err.message
        );
    }

    /// `parse_install_opts` round-trip: scope, contract, allow-reveal, name,
    /// audit-source all land on the right fields.
    #[test]
    fn parse_install_opts_round_trips_all_flags() {
        let rest = argv(&[
            "--profile",
            "demo",
            "--allowed-keys",
            "demo/*,shared/*",
            "--denied-keys",
            "demo/secret",
            "--contract",
            "deploy",
            "--allow-reveal",
            "--name",
            "testsrv",
            "--audit-source",
            "mcp:claude:proof",
        ]);
        let opts = parse_install_opts(&rest, false).unwrap();
        assert_eq!(opts.profile, "demo");
        assert_eq!(opts.allowed_keys, vec!["demo/*", "shared/*"]);
        assert_eq!(opts.denied_keys, vec!["demo/secret"]);
        assert_eq!(opts.contract.as_deref(), Some("deploy"));
        assert!(opts.allow_reveal);
        assert_eq!(opts.name.as_deref(), Some("testsrv"));
        assert_eq!(opts.audit_source.as_deref(), Some("mcp:claude:proof"));
        assert!(!opts.uninstall);
        assert!(!opts.dry_run);
    }

    /// `--project <dir>` switches scope to Project.
    #[test]
    fn parse_install_opts_project_scope() {
        let rest = argv(&[
            "--profile",
            "demo",
            "--allowed-keys",
            "demo/*",
            "--project",
            "/tmp/myproject",
            "--dry-run",
        ]);
        let opts = parse_install_opts(&rest, false).unwrap();
        match opts.scope {
            crate::install::Scope::Project { dir } => {
                assert_eq!(dir, std::path::PathBuf::from("/tmp/myproject"));
            }
            crate::install::Scope::Global => panic!("expected Project scope, got Global"),
        }
        assert!(opts.dry_run);
    }

    /// Missing `--profile` value is InvalidRequest.
    #[test]
    fn parse_install_opts_missing_profile_value() {
        let rest = argv(&["--profile"]);
        let err = parse_install_opts(&rest, false).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
        assert!(err.message.contains("--profile"));
    }

    /// `parse_install_opts` without `--profile` at all also surfaces
    /// InvalidRequest from the final check.
    #[test]
    fn parse_install_opts_missing_profile_entirely() {
        let rest = argv(&["--allowed-keys", "demo/*"]);
        let err = parse_install_opts(&rest, false).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
        assert!(err.message.contains("--profile"));
    }

    /// Unknown install flag bubbles up as InvalidRequest, never silently
    /// swallowed.
    #[test]
    fn parse_install_opts_rejects_unknown_flag() {
        let rest = argv(&["--profile", "demo", "--mystery-flag"]);
        let err = parse_install_opts(&rest, false).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
        assert!(err.message.contains("unknown install flag"));
    }

    /// Uninstall flag is plumbed through correctly.
    #[test]
    fn parse_install_opts_uninstall_sets_flag() {
        let rest = argv(&["--profile", "demo"]);
        let opts = parse_install_opts(&rest, true).unwrap();
        assert!(opts.uninstall);
    }

    /// `split_csv` strips whitespace and drops empty entries — matters for
    /// `--allowed-keys "demo/*, , bar/*"` and similar copy-paste shapes.
    #[test]
    fn split_csv_handles_whitespace_and_empties() {
        assert_eq!(split_csv("demo/*, , shared/*"), vec!["demo/*", "shared/*"]);
        assert!(split_csv("").is_empty());
        assert_eq!(split_csv(" only "), vec!["only"]);
    }
}