rust-fs-mcp 0.1.3

Rust stdio MCP server compatible with fs-mcp public tool contracts.
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
//! git_tools.rs
//! tools::git_tools
//!
//! Collection of git tool handlers that invoke the git CLI resolved from PATH.
//! cwd / status / add / commit / diff / show all preserve the structuredContent key contract.
//!

use crate::core::args_ref::read_text_slice;
use crate::core::config::ensure_path_allowed;
use crate::core::external::{ExternalTool, run_external};
use crate::core::response::RawResult;
use serde_json::{Value, json};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

static GIT_CWD: OnceLock<Mutex<Option<PathBuf>>> = OnceLock::new();

const GIT_TIMEOUT_MS: u64 = 120_000;

fn git_cwd() -> &'static Mutex<Option<PathBuf>> {
    GIT_CWD.get_or_init(|| Mutex::new(None))
}

// Run a git command. On success (exit 0) returns stdout; on failure returns an stderr-based error.
fn run_git(cwd: &Path, args: &[String]) -> Result<String, String> {
    let output = run_external(ExternalTool::Git, args, Some(cwd), Some(GIT_TIMEOUT_MS))?;
    if output.status_code == Some(0) {
        return Ok(output.stdout);
    }

    let detail = if output.stderr.trim().is_empty() {
        output.stdout.trim().to_string()
    } else {
        output.stderr.trim().to_string()
    };
    Err(format!(
        "git failed (code {:?}): {detail}",
        output.status_code
    ))
}

fn git_args(parts: &[&str]) -> Vec<String> {
    parts.iter().map(|part| part.to_string()).collect()
}

// Resolve the repo location: args.path or the stored git cwd. The worktree root is pinned via rev-parse.
fn resolve_repo_path(args: &Value) -> Result<PathBuf, String> {
    if let Some(path) = args.get("path").and_then(Value::as_str) {
        let resolved = ensure_path_allowed(path)?;
        // If a file path is supplied use its parent directory as the git invocation cwd.
        if resolved.is_file() {
            return Ok(resolved.parent().map(Path::to_path_buf).unwrap_or(resolved));
        }
        return Ok(resolved);
    }
    git_cwd()
        .lock()
        .unwrap()
        .clone()
        .ok_or_else(|| "path is required (no git cwd set)".to_string())
}

fn open_repo(args: &Value) -> Result<PathBuf, String> {
    let path = resolve_repo_path(args)?;
    let toplevel = run_git(&path, &git_args(&["rev-parse", "--show-toplevel"]))
        .map_err(|_| format!("Not a git repository: {}", path.display()))?;
    let worktree = toplevel.trim();
    if worktree.is_empty() {
        return Err(format!("Not a git repository: {}", path.display()));
    }

    Ok(PathBuf::from(worktree))
}

fn status_text(worktree: &Path, include_untracked: bool) -> Result<String, String> {
    let mut parts = vec!["status", "--porcelain", "--branch"];
    if !include_untracked {
        parts.push("--untracked-files=no");
    }
    let output = run_git(worktree, &git_args(&parts))?;
    Ok(output.trim_end().to_string())
}

// 1. Git tools ----------------------------------------------------------------
pub fn handle_git_cwd(args: &Value) -> RawResult {
    let Some(path) = args.get("path").and_then(Value::as_str) else {
        return RawResult::error("path must be a string");
    };
    let path = match ensure_path_allowed(path) {
        Ok(path) => path,
        Err(error) => return RawResult::error(error),
    };

    let has_git = path.join(".git").exists();
    if bool_field(args, "initializeIfNotPresent", false) && !has_git {
        if !path.exists()
            && let Err(error) = fs::create_dir_all(&path)
        {
            return RawResult::error(format!("Failed to create {}: {error}", path.display()));
        }
        if let Err(error) = run_git(&path, &git_args(&["init"])) {
            return RawResult::error(error);
        }
    }

    let toplevel = run_git(&path, &git_args(&["rev-parse", "--show-toplevel"]));
    let worktree = match toplevel {
        Ok(value) if !value.trim().is_empty() => PathBuf::from(value.trim()),
        _ => {
            if bool_field(args, "validateGitRepo", true) {
                return RawResult::error(format!("Not a git repository: {}", path.display()));
            }
            *git_cwd().lock().unwrap() = Some(path.clone());
            return RawResult::structured(
                format!("Git cwd set to {}", path.display()),
                json!({ "path": path.display().to_string(), "validated": false }),
            );
        }
    };

    *git_cwd().lock().unwrap() = Some(worktree.clone());
    let git_dir = run_git(&worktree, &git_args(&["rev-parse", "--absolute-git-dir"]))
        .map(|value| value.trim().to_string())
        .unwrap_or_default();
    let status = status_text(&worktree, true).unwrap_or_default();
    RawResult::structured(
        format!("Git cwd set to {}", worktree.display()),
        json!({
            "path": worktree.display().to_string(),
            "gitDir": git_dir,
            "status": status
        }),
    )
}

