bounded-filesystem-mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +280 -2
- package/dist/bounded.js +184 -0
- package/dist/index.js +607 -0
- package/dist/lib.js +310 -0
- package/dist/path-utils.js +103 -0
- package/dist/path-validation.js +75 -0
- package/dist/roots-utils.js +70 -0
- package/package.json +50 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { RootsListChangedNotificationSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
+
import fs from "fs/promises";
|
|
6
|
+
import { createReadStream } from "fs";
|
|
7
|
+
import path from "path";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { minimatch } from "minimatch";
|
|
10
|
+
import { normalizePath, expandHome } from './path-utils.js';
|
|
11
|
+
import { getValidRootDirectories } from './roots-utils.js';
|
|
12
|
+
import {
|
|
13
|
+
// Function imports
|
|
14
|
+
formatSize, validatePath, getFileStats, writeFileContent, searchFilesWithValidation, applyFileEdits, tailFile, headFile, setAllowedDirectories, } from './lib.js';
|
|
15
|
+
import { capText, parseServerArgs, readMultipleFiles, readTextWindow, windowResult, } from './bounded.js';
|
|
16
|
+
// Command line argument parsing
|
|
17
|
+
let serverArgs;
|
|
18
|
+
try {
|
|
19
|
+
serverArgs = parseServerArgs(process.argv.slice(2));
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
const { directories: args, limits } = serverArgs;
|
|
26
|
+
if (args.length === 0) {
|
|
27
|
+
console.error("Usage: bounded-filesystem-mcp [--max-result-chars <n>] [--max-media-bytes <n>] [allowed-directory] [additional-directories...]");
|
|
28
|
+
console.error("Note: Allowed directories can be provided via:");
|
|
29
|
+
console.error(" 1. Command-line arguments (shown above)");
|
|
30
|
+
console.error(" 2. MCP roots protocol (if client supports it)");
|
|
31
|
+
console.error("At least one directory must be provided by EITHER method for the server to operate.");
|
|
32
|
+
}
|
|
33
|
+
// Store allowed directories in normalized and resolved form
|
|
34
|
+
let allowedDirectories = await Promise.all(args.map(async (dir) => {
|
|
35
|
+
const expanded = expandHome(dir);
|
|
36
|
+
const absolute = path.resolve(expanded);
|
|
37
|
+
try {
|
|
38
|
+
// Security: Resolve symlinks in allowed directories during startup
|
|
39
|
+
// This ensures we know the real paths and can validate against them later
|
|
40
|
+
const resolved = await fs.realpath(absolute);
|
|
41
|
+
return normalizePath(resolved);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
// If we can't resolve (doesn't exist), use the normalized absolute path
|
|
45
|
+
// This allows configuring allowed dirs that will be created later
|
|
46
|
+
return normalizePath(absolute);
|
|
47
|
+
}
|
|
48
|
+
}));
|
|
49
|
+
// Validate that all directories exist and are accessible
|
|
50
|
+
await Promise.all(allowedDirectories.map(async (dir) => {
|
|
51
|
+
try {
|
|
52
|
+
const stats = await fs.stat(dir);
|
|
53
|
+
if (!stats.isDirectory()) {
|
|
54
|
+
console.error(`Error: ${dir} is not a directory`);
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
console.error(`Error accessing directory ${dir}:`, error);
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
}));
|
|
63
|
+
// Initialize the global allowedDirectories in lib.ts
|
|
64
|
+
setAllowedDirectories(allowedDirectories);
|
|
65
|
+
// Schema definitions
|
|
66
|
+
const OffsetSchema = z.number().int().min(0).optional()
|
|
67
|
+
.describe('Character position to start reading from (default 0). Use the offset given in a truncation notice to continue');
|
|
68
|
+
const LimitSchema = z.number().int().min(1).optional()
|
|
69
|
+
.describe('Maximum number of characters to return, clamped to the result cap');
|
|
70
|
+
const ReadTextFileArgsSchema = z.object({
|
|
71
|
+
path: z.string(),
|
|
72
|
+
tail: z.number().optional().describe('If provided, returns only the last N lines of the file'),
|
|
73
|
+
head: z.number().optional().describe('If provided, returns only the first N lines of the file'),
|
|
74
|
+
offset: OffsetSchema,
|
|
75
|
+
limit: LimitSchema,
|
|
76
|
+
});
|
|
77
|
+
const ReadMediaFileArgsSchema = z.object({
|
|
78
|
+
path: z.string()
|
|
79
|
+
});
|
|
80
|
+
const ReadMultipleFilesArgsSchema = z.object({
|
|
81
|
+
paths: z
|
|
82
|
+
.array(z.string())
|
|
83
|
+
.min(1, "At least one file path must be provided")
|
|
84
|
+
.describe("Array of file paths to read. Each path must be a string pointing to a valid file within allowed directories."),
|
|
85
|
+
});
|
|
86
|
+
const WriteFileArgsSchema = z.object({
|
|
87
|
+
path: z.string(),
|
|
88
|
+
content: z.string(),
|
|
89
|
+
});
|
|
90
|
+
const EditOperation = z.object({
|
|
91
|
+
oldText: z.string().describe('Text to search for - must match exactly'),
|
|
92
|
+
newText: z.string().describe('Text to replace with')
|
|
93
|
+
});
|
|
94
|
+
const EditFileArgsSchema = z.object({
|
|
95
|
+
path: z.string(),
|
|
96
|
+
edits: z.array(EditOperation),
|
|
97
|
+
dryRun: z.boolean().default(false).describe('Preview changes using git-style diff format')
|
|
98
|
+
});
|
|
99
|
+
const CreateDirectoryArgsSchema = z.object({
|
|
100
|
+
path: z.string(),
|
|
101
|
+
});
|
|
102
|
+
const ListDirectoryArgsSchema = z.object({
|
|
103
|
+
path: z.string(),
|
|
104
|
+
});
|
|
105
|
+
const ListDirectoryWithSizesArgsSchema = z.object({
|
|
106
|
+
path: z.string(),
|
|
107
|
+
sortBy: z.enum(['name', 'size']).optional().default('name').describe('Sort entries by name or size'),
|
|
108
|
+
});
|
|
109
|
+
const DirectoryTreeArgsSchema = z.object({
|
|
110
|
+
path: z.string(),
|
|
111
|
+
excludePatterns: z.array(z.string()).optional().default([])
|
|
112
|
+
});
|
|
113
|
+
const MoveFileArgsSchema = z.object({
|
|
114
|
+
source: z.string(),
|
|
115
|
+
destination: z.string(),
|
|
116
|
+
});
|
|
117
|
+
const SearchFilesArgsSchema = z.object({
|
|
118
|
+
path: z.string(),
|
|
119
|
+
pattern: z.string(),
|
|
120
|
+
excludePatterns: z.array(z.string()).optional().default([])
|
|
121
|
+
});
|
|
122
|
+
const GetFileInfoArgsSchema = z.object({
|
|
123
|
+
path: z.string(),
|
|
124
|
+
});
|
|
125
|
+
// Server setup
|
|
126
|
+
const server = new McpServer({
|
|
127
|
+
name: "bounded-filesystem",
|
|
128
|
+
version: "0.1.0",
|
|
129
|
+
});
|
|
130
|
+
const capNote = `Results longer than ${limits.maxResultChars.toLocaleString("en-US")} characters are cut short, ending with a notice that says how to get the rest.`;
|
|
131
|
+
// Reads a file as a stream of buffers, concatenates them, and then encodes
|
|
132
|
+
// the result to a Base64 string. This is a memory-efficient way to handle
|
|
133
|
+
// binary data from a stream before the final encoding.
|
|
134
|
+
async function readFileAsBase64Stream(filePath, maxBytes) {
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
// Reads at most one byte past the limit, so a file that grew after the size check is still refused.
|
|
137
|
+
const stream = createReadStream(filePath, { end: maxBytes });
|
|
138
|
+
const chunks = [];
|
|
139
|
+
stream.on('data', (chunk) => {
|
|
140
|
+
chunks.push(chunk);
|
|
141
|
+
});
|
|
142
|
+
stream.on('end', () => {
|
|
143
|
+
const finalBuffer = Buffer.concat(chunks);
|
|
144
|
+
if (finalBuffer.length > maxBytes) {
|
|
145
|
+
reject(new Error(`File is larger than the ${maxBytes.toLocaleString("en-US")}-byte limit for read_media_file`));
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
resolve(finalBuffer.toString('base64'));
|
|
149
|
+
});
|
|
150
|
+
stream.on('error', (err) => reject(err));
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
// Tool registrations
|
|
154
|
+
// read_file (deprecated) and read_text_file
|
|
155
|
+
const readTextFileHandler = async (args) => {
|
|
156
|
+
const validPath = await validatePath(args.path);
|
|
157
|
+
if (args.head && args.tail) {
|
|
158
|
+
throw new Error("Cannot specify both head and tail parameters simultaneously");
|
|
159
|
+
}
|
|
160
|
+
if ((args.head || args.tail) && (args.offset !== undefined || args.limit !== undefined)) {
|
|
161
|
+
throw new Error("Cannot combine head or tail with offset or limit: use head/tail to read lines, or offset/limit to read a window of characters");
|
|
162
|
+
}
|
|
163
|
+
const lineHint = "use a smaller head or tail, or page through the file with offset and limit instead";
|
|
164
|
+
let content;
|
|
165
|
+
if (args.tail) {
|
|
166
|
+
content = capText(await tailFile(validPath, args.tail), limits.maxResultChars, lineHint);
|
|
167
|
+
}
|
|
168
|
+
else if (args.head) {
|
|
169
|
+
content = capText(await headFile(validPath, args.head), limits.maxResultChars, lineHint);
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
const limit = Math.min(args.limit ?? limits.maxResultChars, limits.maxResultChars);
|
|
173
|
+
content = windowResult(await readTextWindow(validPath, args.offset ?? 0, limit));
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
content: [{ type: "text", text: content }]
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
server.registerTool("read_file", {
|
|
180
|
+
title: "Read File (Deprecated)",
|
|
181
|
+
description: "Read the complete contents of a file as text. DEPRECATED: Use read_text_file instead. " +
|
|
182
|
+
"Use the 'offset' and 'limit' parameters to read a window of characters. " + capNote,
|
|
183
|
+
inputSchema: ReadTextFileArgsSchema.shape,
|
|
184
|
+
annotations: { readOnlyHint: true }
|
|
185
|
+
}, readTextFileHandler);
|
|
186
|
+
server.registerTool("read_text_file", {
|
|
187
|
+
title: "Read Text File",
|
|
188
|
+
description: "Read the complete contents of a file from the file system as text. " +
|
|
189
|
+
"Handles various text encodings and provides detailed error messages " +
|
|
190
|
+
"if the file cannot be read. Use this tool when you need to examine " +
|
|
191
|
+
"the contents of a single file. Use the 'head' parameter to read only " +
|
|
192
|
+
"the first N lines of a file, or the 'tail' parameter to read only " +
|
|
193
|
+
"the last N lines of a file. Use the 'offset' and 'limit' parameters to read " +
|
|
194
|
+
"a window of characters, for example to continue after a truncated result; " +
|
|
195
|
+
"they cannot be combined with 'head' or 'tail'. " + capNote + " " +
|
|
196
|
+
"Operates on the file as text regardless of extension. " +
|
|
197
|
+
"Only works within allowed directories.",
|
|
198
|
+
inputSchema: {
|
|
199
|
+
path: z.string(),
|
|
200
|
+
tail: z.number().optional().describe("If provided, returns only the last N lines of the file"),
|
|
201
|
+
head: z.number().optional().describe("If provided, returns only the first N lines of the file"),
|
|
202
|
+
offset: OffsetSchema,
|
|
203
|
+
limit: LimitSchema,
|
|
204
|
+
},
|
|
205
|
+
annotations: { readOnlyHint: true }
|
|
206
|
+
}, readTextFileHandler);
|
|
207
|
+
server.registerTool("read_media_file", {
|
|
208
|
+
title: "Read Media File",
|
|
209
|
+
description: "Read an image or audio file. Returns the base64 encoded data and MIME type. " +
|
|
210
|
+
`Files larger than ${limits.maxMediaBytes.toLocaleString("en-US")} bytes are refused with an error. ` +
|
|
211
|
+
"Only works within allowed directories.",
|
|
212
|
+
inputSchema: {
|
|
213
|
+
path: z.string()
|
|
214
|
+
},
|
|
215
|
+
annotations: { readOnlyHint: true }
|
|
216
|
+
}, async (args) => {
|
|
217
|
+
const validPath = await validatePath(args.path);
|
|
218
|
+
const extension = path.extname(validPath).toLowerCase();
|
|
219
|
+
const mimeTypes = {
|
|
220
|
+
".png": "image/png",
|
|
221
|
+
".jpg": "image/jpeg",
|
|
222
|
+
".jpeg": "image/jpeg",
|
|
223
|
+
".gif": "image/gif",
|
|
224
|
+
".webp": "image/webp",
|
|
225
|
+
".bmp": "image/bmp",
|
|
226
|
+
".svg": "image/svg+xml",
|
|
227
|
+
".mp3": "audio/mpeg",
|
|
228
|
+
".wav": "audio/wav",
|
|
229
|
+
".ogg": "audio/ogg",
|
|
230
|
+
".flac": "audio/flac",
|
|
231
|
+
};
|
|
232
|
+
const mimeType = mimeTypes[extension] || "application/octet-stream";
|
|
233
|
+
const { size } = await fs.stat(validPath);
|
|
234
|
+
if (size > limits.maxMediaBytes) {
|
|
235
|
+
return {
|
|
236
|
+
content: [{
|
|
237
|
+
type: "text",
|
|
238
|
+
text: `File too large for read_media_file: ${args.path} is ${size.toLocaleString("en-US")} bytes (${formatSize(size)}), ` +
|
|
239
|
+
`and the limit is ${limits.maxMediaBytes.toLocaleString("en-US")} bytes (${formatSize(limits.maxMediaBytes)}).`,
|
|
240
|
+
}],
|
|
241
|
+
isError: true,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const data = await readFileAsBase64Stream(validPath, limits.maxMediaBytes);
|
|
245
|
+
const type = mimeType.startsWith("image/")
|
|
246
|
+
? "image"
|
|
247
|
+
: mimeType.startsWith("audio/")
|
|
248
|
+
? "audio"
|
|
249
|
+
// Fallback for other binary types, not officially supported by the spec but has been used for some time
|
|
250
|
+
: "blob";
|
|
251
|
+
const contentItem = { type: type, data, mimeType };
|
|
252
|
+
return {
|
|
253
|
+
content: [contentItem],
|
|
254
|
+
};
|
|
255
|
+
});
|
|
256
|
+
server.registerTool("read_multiple_files", {
|
|
257
|
+
title: "Read Multiple Files",
|
|
258
|
+
description: "Read the contents of multiple files simultaneously. This is more " +
|
|
259
|
+
"efficient than reading files one by one when you need to analyze " +
|
|
260
|
+
"or compare multiple files. Each file's content is returned with its " +
|
|
261
|
+
"path as a reference. Failed reads for individual files won't stop " +
|
|
262
|
+
"the entire operation. " + capNote + " Only works within allowed directories.",
|
|
263
|
+
inputSchema: {
|
|
264
|
+
paths: z.array(z.string())
|
|
265
|
+
.min(1)
|
|
266
|
+
.describe("Array of file paths to read. Each path must be a string pointing to a valid file within allowed directories.")
|
|
267
|
+
},
|
|
268
|
+
annotations: { readOnlyHint: true }
|
|
269
|
+
}, async (args) => {
|
|
270
|
+
const text = await readMultipleFiles(args.paths, limits.maxResultChars);
|
|
271
|
+
return {
|
|
272
|
+
content: [{ type: "text", text }]
|
|
273
|
+
};
|
|
274
|
+
});
|
|
275
|
+
server.registerTool("write_file", {
|
|
276
|
+
title: "Write File",
|
|
277
|
+
description: "Create a new file or completely overwrite an existing file with new content. " +
|
|
278
|
+
"Use with caution as it will overwrite existing files without warning. " +
|
|
279
|
+
"Handles text content with proper encoding. Only works within allowed directories.",
|
|
280
|
+
inputSchema: {
|
|
281
|
+
path: z.string(),
|
|
282
|
+
content: z.string()
|
|
283
|
+
},
|
|
284
|
+
annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: true }
|
|
285
|
+
}, async (args) => {
|
|
286
|
+
const validPath = await validatePath(args.path);
|
|
287
|
+
await writeFileContent(validPath, args.content);
|
|
288
|
+
const text = `Successfully wrote to ${args.path}`;
|
|
289
|
+
return {
|
|
290
|
+
content: [{ type: "text", text }]
|
|
291
|
+
};
|
|
292
|
+
});
|
|
293
|
+
server.registerTool("edit_file", {
|
|
294
|
+
title: "Edit File",
|
|
295
|
+
description: "Make line-based edits to a text file. Each edit replaces exact line sequences " +
|
|
296
|
+
"with new content. Returns a git-style diff showing the changes made. " +
|
|
297
|
+
"Only works within allowed directories.",
|
|
298
|
+
inputSchema: {
|
|
299
|
+
path: z.string(),
|
|
300
|
+
edits: z.array(z.object({
|
|
301
|
+
oldText: z.string().describe("Text to search for - must match exactly"),
|
|
302
|
+
newText: z.string().describe("Text to replace with")
|
|
303
|
+
})),
|
|
304
|
+
dryRun: z.boolean().default(false).describe("Preview changes using git-style diff format")
|
|
305
|
+
},
|
|
306
|
+
annotations: { readOnlyHint: false, idempotentHint: false, destructiveHint: true }
|
|
307
|
+
}, async (args) => {
|
|
308
|
+
const validPath = await validatePath(args.path);
|
|
309
|
+
const diff = await applyFileEdits(validPath, args.edits, args.dryRun);
|
|
310
|
+
const result = args.dryRun
|
|
311
|
+
? capText(diff, limits.maxResultChars, "preview fewer edits at a time")
|
|
312
|
+
: capText(diff, limits.maxResultChars, "read the file with read_text_file rather than applying the edits again", "The edits were applied; only the diff is cut short. ");
|
|
313
|
+
return {
|
|
314
|
+
content: [{ type: "text", text: result }]
|
|
315
|
+
};
|
|
316
|
+
});
|
|
317
|
+
server.registerTool("create_directory", {
|
|
318
|
+
title: "Create Directory",
|
|
319
|
+
description: "Create a new directory or ensure a directory exists. Can create multiple " +
|
|
320
|
+
"nested directories in one operation. If the directory already exists, " +
|
|
321
|
+
"this operation will succeed silently. Perfect for setting up directory " +
|
|
322
|
+
"structures for projects or ensuring required paths exist. Only works within allowed directories.",
|
|
323
|
+
inputSchema: {
|
|
324
|
+
path: z.string()
|
|
325
|
+
},
|
|
326
|
+
annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: false }
|
|
327
|
+
}, async (args) => {
|
|
328
|
+
const validPath = await validatePath(args.path);
|
|
329
|
+
await fs.mkdir(validPath, { recursive: true });
|
|
330
|
+
const text = `Successfully created directory ${args.path}`;
|
|
331
|
+
return {
|
|
332
|
+
content: [{ type: "text", text }]
|
|
333
|
+
};
|
|
334
|
+
});
|
|
335
|
+
server.registerTool("list_directory", {
|
|
336
|
+
title: "List Directory",
|
|
337
|
+
description: "Get a detailed listing of all files and directories in a specified path. " +
|
|
338
|
+
"Results clearly distinguish between files and directories with [FILE] and [DIR] " +
|
|
339
|
+
"prefixes. This tool is essential for understanding directory structure and " +
|
|
340
|
+
"finding specific files within a directory. Only works within allowed directories.",
|
|
341
|
+
inputSchema: {
|
|
342
|
+
path: z.string()
|
|
343
|
+
},
|
|
344
|
+
annotations: { readOnlyHint: true }
|
|
345
|
+
}, async (args) => {
|
|
346
|
+
const validPath = await validatePath(args.path);
|
|
347
|
+
const entries = await fs.readdir(validPath, { withFileTypes: true });
|
|
348
|
+
const formatted = entries
|
|
349
|
+
.map((entry) => `${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`)
|
|
350
|
+
.join("\n");
|
|
351
|
+
const text = capText(formatted, limits.maxResultChars, "list a subdirectory, or use search_files with a pattern");
|
|
352
|
+
return {
|
|
353
|
+
content: [{ type: "text", text }]
|
|
354
|
+
};
|
|
355
|
+
});
|
|
356
|
+
server.registerTool("list_directory_with_sizes", {
|
|
357
|
+
title: "List Directory with Sizes",
|
|
358
|
+
description: "Get a detailed listing of all files and directories in a specified path, including sizes. " +
|
|
359
|
+
"Results clearly distinguish between files and directories with [FILE] and [DIR] " +
|
|
360
|
+
"prefixes. This tool is useful for understanding directory structure and " +
|
|
361
|
+
"finding specific files within a directory. Only works within allowed directories.",
|
|
362
|
+
inputSchema: {
|
|
363
|
+
path: z.string(),
|
|
364
|
+
sortBy: z.enum(["name", "size"]).optional().default("name").describe("Sort entries by name or size")
|
|
365
|
+
},
|
|
366
|
+
annotations: { readOnlyHint: true }
|
|
367
|
+
}, async (args) => {
|
|
368
|
+
const validPath = await validatePath(args.path);
|
|
369
|
+
const entries = await fs.readdir(validPath, { withFileTypes: true });
|
|
370
|
+
// Get detailed information for each entry
|
|
371
|
+
const detailedEntries = await Promise.all(entries.map(async (entry) => {
|
|
372
|
+
const entryPath = path.join(validPath, entry.name);
|
|
373
|
+
try {
|
|
374
|
+
const stats = await fs.stat(entryPath);
|
|
375
|
+
return {
|
|
376
|
+
name: entry.name,
|
|
377
|
+
isDirectory: entry.isDirectory(),
|
|
378
|
+
size: stats.size,
|
|
379
|
+
mtime: stats.mtime
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
catch (error) {
|
|
383
|
+
return {
|
|
384
|
+
name: entry.name,
|
|
385
|
+
isDirectory: entry.isDirectory(),
|
|
386
|
+
size: 0,
|
|
387
|
+
mtime: new Date(0)
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
}));
|
|
391
|
+
// Sort entries based on sortBy parameter
|
|
392
|
+
const sortedEntries = [...detailedEntries].sort((a, b) => {
|
|
393
|
+
if (args.sortBy === 'size') {
|
|
394
|
+
return b.size - a.size; // Descending by size
|
|
395
|
+
}
|
|
396
|
+
// Default sort by name
|
|
397
|
+
return a.name.localeCompare(b.name);
|
|
398
|
+
});
|
|
399
|
+
// Format the output
|
|
400
|
+
const formattedEntries = sortedEntries.map(entry => `${entry.isDirectory ? "[DIR]" : "[FILE]"} ${entry.name.padEnd(30)} ${entry.isDirectory ? "" : formatSize(entry.size).padStart(10)}`);
|
|
401
|
+
// Add summary
|
|
402
|
+
const totalFiles = detailedEntries.filter(e => !e.isDirectory).length;
|
|
403
|
+
const totalDirs = detailedEntries.filter(e => e.isDirectory).length;
|
|
404
|
+
const totalSize = detailedEntries.reduce((sum, entry) => sum + (entry.isDirectory ? 0 : entry.size), 0);
|
|
405
|
+
const summary = [
|
|
406
|
+
"",
|
|
407
|
+
`Total: ${totalFiles} files, ${totalDirs} directories`,
|
|
408
|
+
`Combined size: ${formatSize(totalSize)}`
|
|
409
|
+
];
|
|
410
|
+
const text = capText([...formattedEntries, ...summary].join("\n"), limits.maxResultChars, "list a subdirectory, or use search_files with a pattern");
|
|
411
|
+
const contentBlock = { type: "text", text };
|
|
412
|
+
return {
|
|
413
|
+
content: [contentBlock]
|
|
414
|
+
};
|
|
415
|
+
});
|
|
416
|
+
server.registerTool("directory_tree", {
|
|
417
|
+
title: "Directory Tree",
|
|
418
|
+
description: "Get a recursive tree view of files and directories as a JSON structure. " +
|
|
419
|
+
"Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
|
|
420
|
+
"Files have no children array, while directories always have a children array (which may be empty). " +
|
|
421
|
+
"The output is formatted with 2-space indentation for readability. Only works within allowed directories.",
|
|
422
|
+
inputSchema: {
|
|
423
|
+
path: z.string(),
|
|
424
|
+
excludePatterns: z.array(z.string()).optional().default([])
|
|
425
|
+
},
|
|
426
|
+
annotations: { readOnlyHint: true }
|
|
427
|
+
}, async (args) => {
|
|
428
|
+
const rootPath = args.path;
|
|
429
|
+
async function buildTree(currentPath, excludePatterns = []) {
|
|
430
|
+
const validPath = await validatePath(currentPath);
|
|
431
|
+
const entries = await fs.readdir(validPath, { withFileTypes: true });
|
|
432
|
+
const result = [];
|
|
433
|
+
for (const entry of entries) {
|
|
434
|
+
const relativePath = path.relative(rootPath, path.join(currentPath, entry.name));
|
|
435
|
+
const shouldExclude = excludePatterns.some(pattern => {
|
|
436
|
+
if (pattern.includes('*')) {
|
|
437
|
+
return minimatch(relativePath, pattern, { dot: true });
|
|
438
|
+
}
|
|
439
|
+
// For files: match exact name or as part of path
|
|
440
|
+
// For directories: match as directory path
|
|
441
|
+
return minimatch(relativePath, pattern, { dot: true }) ||
|
|
442
|
+
minimatch(relativePath, `**/${pattern}`, { dot: true }) ||
|
|
443
|
+
minimatch(relativePath, `**/${pattern}/**`, { dot: true });
|
|
444
|
+
});
|
|
445
|
+
if (shouldExclude)
|
|
446
|
+
continue;
|
|
447
|
+
const entryData = {
|
|
448
|
+
name: entry.name,
|
|
449
|
+
type: entry.isDirectory() ? 'directory' : 'file'
|
|
450
|
+
};
|
|
451
|
+
if (entry.isDirectory()) {
|
|
452
|
+
const subPath = path.join(currentPath, entry.name);
|
|
453
|
+
entryData.children = await buildTree(subPath, excludePatterns);
|
|
454
|
+
}
|
|
455
|
+
result.push(entryData);
|
|
456
|
+
}
|
|
457
|
+
return result;
|
|
458
|
+
}
|
|
459
|
+
const treeData = await buildTree(rootPath, args.excludePatterns);
|
|
460
|
+
const text = capText(JSON.stringify(treeData, null, 2), limits.maxResultChars, "pass a deeper path, or add excludePatterns");
|
|
461
|
+
const contentBlock = { type: "text", text };
|
|
462
|
+
return {
|
|
463
|
+
content: [contentBlock]
|
|
464
|
+
};
|
|
465
|
+
});
|
|
466
|
+
server.registerTool("move_file", {
|
|
467
|
+
title: "Move File",
|
|
468
|
+
description: "Move or rename files and directories. Can move files between directories " +
|
|
469
|
+
"and rename them in a single operation. If the destination exists, the " +
|
|
470
|
+
"operation will fail. Works across different directories and can be used " +
|
|
471
|
+
"for simple renaming within the same directory. Both source and destination must be within allowed directories.",
|
|
472
|
+
inputSchema: {
|
|
473
|
+
source: z.string(),
|
|
474
|
+
destination: z.string()
|
|
475
|
+
},
|
|
476
|
+
annotations: { readOnlyHint: false, idempotentHint: false, destructiveHint: false }
|
|
477
|
+
}, async (args) => {
|
|
478
|
+
const validSourcePath = await validatePath(args.source);
|
|
479
|
+
const validDestPath = await validatePath(args.destination);
|
|
480
|
+
await fs.rename(validSourcePath, validDestPath);
|
|
481
|
+
const text = `Successfully moved ${args.source} to ${args.destination}`;
|
|
482
|
+
const contentBlock = { type: "text", text };
|
|
483
|
+
return {
|
|
484
|
+
content: [contentBlock]
|
|
485
|
+
};
|
|
486
|
+
});
|
|
487
|
+
server.registerTool("search_files", {
|
|
488
|
+
title: "Search Files",
|
|
489
|
+
description: "Recursively search for files and directories matching a pattern. " +
|
|
490
|
+
"The patterns should be glob-style patterns that match paths relative to the working directory. " +
|
|
491
|
+
"Use pattern like '*.ext' to match files in current directory, and '**/*.ext' to match files in all subdirectories. " +
|
|
492
|
+
"Returns full paths to all matching items. Great for finding files when you don't know their exact location. " +
|
|
493
|
+
"Only searches within allowed directories.",
|
|
494
|
+
inputSchema: {
|
|
495
|
+
path: z.string(),
|
|
496
|
+
pattern: z.string(),
|
|
497
|
+
excludePatterns: z.array(z.string()).optional().default([])
|
|
498
|
+
},
|
|
499
|
+
annotations: { readOnlyHint: true }
|
|
500
|
+
}, async (args) => {
|
|
501
|
+
const validPath = await validatePath(args.path);
|
|
502
|
+
const results = await searchFilesWithValidation(validPath, args.pattern, allowedDirectories, { excludePatterns: args.excludePatterns });
|
|
503
|
+
const text = results.length > 0
|
|
504
|
+
? capText(results.join("\n"), limits.maxResultChars, "use a narrower pattern or a deeper path, or add excludePatterns")
|
|
505
|
+
: "No matches found";
|
|
506
|
+
return {
|
|
507
|
+
content: [{ type: "text", text }]
|
|
508
|
+
};
|
|
509
|
+
});
|
|
510
|
+
server.registerTool("get_file_info", {
|
|
511
|
+
title: "Get File Info",
|
|
512
|
+
description: "Retrieve detailed metadata about a file or directory. Returns comprehensive " +
|
|
513
|
+
"information including size, creation time, last modified time, permissions, " +
|
|
514
|
+
"and type. This tool is perfect for understanding file characteristics " +
|
|
515
|
+
"without reading the actual content. Only works within allowed directories.",
|
|
516
|
+
inputSchema: {
|
|
517
|
+
path: z.string()
|
|
518
|
+
},
|
|
519
|
+
annotations: { readOnlyHint: true }
|
|
520
|
+
}, async (args) => {
|
|
521
|
+
const validPath = await validatePath(args.path);
|
|
522
|
+
const info = await getFileStats(validPath);
|
|
523
|
+
const text = Object.entries(info)
|
|
524
|
+
.map(([key, value]) => `${key}: ${value}`)
|
|
525
|
+
.join("\n");
|
|
526
|
+
return {
|
|
527
|
+
content: [{ type: "text", text }]
|
|
528
|
+
};
|
|
529
|
+
});
|
|
530
|
+
server.registerTool("list_allowed_directories", {
|
|
531
|
+
title: "List Allowed Directories",
|
|
532
|
+
description: "Returns the list of directories that this server is allowed to access. " +
|
|
533
|
+
"Subdirectories within these allowed directories are also accessible. " +
|
|
534
|
+
"Use this to understand which directories and their nested paths are available " +
|
|
535
|
+
"before trying to access files.",
|
|
536
|
+
inputSchema: {},
|
|
537
|
+
annotations: { readOnlyHint: true }
|
|
538
|
+
}, async () => {
|
|
539
|
+
const text = `Allowed directories:\n${allowedDirectories.join('\n')}`;
|
|
540
|
+
return {
|
|
541
|
+
content: [{ type: "text", text }]
|
|
542
|
+
};
|
|
543
|
+
});
|
|
544
|
+
// Updates allowed directories based on MCP client roots
|
|
545
|
+
async function updateAllowedDirectoriesFromRoots(requestedRoots) {
|
|
546
|
+
const validatedRootDirs = await getValidRootDirectories(requestedRoots);
|
|
547
|
+
if (validatedRootDirs.length > 0) {
|
|
548
|
+
allowedDirectories = [...validatedRootDirs];
|
|
549
|
+
setAllowedDirectories(allowedDirectories); // Update the global state in lib.ts
|
|
550
|
+
console.error(`Updated allowed directories from MCP roots: ${validatedRootDirs.length} valid directories`);
|
|
551
|
+
}
|
|
552
|
+
else {
|
|
553
|
+
console.error("No valid root directories provided by client");
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
// Handles dynamic roots updates during runtime, when client sends "roots/list_changed" notification, server fetches the updated roots and replaces all allowed directories with the new roots.
|
|
557
|
+
server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
|
|
558
|
+
try {
|
|
559
|
+
// Request the updated roots list from the client
|
|
560
|
+
const response = await server.server.listRoots();
|
|
561
|
+
if (response && 'roots' in response) {
|
|
562
|
+
await updateAllowedDirectoriesFromRoots(response.roots);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
console.error("Failed to request roots from client:", error instanceof Error ? error.message : String(error));
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
// Handles post-initialization setup, specifically checking for and fetching MCP roots.
|
|
570
|
+
server.server.oninitialized = async () => {
|
|
571
|
+
const clientCapabilities = server.server.getClientCapabilities();
|
|
572
|
+
if (clientCapabilities?.roots) {
|
|
573
|
+
try {
|
|
574
|
+
const response = await server.server.listRoots();
|
|
575
|
+
if (response && 'roots' in response) {
|
|
576
|
+
await updateAllowedDirectoriesFromRoots(response.roots);
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
console.error("Client returned no roots set, keeping current settings");
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
catch (error) {
|
|
583
|
+
console.error("Failed to request initial roots from client:", error instanceof Error ? error.message : String(error));
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
else {
|
|
587
|
+
if (allowedDirectories.length > 0) {
|
|
588
|
+
console.error("Client does not support MCP Roots, using allowed directories set from server args:", allowedDirectories);
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
throw new Error(`Server cannot operate: No allowed directories available. Server was started without command-line directories and client either does not support MCP roots protocol or provided empty roots. Please either: 1) Start server with directory arguments, or 2) Use a client that supports MCP roots protocol and provides valid root directories.`);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
// Start server
|
|
596
|
+
async function runServer() {
|
|
597
|
+
const transport = new StdioServerTransport();
|
|
598
|
+
await server.connect(transport);
|
|
599
|
+
console.error("Bounded Filesystem MCP Server running on stdio");
|
|
600
|
+
if (allowedDirectories.length === 0) {
|
|
601
|
+
console.error("Started without allowed directories - waiting for client to provide roots via MCP protocol");
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
runServer().catch((error) => {
|
|
605
|
+
console.error("Fatal error running server:", error);
|
|
606
|
+
process.exit(1);
|
|
607
|
+
});
|