fs-mcp-rs 1.2.4

A fast, configurable filesystem MCP server with explicit root isolation and bounded I/O
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
//! Tool call dispatching, concurrency control, and tool execution logging.
//!
//! Maps tool calls to blocking implementations, enforces resource permits, and prints
//! concise execution logs (`[OK] tool_name ...` / `[WARN] tool_name ...`) when `server.log_tools` is enabled.

use super::catalog::tools;
use crate::app::App;
use fs_mcp_rs::{
    patch::{ApplyPatchRequest, apply_patch},
    protocol::SUPPORTED_PROTOCOL_VERSIONS,
    tree::ListTreeRequest,
};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{path::PathBuf, time::Instant};

#[derive(Deserialize)]
/// Decoded `tools/call` parameters.
struct ToolCall {
    name: String,
    #[serde(default)]
    arguments: Value,
}

pub(crate) fn tool_error(message: String) -> Value {
    let code = error_code(&message);
    json!({"content":[{"type":"text","text":message}],"structuredContent":{"error":{"code":code,"message":message}},"isError":true})
}

fn error_code(message: &str) -> &'static str {
    if message.contains("write operations are disabled") {
        "READ_ONLY"
    } else if message.contains("outside allowed roots") {
        "OUTSIDE_ALLOWED_ROOT"
    } else if message.contains("symbolic links are disabled") {
        "SYMLINK_DISALLOWED"
    } else if message.contains("valid UTF-8") {
        "INVALID_UTF8"
    } else if message.contains("context does not match") {
        "PATCH_CONTEXT_MISMATCH"
    } else if message.contains("BLAKE3 does not match") {
        "HASH_CONFLICT"
    } else if message.contains("unsupported patch") {
        "UNSUPPORTED_PATCH_OPERATION"
    } else if message.contains("patch") {
        "INVALID_PATCH"
    } else if message.contains("limit") || message.contains("exceeds") {
        "LIMIT_EXCEEDED"
    } else if message.contains("cannot be resolved") || message.contains("not found") {
        "PATH_NOT_FOUND"
    } else {
        "TOOL_ERROR"
    }
}

/// Applies per-class concurrency limits and executes blocking tools off-runtime.
pub(crate) async fn call_tool(app: &App, params: Value) -> Result<Value, String> {
    let total_started = Instant::now();
    let call: ToolCall =    match serde_json::from_value(params) {
        Ok(c) => c,
        Err(e) => {
            let err_msg = e.to_string();
            if app.settings.server.log_tools {
                eprintln!("[WARN] unknown_tool - INVALID_PARAMS: {} (0 ms)", err_msg);
            }
            return Err(err_msg);
        }
    };

    let tool_name = call.name.clone();
    let arg_summary = summarize_arguments(&call.arguments);

    let permits = if tool_name.starts_with("search_") {
        app.search_permits.clone()
    } else {
        app.io_permits.clone()
    };
    let queue_started = Instant::now();
    let _permit = match permits.acquire_owned().await {
        Ok(p) => p,
        Err(_) => {
            let err_msg = "server is shutting down".to_string();
            if app.settings.server.log_tools {
                let ms = total_started.elapsed().as_millis();
                eprintln!(
                    "[WARN] {} {} - SERVER_SHUTDOWN: {} ({} ms)",
                    tool_name, arg_summary, err_msg, ms
                );
            }
            return Err(err_msg);
        }
    };
    let queue_us = queue_started.elapsed().as_micros() as u64;
    let execution_started = Instant::now();
    let app_clone = app.clone();
    let res = tokio::task::spawn_blocking(move || call_tool_blocking(&app_clone, call)).await;

    let execution_us = execution_started.elapsed().as_micros() as u64;
    let total_us = total_started.elapsed().as_micros() as u64;
    let total_ms = total_started.elapsed().as_millis();

    match res {
        Ok(Ok(mut result)) => {
            result["_meta"] = json!({
                "totalDurationUs": total_us,
                "queueDurationUs": queue_us,
                "executionDurationUs": execution_us
            });
            if app.settings.server.log_tools {
                if arg_summary.is_empty() {
                    eprintln!("[OK] {} ({} ms)", tool_name, total_ms);
                } else {
                    eprintln!("[OK] {} {} ({} ms)", tool_name, arg_summary, total_ms);
                }
            }
            Ok(result)
        }
        Ok(Err(err_msg)) => {
            if app.settings.server.log_tools {
                let code = error_code(&err_msg);
                if arg_summary.is_empty() {
                    eprintln!(
                        "[WARN] {} - {}: {} ({} ms)",
                        tool_name, code, err_msg, total_ms
                    );
                } else {
                    eprintln!(
                        "[WARN] {} {} - {}: {} ({} ms)",
                        tool_name, arg_summary, code, err_msg, total_ms
                    );
                }
            }
            Err(err_msg)
        }
        Err(join_err) => {
            let err_msg = format!("blocking task failed: {join_err}");
            if app.settings.server.log_tools {
                eprintln!(
                    "[WARN] {} {} - INTERNAL_ERROR: {} ({} ms)",
                    tool_name, arg_summary, err_msg, total_ms
                );
            }
            Err(err_msg)
        }
    }
}