pub fn handle_git_status(args: &Value) -> RawResult {
    let worktree = match open_repo(args) {
        Ok(worktree) => worktree,
        Err(error) => return RawResult::error(error),
    };

    // The porcelain body ships in text once; the previous structured.status copy plus the
    // structured.entries line array sent the same output three times in one envelope.
    match status_text(&worktree, bool_field(args, "includeUntracked", true)) {
        Ok(status) => RawResult::structured(
            status,
            json!({ "path": worktree.display().to_string() }),
        ),
        Err(error) => RawResult::error(error),
    }
}

pub fn handle_git_add(args: &Value) -> RawResult {
    let worktree = match open_repo(args) {
        Ok(worktree) => worktree,
        Err(error) => return RawResult::error(error),
    };
    let mut paths = string_array(args, "paths").unwrap_or_default();
    if paths.is_empty()
        && let Some(single) = args.get("path").and_then(Value::as_str)
    {
        paths.push(single.to_string());
    }
    if paths.is_empty() {
        return RawResult::error("paths or path is required");
    }

    let mut command = git_args(&["add", "--"]);
    command.extend(paths.iter().cloned());
    if let Err(error) = run_git(&worktree, &command) {
        return RawResult::error(error);
    }

    RawResult::structured(
        format!("Updated index with {} paths", paths.len()),
        json!({
            "path": worktree.display().to_string(),
            "entries": paths.len()
        }),
    )
}

pub fn handle_git_commit(args: &Value) -> RawResult {
    let worktree = match open_repo(args) {
        Ok(worktree) => worktree,
        Err(error) => return RawResult::error(error),
    };

    if let Some(files) = string_array(args, "filesToStage")
        && !files.is_empty()
    {
        let mut add = git_args(&["add", "--"]);
        add.extend(files.iter().cloned());
        if let Err(error) = run_git(&worktree, &add) {
            return RawResult::error(error);
        }
    }

    let message = match commit_message(args) {
        Ok(message) => message,
        Err(error) => return RawResult::error(error),
    };
    if !looks_conventional(&message) {
        return RawResult::error(
            "Commit message must start with an English Conventional Commit header",
        );
    }

    // Inject committer identity so commit works without local git config.
    // `--author` overrides AUTHOR only; COMMITTER must come from -c, git config, or env.
    let mut command: Vec<String> = vec![
        "-c".to_string(),
        "user.name=rust-fs-mcp".to_string(),
        "-c".to_string(),
        "user.email=rust-fs-mcp@example.invalid".to_string(),
        "commit".to_string(),
    ];
    if let Some(author) = author_identity(args) {
        command.push("--author".to_string());
        command.push(author);
    }
    command.push("-m".to_string());
    command.push(message.clone());
    if bool_field(args, "amend", false) {
        command.push("--amend".to_string());
    }
    if bool_field(args, "allowEmpty", false) {
        command.push("--allow-empty".to_string());
    }

    if let Err(error) = run_git(&worktree, &command) {
        return RawResult::error(error);
    }
    let oid = run_git(&worktree, &git_args(&["rev-parse", "HEAD"]))
        .map(|value| value.trim().to_string())
        .unwrap_or_default();

    // The caller already holds the commit message; echoing it back only doubles tokens.
    RawResult::structured(
        format!("[{oid}] {}", first_line(&message)),
        json!({
            "path": worktree.display().to_string(),
            "oid": oid
        }),
    )
}

