@j0hanz/filesystem-mcp 1.2.2 → 1.2.3
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/README.md +11 -0
- package/dist/cli.js +2 -4
- package/dist/completions.js +15 -6
- package/dist/lib/file-operations/glob-engine.js +3 -9
- package/dist/lib/file-operations/read-multiple-files.js +4 -23
- package/dist/lib/file-operations/search-content.js +11 -18
- package/dist/lib/observability.js +4 -4
- package/dist/lib/path-validation.js +22 -9
- package/dist/pkg-info.d.ts +6 -0
- package/dist/pkg-info.js +9 -0
- package/dist/schemas.d.ts +28 -28
- package/dist/schemas.js +26 -26
- package/dist/server/bootstrap.d.ts +4 -0
- package/dist/server/bootstrap.js +117 -0
- package/dist/server/capabilities.d.ts +10 -0
- package/dist/server/capabilities.js +40 -0
- package/dist/server/logging.d.ts +7 -0
- package/dist/server/logging.js +41 -0
- package/dist/server/roots-manager.d.ts +19 -0
- package/dist/server/roots-manager.js +173 -0
- package/dist/server/types.d.ts +4 -0
- package/dist/server/types.js +1 -0
- package/dist/server.d.ts +2 -8
- package/dist/server.js +1 -317
- package/dist/tools/apply-patch.js +3 -2
- package/dist/tools/calculate-hash.js +3 -2
- package/dist/tools/create-directory.js +3 -2
- package/dist/tools/delete-file.js +9 -2
- package/dist/tools/diff-files.js +3 -2
- package/dist/tools/edit-file.js +5 -4
- package/dist/tools/list-directory.js +13 -2
- package/dist/tools/move-file.js +11 -3
- package/dist/tools/read-multiple.js +6 -5
- package/dist/tools/read.js +3 -2
- package/dist/tools/replace-in-files.js +3 -2
- package/dist/tools/roots.js +12 -2
- package/dist/tools/search-content.js +10 -15
- package/dist/tools/search-files.js +13 -9
- package/dist/tools/shared.d.ts +3 -1
- package/dist/tools/shared.js +19 -1
- package/dist/tools/stat-many.js +6 -5
- package/dist/tools/stat.js +4 -3
- package/dist/tools/task-support.js +57 -10
- package/dist/tools/tree.js +15 -2
- package/dist/tools/write-file.js +3 -2
- package/package.json +1 -1
package/dist/schemas.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { ErrorCode } from './
|
|
2
|
+
import { ErrorCode } from './lib/errors.js';
|
|
3
3
|
function isSafeGlobPattern(value) {
|
|
4
4
|
if (value.length === 0)
|
|
5
5
|
return false;
|
|
@@ -90,7 +90,7 @@ const FileInfoSchema = z.strictObject({
|
|
|
90
90
|
mimeType: z.string().optional().describe('MIME type'),
|
|
91
91
|
symlinkTarget: z.string().optional().describe('Target (symlink)'),
|
|
92
92
|
});
|
|
93
|
-
const OperationSummarySchema = z.
|
|
93
|
+
const OperationSummarySchema = z.strictObject({
|
|
94
94
|
total: z.number().describe('Total'),
|
|
95
95
|
succeeded: z.number().describe('Succeeded'),
|
|
96
96
|
failed: z.number().describe('Failed'),
|
|
@@ -293,7 +293,7 @@ export const GetMultipleFileInfoInputSchema = z.strictObject({
|
|
|
293
293
|
.max(100, 'Max 100 files')
|
|
294
294
|
.describe('File/directory paths. e.g. ["src", "lib"]'),
|
|
295
295
|
});
|
|
296
|
-
export const ListAllowedDirectoriesOutputSchema = z.
|
|
296
|
+
export const ListAllowedDirectoriesOutputSchema = z.strictObject({
|
|
297
297
|
ok: z.boolean(),
|
|
298
298
|
directories: z.array(z.string()).optional().describe('Allowed directories'),
|
|
299
299
|
rootsCount: z.number().optional().describe('Number of roots'),
|
|
@@ -303,11 +303,11 @@ export const ListAllowedDirectoriesOutputSchema = z.object({
|
|
|
303
303
|
.describe('Multiple roots configured'),
|
|
304
304
|
error: ErrorSchema.optional(),
|
|
305
305
|
});
|
|
306
|
-
export const ListDirectoryOutputSchema = z.
|
|
306
|
+
export const ListDirectoryOutputSchema = z.strictObject({
|
|
307
307
|
ok: z.boolean(),
|
|
308
308
|
path: z.string().optional(),
|
|
309
309
|
entries: z
|
|
310
|
-
.array(z.
|
|
310
|
+
.array(z.strictObject({
|
|
311
311
|
name: z.string().describe('Entry name'),
|
|
312
312
|
relativePath: z.string().optional(),
|
|
313
313
|
type: FileTypeSchema,
|
|
@@ -327,7 +327,7 @@ export const ListDirectoryOutputSchema = z.object({
|
|
|
327
327
|
symlinksNotFollowed: z.number().optional(),
|
|
328
328
|
error: ErrorSchema.optional(),
|
|
329
329
|
});
|
|
330
|
-
const SearchSummarySchema = z.
|
|
330
|
+
const SearchSummarySchema = z.strictObject({
|
|
331
331
|
totalMatches: z.number().optional().describe('Total matches found'),
|
|
332
332
|
truncated: z.boolean().optional().describe('Results truncated?'),
|
|
333
333
|
resourceUri: z.string().optional().describe('Full results URI'),
|
|
@@ -338,7 +338,7 @@ export const SearchFilesOutputSchema = SearchSummarySchema.extend({
|
|
|
338
338
|
root: z.string().optional().describe('Search root'),
|
|
339
339
|
pattern: z.string().optional().describe('Glob pattern used'),
|
|
340
340
|
results: z
|
|
341
|
-
.array(z.
|
|
341
|
+
.array(z.strictObject({
|
|
342
342
|
path: z.string().describe('Relative path'),
|
|
343
343
|
size: z.number().optional(),
|
|
344
344
|
modified: z.string().optional(),
|
|
@@ -356,7 +356,7 @@ export const SearchContentOutputSchema = SearchSummarySchema.extend({
|
|
|
356
356
|
.describe('Pattern interpretation'),
|
|
357
357
|
caseSensitive: z.boolean().optional().describe('Case-sensitive matching'),
|
|
358
358
|
matches: z
|
|
359
|
-
.array(z.
|
|
359
|
+
.array(z.strictObject({
|
|
360
360
|
file: z.string().describe('Relative path'),
|
|
361
361
|
line: z.number(),
|
|
362
362
|
content: z.string(),
|
|
@@ -379,7 +379,7 @@ export const SearchContentOutputSchema = SearchSummarySchema.extend({
|
|
|
379
379
|
.describe('Lines skipped due to regex timeout'),
|
|
380
380
|
stoppedReason: SearchStopReasonSchema.optional().describe('Why search stopped'),
|
|
381
381
|
});
|
|
382
|
-
export const TreeOutputSchema = z.
|
|
382
|
+
export const TreeOutputSchema = z.strictObject({
|
|
383
383
|
ok: z.boolean(),
|
|
384
384
|
root: z.string().optional(),
|
|
385
385
|
tree: TreeEntrySchema.optional(),
|
|
@@ -388,7 +388,7 @@ export const TreeOutputSchema = z.object({
|
|
|
388
388
|
totalEntries: z.number().optional(),
|
|
389
389
|
error: ErrorSchema.optional(),
|
|
390
390
|
});
|
|
391
|
-
const ReadResultSchema = z.
|
|
391
|
+
const ReadResultSchema = z.strictObject({
|
|
392
392
|
content: z.string().optional().describe('Content'),
|
|
393
393
|
truncated: z.boolean().optional().describe('Truncated?'),
|
|
394
394
|
resourceUri: z.string().optional().describe('Full content URI'),
|
|
@@ -414,21 +414,21 @@ const ReadMultipleFileResultSchema = ReadResultSchema.extend({
|
|
|
414
414
|
maxTotalSize: z.number().optional().describe('Max total size budget'),
|
|
415
415
|
error: z.string().optional().describe('Error message'),
|
|
416
416
|
});
|
|
417
|
-
export const ReadMultipleFilesOutputSchema = z.
|
|
417
|
+
export const ReadMultipleFilesOutputSchema = z.strictObject({
|
|
418
418
|
ok: z.boolean(),
|
|
419
419
|
results: z.array(ReadMultipleFileResultSchema).optional(),
|
|
420
420
|
summary: OperationSummarySchema.optional(),
|
|
421
421
|
error: ErrorSchema.optional(),
|
|
422
422
|
});
|
|
423
|
-
export const GetFileInfoOutputSchema = z.
|
|
423
|
+
export const GetFileInfoOutputSchema = z.strictObject({
|
|
424
424
|
ok: z.boolean(),
|
|
425
425
|
info: FileInfoSchema.optional(),
|
|
426
426
|
error: ErrorSchema.optional(),
|
|
427
427
|
});
|
|
428
|
-
export const GetMultipleFileInfoOutputSchema = z.
|
|
428
|
+
export const GetMultipleFileInfoOutputSchema = z.strictObject({
|
|
429
429
|
ok: z.boolean(),
|
|
430
430
|
results: z
|
|
431
|
-
.array(z.
|
|
431
|
+
.array(z.strictObject({
|
|
432
432
|
path: z.string(),
|
|
433
433
|
info: FileInfoSchema.optional(),
|
|
434
434
|
error: z.string().optional(),
|
|
@@ -440,7 +440,7 @@ export const GetMultipleFileInfoOutputSchema = z.object({
|
|
|
440
440
|
export const CreateDirectoryInputSchema = z.strictObject({
|
|
441
441
|
path: RequiredPathSchema.describe(DESC_PATH_REQUIRED),
|
|
442
442
|
});
|
|
443
|
-
export const CreateDirectoryOutputSchema = z.
|
|
443
|
+
export const CreateDirectoryOutputSchema = z.strictObject({
|
|
444
444
|
ok: z.boolean(),
|
|
445
445
|
path: z.string().optional(),
|
|
446
446
|
error: ErrorSchema.optional(),
|
|
@@ -449,7 +449,7 @@ export const WriteFileInputSchema = z.strictObject({
|
|
|
449
449
|
path: RequiredPathSchema.describe(DESC_PATH_REQUIRED),
|
|
450
450
|
content: z.string().describe('Content to write'),
|
|
451
451
|
});
|
|
452
|
-
export const WriteFileOutputSchema = z.
|
|
452
|
+
export const WriteFileOutputSchema = z.strictObject({
|
|
453
453
|
ok: z.boolean(),
|
|
454
454
|
path: z.string().optional(),
|
|
455
455
|
bytesWritten: z.number().optional(),
|
|
@@ -458,7 +458,7 @@ export const WriteFileOutputSchema = z.object({
|
|
|
458
458
|
export const EditFileInputSchema = z.strictObject({
|
|
459
459
|
path: RequiredPathSchema.describe(DESC_PATH_REQUIRED),
|
|
460
460
|
edits: z
|
|
461
|
-
.array(z.
|
|
461
|
+
.array(z.strictObject({
|
|
462
462
|
oldText: z
|
|
463
463
|
.string()
|
|
464
464
|
.describe('Exact literal string to replace — must match character-for-character including whitespace and indentation. Include 3–5 lines of surrounding context to uniquely identify the location.'),
|
|
@@ -474,7 +474,7 @@ export const EditFileInputSchema = z.strictObject({
|
|
|
474
474
|
.default(false)
|
|
475
475
|
.describe('Preview edits without writing. Check unmatchedEdits in the response to verify all oldText values were found.'),
|
|
476
476
|
});
|
|
477
|
-
export const EditFileOutputSchema = z.
|
|
477
|
+
export const EditFileOutputSchema = z.strictObject({
|
|
478
478
|
ok: z.boolean(),
|
|
479
479
|
path: z.string().optional(),
|
|
480
480
|
appliedEdits: z.number().optional(),
|
|
@@ -492,7 +492,7 @@ export const MoveFileInputSchema = z.strictObject({
|
|
|
492
492
|
source: RequiredPathSchema.describe('Path to move'),
|
|
493
493
|
destination: RequiredPathSchema.describe('New path'),
|
|
494
494
|
});
|
|
495
|
-
export const MoveFileOutputSchema = z.
|
|
495
|
+
export const MoveFileOutputSchema = z.strictObject({
|
|
496
496
|
ok: z.boolean(),
|
|
497
497
|
source: z.string().optional(),
|
|
498
498
|
destination: z.string().optional(),
|
|
@@ -511,7 +511,7 @@ export const DeleteFileInputSchema = z.strictObject({
|
|
|
511
511
|
.default(false)
|
|
512
512
|
.describe('No error if missing'),
|
|
513
513
|
});
|
|
514
|
-
export const DeleteFileOutputSchema = z.
|
|
514
|
+
export const DeleteFileOutputSchema = z.strictObject({
|
|
515
515
|
ok: z.boolean(),
|
|
516
516
|
path: z.string().optional(),
|
|
517
517
|
error: ErrorSchema.optional(),
|
|
@@ -519,7 +519,7 @@ export const DeleteFileOutputSchema = z.object({
|
|
|
519
519
|
export const CalculateHashInputSchema = z.strictObject({
|
|
520
520
|
path: RequiredPathSchema.describe(DESC_PATH_REQUIRED),
|
|
521
521
|
});
|
|
522
|
-
export const CalculateHashOutputSchema = z.
|
|
522
|
+
export const CalculateHashOutputSchema = z.strictObject({
|
|
523
523
|
ok: z.boolean(),
|
|
524
524
|
path: z.string().optional(),
|
|
525
525
|
hash: z.string().optional().describe('SHA-256 hash'),
|
|
@@ -551,7 +551,7 @@ export const DiffFilesInputSchema = z.strictObject({
|
|
|
551
551
|
.default(false)
|
|
552
552
|
.describe('Strip trailing carriage returns before diffing'),
|
|
553
553
|
});
|
|
554
|
-
export const DiffFilesOutputSchema = z.
|
|
554
|
+
export const DiffFilesOutputSchema = z.strictObject({
|
|
555
555
|
ok: z.boolean(),
|
|
556
556
|
diff: z.string().optional().describe('Unified diff content'),
|
|
557
557
|
isIdentical: z.boolean().optional().describe('True if files are identical'),
|
|
@@ -582,7 +582,7 @@ export const ApplyPatchInputSchema = z.strictObject({
|
|
|
582
582
|
.default(false)
|
|
583
583
|
.describe('Validate the patch can be applied without writing. Check `applied` in the response before committing.'),
|
|
584
584
|
});
|
|
585
|
-
export const ApplyPatchOutputSchema = z.
|
|
585
|
+
export const ApplyPatchOutputSchema = z.strictObject({
|
|
586
586
|
ok: z.boolean(),
|
|
587
587
|
path: z.string().optional(),
|
|
588
588
|
applied: z.boolean().optional(),
|
|
@@ -614,21 +614,21 @@ export const SearchAndReplaceInputSchema = z.strictObject({
|
|
|
614
614
|
.default(false)
|
|
615
615
|
.describe('Preview matches without writing. Check changedFiles and matches in the response before committing.'),
|
|
616
616
|
});
|
|
617
|
-
export const SearchAndReplaceOutputSchema = z.
|
|
617
|
+
export const SearchAndReplaceOutputSchema = z.strictObject({
|
|
618
618
|
ok: z.boolean(),
|
|
619
619
|
matches: z.number().optional().describe('Total matches found'),
|
|
620
620
|
filesChanged: z.number().optional().describe('Files modified'),
|
|
621
621
|
processedFiles: z.number().optional().describe('Files processed'),
|
|
622
622
|
failedFiles: z.number().optional().describe('Files skipped due to errors'),
|
|
623
623
|
failures: z
|
|
624
|
-
.array(z.
|
|
624
|
+
.array(z.strictObject({
|
|
625
625
|
path: z.string().describe('File path'),
|
|
626
626
|
error: z.string().describe('Error message'),
|
|
627
627
|
}))
|
|
628
628
|
.optional()
|
|
629
629
|
.describe('Sample of per-file errors'),
|
|
630
630
|
changedFiles: z
|
|
631
|
-
.array(z.
|
|
631
|
+
.array(z.strictObject({
|
|
632
632
|
path: z.string().describe('File path'),
|
|
633
633
|
matches: z.number().describe('Matches in file'),
|
|
634
634
|
}))
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import type { ServerOptions } from './types.js';
|
|
3
|
+
export declare function createServer(options?: ServerOptions): Promise<McpServer>;
|
|
4
|
+
export declare function startServer(server: McpServer): Promise<void>;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { InMemoryTaskMessageQueue, InMemoryTaskStore, } from '@modelcontextprotocol/sdk/experimental/tasks/stores/in-memory.js';
|
|
5
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
6
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
7
|
+
import { SetLevelRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
8
|
+
import { registerCompletions } from '../completions.js';
|
|
9
|
+
import { formatUnknownErrorMessage } from '../lib/errors.js';
|
|
10
|
+
import { createInMemoryResourceStore } from '../lib/resource-store.js';
|
|
11
|
+
import { pkgInfo } from '../pkg-info.js';
|
|
12
|
+
import { registerGetHelpPrompt } from '../prompts.js';
|
|
13
|
+
import { registerInstructionResource, registerResultResources, } from '../resources.js';
|
|
14
|
+
import { registerAllTools } from '../tools.js';
|
|
15
|
+
import { withDefaultIcons } from '../tools/shared.js';
|
|
16
|
+
import { buildServerCapabilities, supportsTaskToolRequests, } from './capabilities.js';
|
|
17
|
+
import { createLoggingState } from './logging.js';
|
|
18
|
+
import { RootsManager } from './roots-manager.js';
|
|
19
|
+
const { version: SERVER_VERSION, description: SERVER_DESCRIPTION, homepage: SERVER_HOMEPAGE, } = pkgInfo;
|
|
20
|
+
const rootsManagers = new WeakMap();
|
|
21
|
+
function getRootsManager(server) {
|
|
22
|
+
const manager = rootsManagers.get(server);
|
|
23
|
+
if (!manager) {
|
|
24
|
+
throw new Error('Roots manager not initialized for server instance');
|
|
25
|
+
}
|
|
26
|
+
return manager;
|
|
27
|
+
}
|
|
28
|
+
async function loadServerInstructions() {
|
|
29
|
+
const defaultInstructions = `
|
|
30
|
+
Filesystem MCP Instructions
|
|
31
|
+
(Detailed instructions failed to load - check logs)
|
|
32
|
+
`;
|
|
33
|
+
try {
|
|
34
|
+
const currentDir = path.dirname(fileURLToPath(import.meta.url));
|
|
35
|
+
return await fs.readFile(path.join(currentDir, '../instructions.md'), 'utf-8');
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
console.error('[WARNING] Failed to load instructions.md:', formatUnknownErrorMessage(error));
|
|
39
|
+
return defaultInstructions;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function getLocalIconInfo() {
|
|
43
|
+
const name = 'logo.svg';
|
|
44
|
+
const mime = 'image/svg+xml';
|
|
45
|
+
const candidates = [`../assets/${name}`, `../../assets/${name}`];
|
|
46
|
+
for (const candidate of candidates) {
|
|
47
|
+
try {
|
|
48
|
+
const iconPath = new URL(candidate, import.meta.url);
|
|
49
|
+
const buffer = await fs.readFile(iconPath);
|
|
50
|
+
return {
|
|
51
|
+
src: `data:${mime};base64,${buffer.toString('base64')}`,
|
|
52
|
+
mimeType: mime,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// Try next candidate.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
export async function createServer(options = {}) {
|
|
62
|
+
const resourceStore = createInMemoryResourceStore();
|
|
63
|
+
const serverInstructions = await loadServerInstructions();
|
|
64
|
+
const localIcon = await getLocalIconInfo();
|
|
65
|
+
const taskToolSupport = supportsTaskToolRequests();
|
|
66
|
+
const serverConfig = {
|
|
67
|
+
capabilities: buildServerCapabilities({
|
|
68
|
+
enablePromptListChanged: false,
|
|
69
|
+
enableTaskToolRequests: taskToolSupport,
|
|
70
|
+
}),
|
|
71
|
+
};
|
|
72
|
+
if (taskToolSupport) {
|
|
73
|
+
serverConfig.taskStore = new InMemoryTaskStore();
|
|
74
|
+
serverConfig.taskMessageQueue = new InMemoryTaskMessageQueue();
|
|
75
|
+
}
|
|
76
|
+
if (serverInstructions) {
|
|
77
|
+
serverConfig.instructions = serverInstructions;
|
|
78
|
+
}
|
|
79
|
+
const server = new McpServer(withDefaultIcons({
|
|
80
|
+
name: 'filesystem-mcp',
|
|
81
|
+
title: 'Filesystem MCP',
|
|
82
|
+
version: SERVER_VERSION,
|
|
83
|
+
...(SERVER_DESCRIPTION ? { description: SERVER_DESCRIPTION } : {}),
|
|
84
|
+
...(SERVER_HOMEPAGE ? { websiteUrl: SERVER_HOMEPAGE } : {}),
|
|
85
|
+
}, localIcon), serverConfig);
|
|
86
|
+
const loggingState = createLoggingState('debug');
|
|
87
|
+
const rootsManager = new RootsManager(options, loggingState);
|
|
88
|
+
rootsManagers.set(server, rootsManager);
|
|
89
|
+
server.server.setRequestHandler(SetLevelRequestSchema, (req) => {
|
|
90
|
+
loggingState.minimumLevel = req.params.level;
|
|
91
|
+
return {};
|
|
92
|
+
});
|
|
93
|
+
registerInstructionResource(server, serverInstructions, localIcon);
|
|
94
|
+
registerGetHelpPrompt(server, serverInstructions, localIcon);
|
|
95
|
+
registerResultResources(server, resourceStore, localIcon);
|
|
96
|
+
registerCompletions(server);
|
|
97
|
+
registerAllTools(server, {
|
|
98
|
+
resourceStore,
|
|
99
|
+
isInitialized: () => rootsManager.isInitialized(),
|
|
100
|
+
...(localIcon ? { iconInfo: localIcon } : {}),
|
|
101
|
+
});
|
|
102
|
+
return server;
|
|
103
|
+
}
|
|
104
|
+
export async function startServer(server) {
|
|
105
|
+
const transport = new StdioServerTransport();
|
|
106
|
+
const rootsManager = getRootsManager(server);
|
|
107
|
+
rootsManager.registerHandlers(server);
|
|
108
|
+
await rootsManager.recomputeAllowedDirectories();
|
|
109
|
+
await server.connect(transport);
|
|
110
|
+
const transportAny = transport;
|
|
111
|
+
const sdkOnClose = transportAny.onclose;
|
|
112
|
+
transportAny.onclose = () => {
|
|
113
|
+
rootsManager.destroy();
|
|
114
|
+
sdkOnClose?.();
|
|
115
|
+
};
|
|
116
|
+
rootsManager.logMissingDirectoriesIfNeeded(server);
|
|
117
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
export interface CapabilityOptions {
|
|
3
|
+
enablePromptListChanged?: boolean;
|
|
4
|
+
enableTaskToolRequests?: boolean;
|
|
5
|
+
}
|
|
6
|
+
type ServerCapabilities = NonNullable<ConstructorParameters<typeof McpServer>[1]>['capabilities'];
|
|
7
|
+
type NonOptionalServerCapabilities = NonNullable<ServerCapabilities>;
|
|
8
|
+
export declare function buildServerCapabilities(options?: CapabilityOptions): NonOptionalServerCapabilities;
|
|
9
|
+
export declare function supportsTaskToolRequests(): boolean;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
let cachedTaskToolSupport;
|
|
3
|
+
function detectTaskToolSupport() {
|
|
4
|
+
if (cachedTaskToolSupport !== undefined) {
|
|
5
|
+
return cachedTaskToolSupport;
|
|
6
|
+
}
|
|
7
|
+
try {
|
|
8
|
+
const probe = new McpServer({
|
|
9
|
+
name: 'filesystem-mcp-capability-probe',
|
|
10
|
+
version: '0.0.0',
|
|
11
|
+
}, { capabilities: { tools: {} } });
|
|
12
|
+
cachedTaskToolSupport =
|
|
13
|
+
typeof probe.experimental.tasks.registerToolTask === 'function';
|
|
14
|
+
void probe.close().catch(() => { });
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
cachedTaskToolSupport = false;
|
|
18
|
+
}
|
|
19
|
+
return cachedTaskToolSupport;
|
|
20
|
+
}
|
|
21
|
+
export function buildServerCapabilities(options = {}) {
|
|
22
|
+
const capabilities = {
|
|
23
|
+
logging: {},
|
|
24
|
+
resources: {},
|
|
25
|
+
tools: {},
|
|
26
|
+
prompts: options.enablePromptListChanged ? { listChanged: true } : {},
|
|
27
|
+
completions: {},
|
|
28
|
+
};
|
|
29
|
+
if (options.enableTaskToolRequests) {
|
|
30
|
+
capabilities.tasks = {
|
|
31
|
+
list: {},
|
|
32
|
+
cancel: {},
|
|
33
|
+
requests: { tools: { call: {} } },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
return capabilities;
|
|
37
|
+
}
|
|
38
|
+
export function supportsTaskToolRequests() {
|
|
39
|
+
return detectTaskToolSupport();
|
|
40
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js';
|
|
3
|
+
export interface LoggingState {
|
|
4
|
+
minimumLevel: LoggingLevel;
|
|
5
|
+
}
|
|
6
|
+
export declare function createLoggingState(minimumLevel?: LoggingLevel): LoggingState;
|
|
7
|
+
export declare function logToMcp(server: McpServer | undefined, level: LoggingLevel, data: string, minLevel?: LoggingLevel): void;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { formatUnknownErrorMessage } from '../lib/errors.js';
|
|
2
|
+
import { isRecord } from '../lib/type-guards.js';
|
|
3
|
+
const MCP_LOGGER_NAME = 'filesystem-mcp';
|
|
4
|
+
const LOG_LEVEL_ORDER = {
|
|
5
|
+
debug: 0,
|
|
6
|
+
info: 1,
|
|
7
|
+
notice: 2,
|
|
8
|
+
warning: 3,
|
|
9
|
+
error: 4,
|
|
10
|
+
critical: 5,
|
|
11
|
+
alert: 6,
|
|
12
|
+
emergency: 7,
|
|
13
|
+
};
|
|
14
|
+
export function createLoggingState(minimumLevel = 'debug') {
|
|
15
|
+
return { minimumLevel };
|
|
16
|
+
}
|
|
17
|
+
function canSendMcpLogs(server) {
|
|
18
|
+
const capabilities = server.server.getClientCapabilities();
|
|
19
|
+
if (!isRecord(capabilities))
|
|
20
|
+
return false;
|
|
21
|
+
if (!('logging' in capabilities))
|
|
22
|
+
return false;
|
|
23
|
+
return capabilities.logging !== null;
|
|
24
|
+
}
|
|
25
|
+
export function logToMcp(server, level, data, minLevel = 'debug') {
|
|
26
|
+
if (LOG_LEVEL_ORDER[level] < LOG_LEVEL_ORDER[minLevel]) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (!server || !canSendMcpLogs(server)) {
|
|
30
|
+
console.error(data);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const params = {
|
|
34
|
+
level,
|
|
35
|
+
logger: MCP_LOGGER_NAME,
|
|
36
|
+
data,
|
|
37
|
+
};
|
|
38
|
+
void server.sendLoggingMessage(params).catch((error) => {
|
|
39
|
+
console.error(`Failed to send MCP log: ${level} | ${data}`, formatUnknownErrorMessage(error));
|
|
40
|
+
});
|
|
41
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { type LoggingState } from './logging.js';
|
|
3
|
+
import type { ServerOptions } from './types.js';
|
|
4
|
+
export declare class RootsManager {
|
|
5
|
+
private rootsUpdateTimeout;
|
|
6
|
+
private rootDirectories;
|
|
7
|
+
private clientInitialized;
|
|
8
|
+
private readonly options;
|
|
9
|
+
readonly loggingState: LoggingState;
|
|
10
|
+
constructor(options: ServerOptions, loggingState: LoggingState);
|
|
11
|
+
isInitialized(): boolean;
|
|
12
|
+
destroy(): void;
|
|
13
|
+
logMissingDirectoriesIfNeeded(server: McpServer): void;
|
|
14
|
+
registerHandlers(server: McpServer): void;
|
|
15
|
+
recomputeAllowedDirectories(): Promise<void>;
|
|
16
|
+
private scheduleRootsUpdate;
|
|
17
|
+
private logMissingDirectories;
|
|
18
|
+
private updateRootsFromClient;
|
|
19
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import { InitializedNotificationSchema, RootsListChangedNotificationSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { formatUnknownErrorMessage } from '../lib/errors.js';
|
|
5
|
+
import { assertNotAborted, createTimedAbortSignal, withAbort, } from '../lib/fs-helpers.js';
|
|
6
|
+
import { getAllowedDirectories, getValidRootDirectories, isPathWithinDirectories, normalizePath, setAllowedDirectoriesResolved, } from '../lib/path-validation.js';
|
|
7
|
+
import { isRecord } from '../lib/type-guards.js';
|
|
8
|
+
import { logToMcp } from './logging.js';
|
|
9
|
+
const ROOTS_TIMEOUT_MS = 5000;
|
|
10
|
+
const ROOTS_DEBOUNCE_MS = 100;
|
|
11
|
+
function normalizeCLIDirectories(dirs) {
|
|
12
|
+
const normalized = [];
|
|
13
|
+
for (const dir of dirs) {
|
|
14
|
+
const trimmed = dir.trim();
|
|
15
|
+
if (trimmed.length === 0)
|
|
16
|
+
continue;
|
|
17
|
+
normalized.push(normalizePath(trimmed));
|
|
18
|
+
}
|
|
19
|
+
return normalized;
|
|
20
|
+
}
|
|
21
|
+
const RootSchema = z.strictObject({
|
|
22
|
+
uri: z.string(),
|
|
23
|
+
name: z.string().optional(),
|
|
24
|
+
});
|
|
25
|
+
const RootsResponseSchema = z.object({
|
|
26
|
+
roots: z.array(RootSchema).optional(),
|
|
27
|
+
});
|
|
28
|
+
function isRoot(value) {
|
|
29
|
+
return isRecord(value) && typeof value['uri'] === 'string';
|
|
30
|
+
}
|
|
31
|
+
function normalizeRoot(root) {
|
|
32
|
+
return root.name ? { uri: root.uri, name: root.name } : { uri: root.uri };
|
|
33
|
+
}
|
|
34
|
+
function extractRoots(value) {
|
|
35
|
+
const parsed = RootsResponseSchema.safeParse(value);
|
|
36
|
+
if (!parsed.success || !parsed.data.roots) {
|
|
37
|
+
return [];
|
|
38
|
+
}
|
|
39
|
+
const roots = [];
|
|
40
|
+
for (const root of parsed.data.roots) {
|
|
41
|
+
if (isRoot(root)) {
|
|
42
|
+
roots.push(normalizeRoot(root));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return roots;
|
|
46
|
+
}
|
|
47
|
+
async function resolveRootDirectories(roots) {
|
|
48
|
+
if (roots.length === 0)
|
|
49
|
+
return [];
|
|
50
|
+
const { signal, cleanup } = createTimedAbortSignal(undefined, ROOTS_TIMEOUT_MS);
|
|
51
|
+
try {
|
|
52
|
+
return await getValidRootDirectories(roots, signal);
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
cleanup();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function isRootWithinBaseline(normalizedRoot, baseline, signal) {
|
|
59
|
+
if (!isPathWithinDirectories(normalizedRoot, baseline)) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
assertNotAborted(signal);
|
|
64
|
+
const realPath = await withAbort(fs.realpath(normalizedRoot), signal);
|
|
65
|
+
const normalizedReal = normalizePath(realPath);
|
|
66
|
+
return isPathWithinDirectories(normalizedReal, baseline);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function filterRootsWithinBaseline(roots, baseline, signal) {
|
|
73
|
+
const normalizedBaseline = normalizeCLIDirectories(baseline);
|
|
74
|
+
const normalizedRoots = roots.map(normalizePath);
|
|
75
|
+
if (normalizedRoots.length === 0)
|
|
76
|
+
return [];
|
|
77
|
+
const results = await Promise.allSettled(normalizedRoots.map((normalizedRoot) => isRootWithinBaseline(normalizedRoot, normalizedBaseline, signal)));
|
|
78
|
+
return normalizedRoots.filter((_, i) => {
|
|
79
|
+
const result = results[i];
|
|
80
|
+
return result?.status === 'fulfilled' && result.value;
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
export class RootsManager {
|
|
84
|
+
rootsUpdateTimeout;
|
|
85
|
+
rootDirectories = [];
|
|
86
|
+
clientInitialized = false;
|
|
87
|
+
options;
|
|
88
|
+
loggingState;
|
|
89
|
+
constructor(options, loggingState) {
|
|
90
|
+
this.options = options;
|
|
91
|
+
this.loggingState = loggingState;
|
|
92
|
+
}
|
|
93
|
+
isInitialized() {
|
|
94
|
+
return this.clientInitialized;
|
|
95
|
+
}
|
|
96
|
+
destroy() {
|
|
97
|
+
if (this.rootsUpdateTimeout) {
|
|
98
|
+
clearTimeout(this.rootsUpdateTimeout);
|
|
99
|
+
this.rootsUpdateTimeout = undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
logMissingDirectoriesIfNeeded(server) {
|
|
103
|
+
if (getAllowedDirectories().length === 0) {
|
|
104
|
+
this.logMissingDirectories(server);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
registerHandlers(server) {
|
|
108
|
+
server.server.setNotificationHandler(InitializedNotificationSchema, async () => {
|
|
109
|
+
this.clientInitialized = true;
|
|
110
|
+
await this.updateRootsFromClient(server);
|
|
111
|
+
});
|
|
112
|
+
server.server.setNotificationHandler(RootsListChangedNotificationSchema, () => {
|
|
113
|
+
if (!this.clientInitialized)
|
|
114
|
+
return;
|
|
115
|
+
this.scheduleRootsUpdate(server);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
async recomputeAllowedDirectories() {
|
|
119
|
+
const cliAllowedDirs = normalizeCLIDirectories(this.options.cliAllowedDirs ?? []);
|
|
120
|
+
const allowCwd = this.options.allowCwd === true;
|
|
121
|
+
const allowCwdDirs = allowCwd ? [normalizePath(process.cwd())] : [];
|
|
122
|
+
const baseline = [...cliAllowedDirs, ...allowCwdDirs];
|
|
123
|
+
const { signal, cleanup } = createTimedAbortSignal(undefined, ROOTS_TIMEOUT_MS);
|
|
124
|
+
try {
|
|
125
|
+
const rootsToInclude = baseline.length > 0
|
|
126
|
+
? await filterRootsWithinBaseline(this.rootDirectories, baseline, signal)
|
|
127
|
+
: this.rootDirectories;
|
|
128
|
+
const combined = [...baseline, ...rootsToInclude];
|
|
129
|
+
await setAllowedDirectoriesResolved(combined, signal);
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
cleanup();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
scheduleRootsUpdate(server) {
|
|
136
|
+
if (this.rootsUpdateTimeout) {
|
|
137
|
+
this.rootsUpdateTimeout.refresh();
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
this.rootsUpdateTimeout = setTimeout(() => {
|
|
141
|
+
this.rootsUpdateTimeout = undefined;
|
|
142
|
+
void this.updateRootsFromClient(server);
|
|
143
|
+
}, ROOTS_DEBOUNCE_MS);
|
|
144
|
+
this.rootsUpdateTimeout.unref();
|
|
145
|
+
}
|
|
146
|
+
logMissingDirectories(server) {
|
|
147
|
+
if (this.options.allowCwd) {
|
|
148
|
+
logToMcp(server, 'notice', 'No allowed directories specified. Using the current working directory as an allowed directory.', this.loggingState.minimumLevel);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
logToMcp(server, 'warning', 'No allowed directories specified. Please provide directories as command-line arguments or enable --allow-cwd to use the current working directory.', this.loggingState.minimumLevel);
|
|
152
|
+
}
|
|
153
|
+
async updateRootsFromClient(server) {
|
|
154
|
+
try {
|
|
155
|
+
const clientCapabilities = server.server.getClientCapabilities();
|
|
156
|
+
if (!clientCapabilities?.roots) {
|
|
157
|
+
this.rootDirectories = [];
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const rootsResult = await server.server.listRoots(undefined, {
|
|
161
|
+
timeout: ROOTS_TIMEOUT_MS,
|
|
162
|
+
});
|
|
163
|
+
const roots = extractRoots(rootsResult);
|
|
164
|
+
this.rootDirectories = await resolveRootDirectories(roots);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
logToMcp(server, 'debug', `[DEBUG] MCP Roots protocol unavailable or failed: ${formatUnknownErrorMessage(error)}`, this.loggingState.minimumLevel);
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
await this.recomputeAllowedDirectories();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/server.d.ts
CHANGED
|
@@ -1,8 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
allowCwd?: boolean;
|
|
4
|
-
cliAllowedDirs?: string[];
|
|
5
|
-
}
|
|
6
|
-
export declare function createServer(options?: ServerOptions): Promise<McpServer>;
|
|
7
|
-
export declare function startServer(server: McpServer): Promise<void>;
|
|
8
|
-
export {};
|
|
1
|
+
export { createServer, startServer } from './server/bootstrap.js';
|
|
2
|
+
export type { ServerOptions } from './server/types.js';
|