@j0hanz/filesystem-mcp 1.14.0 → 1.14.1

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.
Files changed (66) hide show
  1. package/README.md +47 -47
  2. package/dist/cli.js +2 -2
  3. package/dist/completions.js +54 -51
  4. package/dist/config.d.ts +13 -13
  5. package/dist/config.js +12 -12
  6. package/dist/index.js +1 -1
  7. package/dist/lib/abort.d.ts +7 -0
  8. package/dist/lib/abort.js +81 -0
  9. package/dist/lib/constants.d.ts +3 -1
  10. package/dist/lib/constants.js +8 -2
  11. package/dist/lib/errors.d.ts +7 -3
  12. package/dist/lib/errors.js +59 -39
  13. package/dist/lib/file-operations/core.d.ts +3 -3
  14. package/dist/lib/file-operations/core.js +23 -20
  15. package/dist/lib/file-operations/metadata.d.ts +2 -2
  16. package/dist/lib/file-operations/metadata.js +60 -19
  17. package/dist/lib/file-operations/search.js +83 -84
  18. package/dist/lib/file-operations/traversal.js +13 -15
  19. package/dist/lib/fs-helpers.d.ts +3 -10
  20. package/dist/lib/fs-helpers.js +20 -98
  21. package/dist/lib/globs.js +1 -1
  22. package/dist/lib/logger.d.ts +28 -0
  23. package/dist/lib/logger.js +91 -0
  24. package/dist/lib/observability.d.ts +7 -0
  25. package/dist/lib/observability.js +19 -9
  26. package/dist/lib/paths.js +55 -55
  27. package/dist/lib/resource-store.js +4 -4
  28. package/dist/lib/utils.d.ts +0 -12
  29. package/dist/lib/utils.js +0 -13
  30. package/dist/resources/generated-instructions.js +40 -31
  31. package/dist/resources/tool-catalog.js +32 -26
  32. package/dist/resources/tool-info.js +34 -29
  33. package/dist/resources/workflows.js +39 -18
  34. package/dist/resources.d.ts +1 -1
  35. package/dist/resources.js +4 -4
  36. package/dist/schemas.d.ts +66 -66
  37. package/dist/schemas.js +21 -44
  38. package/dist/server/bootstrap.d.ts +12 -11
  39. package/dist/server/bootstrap.js +95 -86
  40. package/dist/server/roots-manager.d.ts +5 -2
  41. package/dist/server/roots-manager.js +8 -6
  42. package/dist/server/task-store.d.ts +10 -0
  43. package/dist/server/task-store.js +73 -0
  44. package/dist/tools/apply-patch.js +26 -18
  45. package/dist/tools/calculate-hash.js +11 -22
  46. package/dist/tools/create-directory.js +10 -8
  47. package/dist/tools/delete-file.js +17 -15
  48. package/dist/tools/diff-files.js +15 -15
  49. package/dist/tools/edit-file.js +7 -4
  50. package/dist/tools/list-directory.js +6 -6
  51. package/dist/tools/move-file.js +98 -81
  52. package/dist/tools/read-multiple.js +4 -4
  53. package/dist/tools/read.js +5 -5
  54. package/dist/tools/replace-in-files.js +20 -23
  55. package/dist/tools/roots.js +1 -1
  56. package/dist/tools/search-content.js +32 -41
  57. package/dist/tools/search-files.js +54 -41
  58. package/dist/tools/shared.d.ts +3 -0
  59. package/dist/tools/shared.js +70 -28
  60. package/dist/tools/stat-many.js +11 -7
  61. package/dist/tools/stat.js +4 -4
  62. package/dist/tools/task-support.d.ts +10 -9
  63. package/dist/tools/task-support.js +94 -23
  64. package/dist/tools/tree.js +3 -3
  65. package/dist/tools/write-file.js +10 -7
  66. package/package.json +9 -9
@@ -1,10 +1,11 @@
1
+ import { CallToolResultSchema, } from '@modelcontextprotocol/sdk/types.js';
1
2
  import { AsyncLocalStorage } from 'node:async_hooks';