fn summarize_arguments(args: &Value) -> String {
    if let Some(obj) = args.as_object() {
        for key in &["path", "command", "pattern", "source"] {
            if let Some(val) = obj.get(*key).and_then(Value::as_str) {
                let truncated = if val.len() > 40 {
                    format!("{}...", &val[..37])
                } else {
                    val.to_string()
                };
                return format!("{}={:?}", key, truncated);
            }
        }
    }
    String::new()
}

/// Dispatches one validated tool call on a blocking worker thread.
fn call_tool_blocking(app: &App, call: ToolCall) -> Result<Value, String> {
    let arguments = call.arguments;
    let text = |key: &str| {
        arguments
            .get(key)
            .and_then(Value::as_str)
            .map(str::to_owned)
            .ok_or_else(|| format!("missing string argument: {key}"))
    };
    let output = match call.name.as_str() {
        "get_capabilities" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields)]
            struct Empty {}
            let _: Empty = serde_json::from_value(arguments.clone()).map_err(|e| e.to_string())?;
            let cfg = &app.settings;
            serde_json::to_string(&json!({"server":{"name":"fs-mcp-rs","version":env!("CARGO_PKG_VERSION")},"protocolVersions":SUPPORTED_PROTOCOL_VERSIONS,"osFamily":std::env::consts::FAMILY,"roots":cfg.filesystem.roots.iter().map(|p| fs_mcp_rs::security::display_path(p)).collect::<Vec<_>>(),"filesystem":{"readOnly":cfg.filesystem.read_only,"followLinks":cfg.filesystem.follow_links,"maxReadBytes":cfg.filesystem.max_read_bytes,"maxWriteBytes":cfg.filesystem.max_write_bytes},"search":{"maxResults":cfg.search.max_results,"maxConcurrency":cfg.search.max_concurrency},"tree":{"maxDepth":cfg.filesystem.tree_max_depth,"maxEntries":cfg.filesystem.tree_max_entries,"maxWarnings":cfg.filesystem.tree_max_warnings},"terminal":{"enabled":cfg.terminal.enabled,"defaultTimeoutMs":cfg.terminal.default_timeout_ms,"maxTimeoutMs":cfg.terminal.max_timeout_ms,"maxOutputBytes":cfg.terminal.max_output_bytes,"maxReadBytes":cfg.terminal.max_read_bytes,"maxWaitMs":cfg.terminal.max_wait_ms,"sessionRetentionMs":cfg.terminal.session_retention_ms,"maxConcurrency":cfg.terminal.max_concurrency},"tools":tools().iter().map(|t|t.name).collect::<Vec<_>>() })).map_err(|e| e.to_string())?
        }
        "list_tree" => {
            let req: ListTreeRequest =
                serde_json::from_value(arguments.clone()).map_err(|e| e.to_string())?;
            serde_json::to_string(&app.tree.list(&req).map_err(|e| e.to_string())?)
                .map_err(|e| e.to_string())?
        }
        "file_info" => {
            #[derive(Deserialize)]
            #[serde(deny_unknown_fields, rename_all = "camelCase")]
            struct A {
                path: PathBuf,
                #[serde(default)]
                include_hash: bool,
            }
            let req: A = serde_json::from_value(arguments.clone()).map_err(|e| e.to_string())?;
            serde_json::to_string(
                &app.fs
                    .file_info(&req.path, req.include_hash)
                    .map_err(|e| e.to_string())?,
            )
            .map_err(|e| e.to_string())?
        }
        "apply_patch" => {
            let req: ApplyPatchRequest =
                serde_json::from_value(arguments.clone()).map_err(|e| e.to_string())?;
            serde_json::to_string(
                &apply_patch(
                    &app.fs,
                    &req,
                    app.settings.filesystem.patch_max_bytes,
                    app.settings.filesystem.patch_preview_bytes,
                )
                .map_err(|e| e.to_string())?,
            )
            .map_err(|e| e.to_string())?
        }
        "list_directory" => serde_json::to_string(&json!({
            "entries": app.fs
                .list(&PathBuf::from(text("path")?))
                .map_err(|e| e.to_string())?
        }))
        .map_err(|e| e.to_string())?,
        "read_file" => {
            let length = arguments
                .get("length")
                .and_then(Value::as_u64)
                .ok_or_else(|| "missing integer argument: length".to_owned())?
                as usize;
            let bytes = app
                .fs
                .read(
                    &PathBuf::from(text("path")?),
                    arguments.get("offset").and_then(Value::as_u64).unwrap_or(0),
                    length,
                )
                .map_err(|e| e.to_string())?;
            match String::from_utf8(bytes) {
                Ok(text) => text,
                Err(error) => String::from_utf8_lossy(error.as_bytes()).into_owned(),
            }
        }
        "write_file" => {
            let content = text("content")?;
            let create_parents = arguments
                .get("createParents")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let (hash, created_directories) = app
                .fs
                .write_with_parents(
                    &PathBuf::from(text("path")?),
                    content.as_bytes(),
                    create_parents,
                )
                .map_err(|e| e.to_string())?;
            serde_json::to_string(&json!({
                "written": content.len(),
                "blake3": hash,
                "createdDirectories": created_directories
            }))
            .map_err(|e| e.to_string())?
        }
        "search_files" => serde_json::to_string(&json!({
            "paths": app.search
                .files(&PathBuf::from(text("path")?), &text("pattern")?)
                .map_err(|e| e.to_string())?
        }))
        .map_err(|e| e.to_string())?,
        "search_content" => serde_json::to_string(&json!({
            "matches": app.search
                .content(
                    &PathBuf::from(text("path")?),
                    &text("pattern")?,
                    arguments
                        .get("literal")
                        .and_then(Value::as_bool)
                        .unwrap_or(true),
                )
                .map_err(|e| e.to_string())?
        }))
        .map_err(|e| e.to_string())?,

        "create_directory" => {
            app.fs
                .create_directory(&PathBuf::from(text("path")?))
                .map_err(|e| e.to_string())?;
            "{\"created\":true}".into()
        }
        "remove" => {
            app.fs
                .remove(&PathBuf::from(text("path")?))
                .map_err(|e| e.to_string())?;
            "{\"removed\":true}".into()
        }
        "hash_file" => app
            .fs
            .hash(&PathBuf::from(text("path")?))
            .map_err(|e| e.to_string())?,
        "move" => {
            app.fs
                .move_path(
                    &PathBuf::from(text("source")?),
                    &PathBuf::from(text("destination")?),
                )
                .map_err(|e| e.to_string())?;
            "{\"moved\":true}".into()
        }
        "edit_text" => app
            .fs
            .edit(
                &PathBuf::from(text("path")?),
                &text("old")?,
                &text("new")?,
                arguments
                    .get("expected")
                    .and_then(Value::as_u64)
                    .ok_or_else(|| "missing integer argument: expected".to_owned())?
                    as usize,
            )
            .map_err(|e| e.to_string())?,
        "terminal_start" => {
            let command = text("command")?;
            let cwd = arguments
                .get("cwd")
                .and_then(Value::as_str)
                .map(PathBuf::from);
            let result = app
                .terminal
                .start(
                    &command,
                    cwd.as_deref(),
                    arguments.get("timeoutMs").and_then(Value::as_u64),
                )
                .map_err(|e| e.to_string())?;
            serde_json::to_string(&result).map_err(|e| e.to_string())?
        }
        "terminal_read" => {
            let result = app
                .terminal
                .read(
                    &text("sessionId")?,
                    arguments.get("cursor").and_then(Value::as_u64).unwrap_or(0),
                    arguments.get("waitMs").and_then(Value::as_u64),
                    arguments
                        .get("maxBytes")
                        .and_then(Value::as_u64)
                        .map(|value| value as usize),
                )
                .map_err(|e| e.to_string())?;
            serde_json::to_string(&result).map_err(|e| e.to_string())?
        }
        "terminal_write" => {
            let result = app
                .terminal
                .write(&text("sessionId")?, text("data")?.as_bytes())
                .map_err(|e| e.to_string())?;
            serde_json::to_string(&result).map_err(|e| e.to_string())?
        }
        "terminal_close_stdin" => {
            app.terminal
                .close_stdin(&text("sessionId")?)
                .map_err(|e| e.to_string())?;
            "{\"closed\":true}".into()
        }
        "terminal_kill" => {
            let result = app
                .terminal
                .kill(&text("sessionId")?)
                .map_err(|e| e.to_string())?;
            serde_json::to_string(&result).map_err(|e| e.to_string())?
        }
        "terminal_close" => {
            app.terminal
                .close(&text("sessionId")?)
                .map_err(|e| e.to_string())?;
            "{\"closed\":true}".into()
        }
        "run_command" => {
            let command = text("command")?;
            let cwd = arguments
                .get("cwd")
                .and_then(Value::as_str)
                .map(PathBuf::from);
            let result = app
                .terminal
                .run(
                    &command,
                    cwd.as_deref(),
                    arguments.get("timeoutMs").and_then(Value::as_u64),
                )
                .map_err(|e| e.to_string())?;
            serde_json::to_string(&result).map_err(|e| e.to_string())?
        }
        _ => return Err(format!("unknown tool: {}", call.name)),
    };
    let mut result = json!({
        "content": [{"type": "text", "text": output}],
        "isError": false
    });
    if let Ok(Value::Object(object)) = serde_json::from_str::<Value>(&output) {
        result["structuredContent"] = Value::Object(object);
    }
    Ok(result)
}