pub fn handle_git_diff(args: &Value) -> RawResult {
    let worktree = match open_repo(args) {
        Ok(worktree) => worktree,
        Err(error) => return RawResult::error(error),
    };

    let mut command: Vec<String> = vec!["diff".to_string()];
    if bool_field(args, "nameOnly", false) {
        command.push("--name-only".to_string());
    } else if bool_field(args, "stat", false) {
        command.push("--stat".to_string());
    }

    if bool_field(args, "staged", false) {
        command.push("--staged".to_string());
    } else {
        let source = args.get("source").and_then(Value::as_str);
        let target = args.get("target").and_then(Value::as_str);
        match (source, target) {
            (Some(source), Some(target)) => {
                command.push(source.to_string());
                command.push(target.to_string());
            }
            (Some(value), None) | (None, Some(value)) => {
                command.push(value.to_string());
            }
            (None, None) => {}
        }
    }

    if let Some(paths) = string_array(args, "paths")
        && !paths.is_empty()
    {
        command.push("--".to_string());
        command.extend(paths);
    }

    let output = match run_git(&worktree, &command) {
        Ok(output) => output.trim_end().to_string(),
        Err(error) => return RawResult::error(error),
    };

    // The diff body ships in text once instead of doubling as structured.diff.
    RawResult::structured(
        output,
        json!({ "path": worktree.display().to_string() }),
    )
}

pub fn handle_git_show(args: &Value) -> RawResult {
    let worktree = match open_repo(args) {
        Ok(worktree) => worktree,
        Err(error) => return RawResult::error(error),
    };
    let Some(object) = args.get("object").and_then(Value::as_str) else {
        return RawResult::error("object must be a string");
    };

    let spec = match args.get("filePath").and_then(Value::as_str) {
        Some(file) => format!("{object}:{file}"),
        None => object.to_string(),
    };
    let output = match run_git(&worktree, &git_args(&["show", &spec])) {
        Ok(output) => output.trim_end().to_string(),
        Err(error) => return RawResult::error(error),
    };

    // The show body ships in text once instead of doubling as structured.output.
    RawResult::structured(
        output,
        json!({
            "path": worktree.display().to_string(),
            "object": object
        }),
    )
}

// 2. Argument helpers ---------------------------------------------------------
fn commit_message(args: &Value) -> Result<String, String> {
    if let Some(path) = args.get("messagePath").and_then(Value::as_str) {
        let path = ensure_path_allowed(path)?;
        let offset = args
            .get("messageOffset")
            .and_then(Value::as_u64)
            .unwrap_or(0) as usize;
        let length = args
            .get("messageLength")
            .and_then(Value::as_u64)
            .map(|value| value as usize);
        return read_text_slice(path, offset, length);
    }

    args.get("message")
        .and_then(Value::as_str)
        .map(str::to_string)
        .ok_or_else(|| "message or messagePath is required".to_string())
}

// When an author object is present return "name <email>" form; otherwise fall back to git's default author.
fn author_identity(args: &Value) -> Option<String> {
    let author = args.get("author").and_then(Value::as_object)?;
    let name = author
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or("rust-fs-mcp");
    let email = author
        .get("email")
        .and_then(Value::as_str)
        .unwrap_or("rust-fs-mcp@example.invalid");
    Some(format!("{name} <{email}>"))
}

fn looks_conventional(message: &str) -> bool {
    let Some(header) = message.lines().next() else {
        return false;
    };
    let Some((kind, summary)) = header.split_once(": ") else {
        return false;
    };

    let valid_type = kind
        .chars()
        .all(|ch| ch.is_ascii_lowercase() || ch == '-' || ch == '(' || ch == ')');
    valid_type && summary.chars().any(|ch| ch.is_ascii_alphabetic())
}

fn first_line(value: &str) -> &str {
    value.lines().next().unwrap_or("")
}

fn bool_field(value: &Value, key: &str, default: bool) -> bool {
    value.get(key).and_then(Value::as_bool).unwrap_or(default)
}

fn string_array(args: &Value, key: &str) -> Option<Vec<String>> {
    args.get(key).and_then(Value::as_array).map(|items| {
        items
            .iter()
            .filter_map(Value::as_str)
            .map(str::to_string)
            .collect()
    })
}

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

    #[test]
    fn conventional_header_detected() {
        assert!(looks_conventional("feat: add thing"));
        assert!(looks_conventional("fix(core): correct path"));
        assert!(!looks_conventional("no type here"));
        assert!(!looks_conventional("WIP"));
    }

    #[test]
    fn author_identity_formats_name_and_email() {
        let args = json!({ "author": { "name": "Jane", "email": "jane@example.com" } });
        assert_eq!(
            author_identity(&args).as_deref(),
            Some("Jane <jane@example.com>")
        );
        assert_eq!(author_identity(&json!({})), None);
    }
}