2
3
  import { channel } from 'node:diagnostics_channel';
3
4
  import { performance } from 'node:perf_hooks';
4
5
  import { format } from 'node:util';
5
- import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
6
- import { DEFAULT_TASK_TTL_MS, MAX_CONCURRENT_TASKS, MAX_TASK_TTL_MS, } from '../lib/constants.js';
6
+ import { DEFAULT_TASK_TTL_MS, MAX_CONCURRENT_TASKS, MAX_TASK_TTL_MS, TASK_CANCEL_POLL_MS, TASK_POLL_INTERVAL_MS, } from '../lib/constants.js';
7
7
  import { ErrorCode, McpError } from '../lib/errors.js';
8
+ import { Logger } from '../lib/logger.js';
8
9
  import { isRecord } from '../lib/utils.js';
9
10
  import { buildToolErrorResponse, maybeStripStructuredContentFromResult, withDefaultIcons, } from './shared.js';
10
11
  const taskContext = new AsyncLocalStorage();
@@ -50,6 +51,7 @@ function hasTaskToolCapability(server) {
50
51
  isRecord(tasks.requests.tools.call));
51
52
  }
52
53
  const TASK_STATUS_NOTIFICATION_METHOD = 'notifications/tasks/status';
54
+ const TASK_CREATED_NOTIFICATION_METHOD = 'notifications/tasks/created';
53
55
  function isRequestTaskStore(value) {
54
56
  return (isRecord(value) &&
55
57
  typeof value.createTask === 'function' &&
@@ -67,13 +69,13 @@ function isTaskExtra(value) {
67
69
  }
68
70
  function asCreateTaskExtra(value) {
69
71
  if (!isCreateTaskExtra(value)) {
70
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Task store not configured for task-capable tool.');
72
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Task store not configured.');
71
73
  }
72
74
  return value;
73
75
  }
74
76
  function asTaskRequestExtra(value) {
75
77
  if (!isTaskExtra(value)) {
76
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Task id or task store missing for task operation.');
78
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Task id or store missing.');
77
79
  }
78
80
  return value;
79
81
  }
@@ -90,11 +92,11 @@ function isTaskStatus(value) {
90
92
  }
91
93
  function normalizeGetTaskResult(value) {
92
94
  if (!isRecord(value) || typeof value.taskId !== 'string') {
93
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Invalid task object.');
95
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Invalid task object.');
94
96
  }
95
97
  const status = isTaskStatus(value.status) ? value.status : undefined;
96
98
  if (!status) {
97
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Invalid task status.');
99
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Invalid task status.');
98
100
  }
99
101
  const createdAt = typeof value.createdAt === 'string'
100
102
  ? value.createdAt
@@ -123,7 +125,7 @@ function normalizeCallToolResult(value) {
123
125
  const parsed = CallToolResultSchema.safeParse(value);
124
126
  if (parsed.success)
125
127
  return parsed.data;
126
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Stored task result is not a valid tool result.');
128
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Invalid stored task result.');
127
129
  }
128
130
  function getToolResultErrorCode(result) {
129
131
  if (!isRecord(result) || result.isError !== true)
@@ -143,7 +145,7 @@ function getToolResultErrorCode(result) {
143
145
  return match ? match[1] : undefined;
144
146
  }
145
147
  function isCancelledToolResult(result) {
146
- return getToolResultErrorCode(result) === ErrorCode.E_CANCELLED;
148
+ return getToolResultErrorCode(result) === ErrorCode.CANCELLED;
147
149
  }
148
150
  function resolveTaskResultStatuses(result) {
149
151
  if (isCancelledToolResult(result)) {
@@ -192,6 +194,31 @@ function buildTaskStatusNotificationParams(task) {
192
194
  params.statusMessage = task.statusMessage;
193
195
  return params;
194
196
  }
197
+ async function notifyTaskCreatedIfPossible(extra, taskId, toolName) {
198
+ const { sendNotification } = extra;
199
+ if (typeof sendNotification !== 'function')
200
+ return;
201
+ const notify = sendNotification;
202
+ try {
203
+ await notify({
204
+ method: TASK_CREATED_NOTIFICATION_METHOD,
205
+ params: {
206
+ _meta: {
207
+ 'modelcontextprotocol.io/related-task': {
208
+ taskId,
209
+ },
210
+ },
211
+ },
212
+ });
213
+ }
214
+ catch {
215
+ publishTaskDiagnostics({
216
+ phase: 'task_status_notify_failed',
217
+ taskId,
218
+ ...(toolName ? { toolName } : {}),
219
+ });
220
+ }
221
+ }
195
222
  async function notifyTaskStatusIfPossible(extra, taskStore, taskId, toolName) {
196
223
  const { sendNotification } = extra;
197
224
  if (typeof sendNotification !== 'function')
@@ -222,13 +249,13 @@ async function notifyTaskStatusIfPossible(extra, taskStore, taskId, toolName) {
222
249
  }
223
250
  function getTaskStore(extra) {
224
251
  if (!extra.taskStore) {
225
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Task store not configured for task-capable tool.');
252
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Task store not configured.');
226
253
  }
227
254
  return extra.taskStore;
228
255
  }
229
256
  function getTaskId(extra) {
230
257
  if (!extra.taskId) {
231
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Task id missing for task operation.');
258
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Task id missing.');
232
259
  }
233
260
  return extra.taskId;
234
261
  }
@@ -260,6 +287,10 @@ async function isTaskAlreadyTerminal(taskStore, taskId) {
260
287
  return false;
261
288
  }
262
289
  }
290
+ function isMissingTaskStoreError(error) {
291
+ return (error instanceof Error &&
292
+ /Task .*not found|not found after cancellation/iu.test(error.message));
293
+ }
263
294
  async function countActiveTasks(taskStore) {
264
295
  if (typeof taskStore.listTasks !== 'function')
265
296
  return 0;
@@ -281,11 +312,11 @@ function resolveRequestedTaskTtl(requestedTtl) {
281
312
  if (requestedTtl == null)
282
313
  return DEFAULT_TASK_TTL_MS;
283
314
  if (!Number.isFinite(requestedTtl)) {
284
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Task ttl must be a finite number of milliseconds.');
315
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Task TTL must be finite.');
285
316
  }
286
317
  const normalized = Math.trunc(requestedTtl);
287
318
  if (normalized <= 0) {
288
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Task ttl must be greater than zero.');
319
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Task TTL must be > 0.');
289
320
  }
290
321
  return Math.min(normalized, MAX_TASK_TTL_MS);
291
322
  }
@@ -294,18 +325,40 @@ async function safelyStoreTaskResult(taskStore, taskId, storedStatus, result) {
294
325
  await taskStore.storeTaskResult(taskId, storedStatus, result);
295
326
  }
296
327
  catch (error) {
328
+ if (isMissingTaskStoreError(error))
329
+ return;
297
330
  // If task was already cancelled/failed by another process, ignore the write error
298
331
  if (await isTaskAlreadyTerminal(taskStore, taskId))
299
332
  return;
300
333
  throw error;
301
334
  }
302
335
  }
303
- async function runTaskInBackground(run, args, extra, taskStore, taskId, toolName) {
336
+ async function isTaskCancelled(taskStore, taskId) {
337
+ try {
338
+ const task = await taskStore.getTask(taskId);
339
+ return isRecord(task) && task.status === 'cancelled';
340
+ }
341
+ catch {
342
+ return false;
343
+ }
344
+ }
345
+ async function runTaskInBackground(run, args, extra, taskStore, taskId, toolName, cancelPollMs) {
346
+ // Create a dedicated AbortController for background execution.
347
+ // The original request signal is stale once createTask returns.
348
+ const taskAbort = new AbortController();
349
+ const taskExtra = { ...extra, signal: taskAbort.signal };
350
+ // Poll the task store for client-initiated cancellation.
351
+ const cancelPoller = setInterval(() => {
352
+ void isTaskCancelled(taskStore, taskId).then((cancelled) => {
353
+ if (cancelled)
354
+ taskAbort.abort(new Error('Task cancelled by client'));
355
+ });
356
+ }, cancelPollMs ?? TASK_CANCEL_POLL_MS);
304
357
  const start = performance.now();
305
358
  let taskStatuses;
306
359
  let result;
307
360
  try {
308
- const rawResult = await taskContext.run({ taskId, toolName, startTime: start }, () => run(args, extra));
361
+ const rawResult = await taskContext.run({ taskId, toolName, startTime: start }, () => run(args, taskExtra));
309
362
  taskStatuses = resolveTaskResultStatuses(rawResult);
310
363
  result = isErrorResult(rawResult)
311
364
  ? withoutStructuredContent(rawResult)
@@ -313,7 +366,10 @@ async function runTaskInBackground(run, args, extra, taskStore, taskId, toolName
313
366
  }
314
367
  catch (error) {
315
368
  taskStatuses = { storedStatus: 'failed', reportedStatus: 'failed' };
316
- result = maybeStripStructuredContentFromResult(buildToolErrorResponse(error, ErrorCode.E_UNKNOWN));
369
+ result = maybeStripStructuredContentFromResult(buildToolErrorResponse(error, ErrorCode.UNKNOWN));
370
+ }
371
+ finally {
372
+ clearInterval(cancelPoller);
317
373
  }
318
374
  const durationMs = performance.now() - start;
319
375
  try {
@@ -328,7 +384,7 @@ async function runTaskInBackground(run, args, extra, taskStore, taskId, toolName
328
384
  await notifyTaskStatusIfPossible(extra, taskStore, taskId, toolName);
329
385
  }
330
386
  catch (innerError) {
331
- console.error(format('Failed to store task result for task %s:', taskId), innerError);
387
+ Logger.error(format('Failed to store task result for task %s:', taskId), innerError);
332
388
  const syntheticTask = {
333
389
  taskId,
334
390
  status: taskStatuses.reportedStatus === 'cancelled' ? 'cancelled' : 'failed',
@@ -339,10 +395,16 @@ async function runTaskInBackground(run, args, extra, taskStore, taskId, toolName
339
395
  };
340
396
  const { sendNotification } = extra;
341
397
  if (typeof sendNotification === 'function') {
342
- void sendNotification({
343
- method: TASK_STATUS_NOTIFICATION_METHOD,
344
- params: buildTaskStatusNotificationParams(syntheticTask),
345
- });
398
+ try {
399
+ await sendNotification({
400
+ method: TASK_STATUS_NOTIFICATION_METHOD,
401
+ params: buildTaskStatusNotificationParams(syntheticTask),
402
+ });
403
+ }
404
+ catch {
405
+ // Best effort only: transport may already be closed while a cancelled
406
+ // task is still unwinding in the background.
407
+ }
346
408
  }
347
409
  }
348
410
  }
@@ -379,15 +441,23 @@ export function createToolTaskHandler(run, options) {
379
441
  const extra = asCreateTaskExtra(maybeExtra ?? argsOrExtra);
380
442
  const args = (maybeExtra ? argsOrExtra : undefined);
381
443
  if (options?.guard && !options.guard()) {
382
- throw new McpError(ErrorCode.E_INVALID_INPUT, 'Client not initialized; wait for notifications/initialized');
444
+ throw new McpError(ErrorCode.INVALID_INPUT, 'Client not initialized; wait for notifications/initialized');
383
445
  }
384
446
  const taskStore = getTaskStore(extra);
385
447
  if ((await countActiveTasks(taskStore)) >= MAX_CONCURRENT_TASKS) {
386
- throw new McpError(ErrorCode.E_INVALID_INPUT, `Too many active tasks. Limit: ${String(MAX_CONCURRENT_TASKS)}.`);
448
+ throw new McpError(ErrorCode.INVALID_INPUT, `Too many active tasks (limit: ${String(MAX_CONCURRENT_TASKS)}).`);
387
449
  }
388
450
  const task = await taskStore.createTask({
389
451
  ttl: resolveRequestedTaskTtl(extra.taskRequestedTtl),
452
+ pollInterval: options?.pollIntervalMs ?? TASK_POLL_INTERVAL_MS,
390
453
  });
454
+ const toolLabel = options?.toolName ?? 'tool';
455
+ try {
456
+ await taskStore.updateTaskStatus(task.taskId, 'working', `${toolLabel}: starting`);
457
+ }
458
+ catch {
459
+ // Best effort — status message is informational.
460
+ }
391
461
  publishTaskDiagnostics({
392
462
  phase: 'task_created',
393
463
  taskId: task.taskId,
@@ -399,8 +469,9 @@ export function createToolTaskHandler(run, options) {
399
469
  taskStore,
400
470
  taskId: task.taskId,
401
471
  };
472
+ void notifyTaskCreatedIfPossible(taskExtra, task.taskId, options?.toolName);
402
473
  void notifyTaskStatusIfPossible(taskExtra, taskStore, task.taskId, options?.toolName);
403
- void runTaskInBackground(run, args, taskExtra, taskStore, task.taskId, options?.toolName);
474
+ void runTaskInBackground(run, args, taskExtra, taskStore, task.taskId, options?.toolName, options?.cancelPollMs);
404
475
  return { task };
405
476
  });
406
477
  const getTask = (async (argsOrExtra, maybeExtra) => {
@@ -1,4 +1,4 @@
1
- import * as path from 'node:path';
1
+ import { basename } from 'node:path';
2
2
  import { DEFAULT_SEARCH_TIMEOUT_MS } from '../lib/constants.js';
3
3
  import { ErrorCode } from '../lib/errors.js';
4
4
  import { formatTreeAscii, treeDirectory, } from '../lib/file-operations/metadata.js';
@@ -48,7 +48,7 @@ export function registerTreeTool(server, options = {}) {
48
48
  timedSignal: { timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS },
49
49
  context: { path: targetPath },
50
50
  run: async (signal) => {
51
- const context = args.path ? path.basename(args.path) : '.';
51
+ const context = args.path ? basename(args.path) : '.';
52
52
  let progressCursor = 0;
53
53
  const knownTotal = args.maxEntries;
54
54
  notifyProgress(extra, {
@@ -93,7 +93,7 @@ export function registerTreeTool(server, options = {}) {
93
93
  throw error;
94
94
  }
95
95
  },
96
- onError: (error) => buildToolErrorResponse(error, ErrorCode.E_NOT_DIRECTORY, targetPath),
96
+ onError: (error) => buildToolErrorResponse(error, ErrorCode.NOT_DIRECTORY, targetPath),
97
97
  });
98
98
  };
99
99
  const wrappedHandler = wrapToolHandler(handler, {
@@ -1,7 +1,9 @@
1
- import * as fs from 'node:fs/promises';
2
- import * as path from 'node:path';
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { basename, dirname } from 'node:path';
3
+ import { withAbort } from '../lib/abort.js';
3
4
  import { ErrorCode } from '../lib/errors.js';
4
- import { atomicWriteFile, withAbort } from '../lib/fs-helpers.js';
5
+ import { atomicWriteFile } from '../lib/fs-helpers.js';
6
+ import { Logger } from '../lib/logger.js';
5
7
  import { validatePathForWrite } from '../lib/paths.js';
6
8
  import { formatBytes } from '../config.js';
7
9
  import { WriteFileInputSchema, WriteFileOutputSchema } from '../schemas.js';
@@ -19,9 +21,10 @@ export const WRITE_FILE_TOOL = {
19
21
  async function handleWriteFile(args, signal) {
20
22
  const validPath = await validatePathForWrite(args.path, signal);
21
23
  // Ensure parent directory exists
22
- await withAbort(fs.mkdir(path.dirname(validPath), { recursive: true }), signal);
24
+ await withAbort(mkdir(dirname(validPath), { recursive: true }), signal);
23
25
  await atomicWriteFile(validPath, args.content, { encoding: 'utf-8', signal });
24
26
  const bytesWritten = Buffer.byteLength(args.content, 'utf-8');
27
+ Logger.info(`write: ${args.path} (${bytesWritten} bytes)`);
25
28
  return buildToolResponse(`Successfully wrote to file: ${args.path}`, {
26
29
  ok: true,
27
30
  path: validPath,
@@ -36,13 +39,13 @@ export function registerWriteFileTool(server, options = {}) {
36
39
  timedSignal: {},
37
40
  context: { path: args.path },
38
41
  run: (signal) => handleWriteFile(args, signal),
39
- onError: (error) => buildToolErrorResponse(error, ErrorCode.E_UNKNOWN, args.path),
42
+ onError: (error) => buildToolErrorResponse(error, ErrorCode.UNKNOWN, args.path),
40
43
  });
41
44
  const wrappedHandler = wrapToolHandler(handler, {
42
45
  guard: options.isInitialized,
43
- progressMessage: (args) => `🛠 write: ${path.basename(args.path)}`,
46
+ progressMessage: (args) => `🛠 write: ${basename(args.path)}`,
44
47
  completionMessage: (args, result) => {
45
- const name = path.basename(args.path);
48
+ const name = basename(args.path);
46
49
  if (result.isError)
47
50
  return `🛠 write: ${name} • failed`;
48
51
  const sc = result.structuredContent;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@j0hanz/filesystem-mcp",
3
- "version": "1.14.0",
3
+ "version": "1.14.1",
4
4
  "mcpName": "io.github.j0hanz/filesystem-mcp",
5
5
  "description": "A local filesystem MCP server that lets LLMs and AI agents read, write, search, diff, patch, and manage files safely and efficiently. Built for reliable, structured, and controlled filesystem interaction.",
6
6
  "type": "module",
@@ -75,28 +75,28 @@
75
75
  },
76
76
  "homepage": "https://github.com/j0hanz/filesystem-mcp#readme",
77
77
  "dependencies": {
78
- "@modelcontextprotocol/sdk": "^1.27.1",
78
+ "@modelcontextprotocol/sdk": "^1.29.0",
79
79
  "commander": "^14.0.3",
80
- "diff": "^8.0.3",
80
+ "diff": "^8.0.4",
81
81
  "ignore": "^7.0.5",
82
- "re2": "^1.23.3",
83
- "safe-regex2": "^5.0.0",
82
+ "re2": "^1.24.0",
84
83
  "zod": "^4.3.6"
85
84
  },
86
85
  "devDependencies": {
87
86
  "@eslint/js": "^10.0.1",
88
87
  "@trivago/prettier-plugin-sort-imports": "^6.0.2",
89
88
  "@types/node": "^24",
90
- "eslint": "^10.0.3",
89
+ "eslint": "^10.2.0",
91
90
  "eslint-config-prettier": "^10.1.8",
92
91
  "eslint-plugin-de-morgan": "^2.1.1",
93
92
  "eslint-plugin-depend": "^1.5.0",
93
+ "eslint-plugin-sonarjs": "^4.0.2",
94
94
  "eslint-plugin-unused-imports": "^4.4.1",
95
- "knip": "^5.86.0",
95
+ "knip": "^6.3.1",
96
96
  "prettier": "^3.8.1",
97
97
  "tsx": "^4.21.0",
98
- "typescript": "^5.9.3",
99
- "typescript-eslint": "^8.57.0"
98
+ "typescript": "^6.0.2",
99
+ "typescript-eslint": "^8.58.1"
100
100
  },
101
101
  "engines": {
102
102
  "node": ">=24"