@j0hanz/filesystem-mcp 2.0.0 → 2.1.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 (77) hide show
  1. package/README.md +27 -86
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +6 -31
  4. package/dist/cli.js.map +1 -1
  5. package/dist/core/config.d.ts +7 -0
  6. package/dist/core/config.d.ts.map +1 -1
  7. package/dist/core/config.js +7 -0
  8. package/dist/core/config.js.map +1 -1
  9. package/dist/core/fmt.d.ts +1 -2
  10. package/dist/core/fmt.d.ts.map +1 -1
  11. package/dist/core/fmt.js +0 -21
  12. package/dist/core/fmt.js.map +1 -1
  13. package/dist/core/input-required.d.ts +0 -9
  14. package/dist/core/input-required.d.ts.map +1 -1
  15. package/dist/core/input-required.js +4 -26
  16. package/dist/core/input-required.js.map +1 -1
  17. package/dist/core/primitives.d.ts +0 -1
  18. package/dist/core/primitives.d.ts.map +1 -1
  19. package/dist/core/primitives.js +0 -3
  20. package/dist/core/primitives.js.map +1 -1
  21. package/dist/core/schema.d.ts +0 -1
  22. package/dist/core/schema.d.ts.map +1 -1
  23. package/dist/core/schema.js +5 -2
  24. package/dist/core/schema.js.map +1 -1
  25. package/dist/core/util.d.ts +0 -2
  26. package/dist/core/util.d.ts.map +1 -1
  27. package/dist/core/util.js +1 -2
  28. package/dist/core/util.js.map +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/instructions.d.ts +0 -1
  32. package/dist/instructions.d.ts.map +1 -1
  33. package/dist/instructions.js +2 -3
  34. package/dist/instructions.js.map +1 -1
  35. package/dist/prompts.d.ts.map +1 -1
  36. package/dist/prompts.js +5 -11
  37. package/dist/prompts.js.map +1 -1
  38. package/dist/tools/create.d.ts.map +1 -1
  39. package/dist/tools/create.js +6 -24
  40. package/dist/tools/create.js.map +1 -1
  41. package/dist/tools/define.d.ts +0 -8
  42. package/dist/tools/define.d.ts.map +1 -1
  43. package/dist/tools/define.js +28 -19
  44. package/dist/tools/define.js.map +1 -1
  45. package/dist/tools/delete-file.d.ts.map +1 -1
  46. package/dist/tools/delete-file.js +0 -3
  47. package/dist/tools/delete-file.js.map +1 -1
  48. package/dist/tools/edit.d.ts.map +1 -1
  49. package/dist/tools/edit.js +0 -2
  50. package/dist/tools/edit.js.map +1 -1
  51. package/dist/tools/list.d.ts.map +1 -1
  52. package/dist/tools/list.js +11 -1
  53. package/dist/tools/list.js.map +1 -1
  54. package/dist/tools/progress.d.ts +2 -7
  55. package/dist/tools/progress.d.ts.map +1 -1
  56. package/dist/tools/progress.js +10 -26
  57. package/dist/tools/progress.js.map +1 -1
  58. package/dist/tools/read.d.ts.map +1 -1
  59. package/dist/tools/read.js +32 -5
  60. package/dist/tools/read.js.map +1 -1
  61. package/dist/tools/replace-in-files.d.ts.map +1 -1
  62. package/dist/tools/replace-in-files.js +0 -3
  63. package/dist/tools/replace-in-files.js.map +1 -1
  64. package/dist/tools/roots.d.ts.map +1 -1
  65. package/dist/tools/roots.js +21 -5
  66. package/dist/tools/roots.js.map +1 -1
  67. package/dist/tools/stat.d.ts.map +1 -1
  68. package/dist/tools/stat.js +4 -17
  69. package/dist/tools/stat.js.map +1 -1
  70. package/dist/transport/http.d.ts.map +1 -1
  71. package/dist/transport/http.js +1 -11
  72. package/dist/transport/http.js.map +1 -1
  73. package/dist/transport/shared.d.ts +0 -5
  74. package/dist/transport/shared.d.ts.map +1 -1
  75. package/dist/transport/shared.js +4 -0
  76. package/dist/transport/shared.js.map +1 -1
  77. package/package.json +2 -3
@@ -1 +1 @@
1
- {"version":3,"file":"roots.js","sourceRoot":"","sources":["../../src/tools/roots.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,gBAAgB,GAAG,CAAC,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;AAE5C,MAAM,iBAAiB,GAAG,CAAC,CAAC,YAAY,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,0DAA0D,CAAC;CAChG,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG,UAAU,CAAC;IACjD,IAAI,EAAE,YAAY;IAClB,KAAK,EAAE,iBAAiB;IACxB,WAAW,EACT,gQAAgQ;IAClQ,KAAK,EAAE,gBAAgB;IACvB,MAAM,EAAE,iBAAiB;IACzB,WAAW,EAAE;QACX,YAAY,EAAE,IAAI;QAClB,cAAc,EAAE,IAAI;QACpB,eAAe,EAAE,KAAK;QACtB,aAAa,EAAE,KAAK;KACrB;IACD,GAAG,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QAClB,MAAM,IAAI,GAAG,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,qBAAqB,EAAE,CAAC;QACtD,MAAM,UAAU,GAAG,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;QACxC,MAAM,IAAI,GACR,IAAI,CAAC,MAAM,GAAG,CAAC;YACb,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;YACjB,CAAC,CAAC,6IAA6I,CAAC;QACpJ,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,gBAAgB,EAAE,SAAS,CAAC,OAAO;CACpC,CAAC,CAAC","sourcesContent":["import * as z from 'zod/v4';\n\nimport { ErrorCode } from '../core/errors.js';\nimport { defineTool } from './define.js';\n\nconst RootsInputSchema = z.strictObject({});\n\nconst RootsOutputSchema = z.strictObject({\n roots: z.array(z.string()).describe('Absolute paths of the allowed workspace root directories'),\n});\n\nexport const LIST_ALLOWED_DIRECTORIES = defineTool({\n name: 'list_roots',\n title: 'Workspace Roots',\n description:\n 'List the allowed workspace root directories. Call this first to discover what paths are accessible; all other tools are scoped to these roots. Allowed directories are configured via CLI arguments, the FS_ALLOWED_DIRS environment variable, or --allow-cwd.',\n input: RootsInputSchema,\n output: RootsOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n run: (_args, ctx) => {\n const dirs = ctx.fs.pathGuard.getAllowedDirectories();\n const structured = { roots: [...dirs] };\n const text =\n dirs.length > 0\n ? dirs.join('\\n')\n : 'No allowed directories. Please configure allowed directories using CLI arguments, the FS_ALLOWED_DIRS environment variable, or --allow-cwd.';\n return Promise.resolve({ structured, text });\n },\n\n defaultErrorCode: ErrorCode.UNKNOWN,\n});\n"]}
1
+ {"version":3,"file":"roots.js","sourceRoot":"","sources":["../../src/tools/roots.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,gBAAgB,GAAG,CAAC,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;AAE5C,MAAM,iBAAiB,GAAG,CAAC,CAAC,YAAY,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,0DAA0D,CAAC;IAC/F,IAAI,EAAE,CAAC;SACJ,MAAM,EAAE;SACR,QAAQ,EAAE;SACV,QAAQ,CAAC,kEAAkE,CAAC;CAChF,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG,UAAU,CAAC;IACjD,IAAI,EAAE,YAAY;IAClB,KAAK,EAAE,iBAAiB;IACxB,WAAW,EACT,gQAAgQ;IAClQ,KAAK,EAAE,gBAAgB;IACvB,MAAM,EAAE,iBAAiB;IACzB,WAAW,EAAE;QACX,YAAY,EAAE,IAAI;QAClB,cAAc,EAAE,IAAI;QACpB,eAAe,EAAE,KAAK;QACtB,aAAa,EAAE,KAAK;KACrB;IACD,GAAG,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QAClB,MAAM,IAAI,GAAG,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,qBAAqB,EAAE,CAAC;QACtD,wEAAwE;QACxE,0EAA0E;QAC1E,4EAA4E;QAC5E,uCAAuC;QACvC,EAAE;QACF,4EAA4E;QAC5E,yEAAyE;QACzE,uEAAuE;QACvE,wEAAwE;QACxE,wEAAwE;QACxE,OAAO,OAAO,CAAC,OAAO,CAAC;YACrB,UAAU,EAAE;gBACV,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;gBAChB,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,4BAA4B,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACrE;SACF,CAAC,CAAC;IACL,CAAC;IAED,gBAAgB,EAAE,SAAS,CAAC,OAAO;CACpC,CAAC,CAAC","sourcesContent":["import * as z from 'zod/v4';\n\nimport { NO_POSITIONAL_ROOTS_GUIDANCE } from '../core/config.js';\nimport { ErrorCode } from '../core/errors.js';\nimport { defineTool } from './define.js';\n\nconst RootsInputSchema = z.strictObject({});\n\nconst RootsOutputSchema = z.strictObject({\n roots: z.array(z.string()).describe('Absolute paths of the allowed workspace root directories'),\n hint: z\n .string()\n .optional()\n .describe('How to configure roots; present only when there are none to list'),\n});\n\nexport const LIST_ALLOWED_DIRECTORIES = defineTool({\n name: 'list_roots',\n title: 'Workspace Roots',\n description:\n 'List the allowed workspace root directories. Call this first to discover what paths are accessible; all other tools are scoped to these roots. Allowed directories are configured via CLI arguments, the FS_ALLOWED_DIRS environment variable, or --allow-cwd.',\n input: RootsInputSchema,\n output: RootsOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n run: (_args, ctx) => {\n const dirs = ctx.fs.pathGuard.getAllowedDirectories();\n // No `text` on purpose. A newline-joined path list and the JSON say the\n // same thing, and the JSON is the shape every caller of this tool parses.\n // Supplying no text makes this a data tool, so `define.ts` renders the JSON\n // and keeps it in `structuredContent`.\n //\n // `hint` rides the same JSON so the recovery reaches every client. An empty\n // `roots` says the call failed to be useful but not what to do about it,\n // and the elicitation route out call a tool with a concrete path and\n // approve the grant — appears in no tool description. It is conditional\n // because a configured server pays nothing to be told how to configure.\n return Promise.resolve({\n structured: {\n roots: [...dirs],\n ...(dirs.length === 0 ? { hint: NO_POSITIONAL_ROOTS_GUIDANCE } : {}),\n },\n });\n },\n\n defaultErrorCode: ErrorCode.UNKNOWN,\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"stat.d.ts","sourceRoot":"","sources":["../../src/tools/stat.ts"],"names":[],"mappings":"AAgMA,eAAO,MAAM,aAAa,mCAkFxB,CAAC"}
1
+ {"version":3,"file":"stat.d.ts","sourceRoot":"","sources":["../../src/tools/stat.ts"],"names":[],"mappings":"AA+LA,eAAO,MAAM,aAAa,mCAsExB,CAAC"}
@@ -1,7 +1,6 @@
1
1
  import { parse } from 'node:path';
2
2
  import * as z from 'zod/v4';
3
3
  import { ErrorCode, rethrowIfAborted } from '../core/errors.js';
4
- import { formatBytes } from '../core/fmt.js';
5
4
  import { getFileType, isHidden } from '../core/fs.js';
6
5
  import { detectMimeType } from '../core/mime.js';
7
6
  import { FileInfoSchema, NonNegInt, OperationSummarySchema, PerFileErrorSchema, singleOrBatchAccessPaths, singleOrBatchPathsInput, } from '../core/schema.js';
@@ -176,21 +175,10 @@ export const GET_FILE_INFO = defineTool({
176
175
  resourceUri = entry.uri;
177
176
  resources.push(link);
178
177
  }
179
- const text = perPathPayload
180
- .map((r) => {
181
- if (r.value) {
182
- const { name, type, size } = r.value;
183
- // A directory's own inode size says nothing about what is inside it
184
- // (0 on Windows, 4096 on ext4), and "directory, 0 B" reads as empty.
185
- // Use `list` for contents; report the byte size only where it means
186
- // something.
187
- if (type === 'directory')
188
- return `${name}: directory`;
189
- return `${name}: ${type}, ${formatBytes(size)}`;
190
- }
191
- return `${r.path}: ${r.error?.message ?? 'error'}`;
192
- })
193
- .join('\n');
178
+ // No `text` on purpose. The one-liner this used to build (`AGENTS.md: file,
179
+ // 751 B`) dropped tokenEstimate, modified, mimeType and isHidden — the very
180
+ // fields a caller asks `stat` for. Supplying no text makes this a data tool,
181
+ // so `define.ts` renders the JSON and keeps it in `structuredContent`.
194
182
  return {
195
183
  structured: {
196
184
  results: perPathPayload,
@@ -199,7 +187,6 @@ export const GET_FILE_INFO = defineTool({
199
187
  dirCount,
200
188
  ...(resourceUri ? { resourceUri } : {}),
201
189
  },
202
- text,
203
190
  ...(resources.length > 0 ? { resources } : {}),
204
191
  };
205
192
  },
@@ -1 +1 @@
1
- {"version":3,"file":"stat.js","sourceRoot":"","sources":["../../src/tools/stat.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EACL,cAAc,EACd,SAAS,EACT,sBAAsB,EACtB,kBAAkB,EAClB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AA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BACV,OAAO,EAAE,cAAc;gBACvB,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,SAAS;gBACT,QAAQ;gBACR,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACxC;YACD,IAAI;YACJ,GAAG,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/C,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { parse } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, rethrowIfAborted } from '../core/errors.js';\nimport { formatBytes } from '../core/fmt.js';\nimport type { FileInfo, GuardedFileSystem, Stats } from '../core/fs.js';\nimport { getFileType, isHidden } from '../core/fs.js';\nimport { detectMimeType } from '../core/mime.js';\nimport {\n FileInfoSchema,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n singleOrBatchAccessPaths,\n singleOrBatchPathsInput,\n} from '../core/schema.js';\nimport { putJsonResource } from '../core/store.js';\nimport { DEFAULT_SEARCH_TIMEOUT_MS } from '../core/util.js';\nimport type { PerPathResult } from './batch.js';\nimport { runOverPaths } from './batch.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst StatInputSchema = singleOrBatchPathsInput({ extra: {} });\n\nconst StatPerPathSchema = z.strictObject({\n path: z.string().describe('Requested path'),\n value: FileInfoSchema.optional().describe('File metadata; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst StatOutputSchema = z.strictObject({\n results: z\n .array(StatPerPathSchema)\n .describe('Per-path metadata results ordered to match the input paths'),\n summary: OperationSummarySchema,\n fileCount: NonNegInt.optional().describe('Number of regular files in the results'),\n dirCount: NonNegInt.optional().describe('Number of directories in the results'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'URI to aggregated stats.json in the resource store (present when resource store is available)',\n ),\n});\n\nfunction getPermissions(mode: number): string {\n let out = '';\n for (const shift of [6, 3, 0]) {\n const bits = (mode >> shift) & 0b111;\n out += (bits & 0b100 ? 'r' : '-') + (bits & 0b010 ? 'w' : '-') + (bits & 0b001 ? 'x' : '-');\n }\n return out;\n}\n\nfunction buildFileInfoResult(\n name: string,\n requestedPath: string,\n isSymlink: boolean,\n stats: Stats,\n mimeType: string | undefined,\n symlinkTarget: string | undefined,\n): FileInfo {\n const tokenEstimate = stats.isFile() ? Math.ceil(stats.size / 4) : undefined;\n return {\n name,\n path: requestedPath,\n type: isSymlink ? 'symlink' : getFileType(stats),\n size: stats.size,\n ...(tokenEstimate !== undefined ? { tokenEstimate } : {}),\n created: stats.birthtime,\n modified: stats.mtime,\n accessed: stats.atime,\n permissions: getPermissions(stats.mode),\n isHidden: isHidden(name),\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(symlinkTarget !== undefined ? { symlinkTarget } : {}),\n };\n}\n\nasync function getSymlinkTarget(\n pathToRead: string,\n fs: GuardedFileSystem,\n signal?: AbortSignal,\n log?: ToolCtx['log'],\n): Promise<string | undefined> {\n signal?.throwIfAborted();\n try {\n const { linkString } = await fs.readlink(pathToRead);\n return linkString;\n } catch (error) {\n rethrowIfAborted(error);\n log?.('warning', `stat: readlink failed for \"${pathToRead}\": ${String(error)}`, 'stat');\n return undefined;\n }\n}\n\ninterface FileInfoOptions {\n includeMimeType?: boolean | undefined;\n signal?: AbortSignal | undefined;\n onProgress?: (() => void) | undefined;\n fs: GuardedFileSystem;\n log?: ToolCtx['log'] | undefined;\n}\n\nasync function getFileInfo(filePath: string, options: FileInfoOptions): Promise<FileInfo> {\n const { signal, fs, log } = options;\n signal?.throwIfAborted();\n\n const {\n requestedPath,\n isSymlink,\n stats: followedStats,\n } = await fs.statDetailed(filePath, signal ? { signal } : undefined);\n\n const { base: name, ext: rawExt } = parse(requestedPath);\n const includeMimeType = options.includeMimeType !== false;\n const mimeType =\n includeMimeType && rawExt.length > 0 ? detectMimeType(requestedPath).mimeType : undefined;\n\n // For a symlink, fsStat follows the link and reports the target's metadata.\n // Report the link's own metadata instead so size/permissions/timestamps\n // describe the link the user asked about, not its target.\n let stats = followedStats;\n if (isSymlink) {\n try {\n ({ stats } = await fs.lstat(requestedPath, signal ? { signal } : undefined));\n } catch (error) {\n // A cancelled request is not a \"link metadata unavailable\" fallback.\n rethrowIfAborted(error);\n // Guarded lstat can be refused where raw lstat succeeded (e.g. an allowed\n // root that is itself a symlink, whose parent sits outside the roots).\n // Falling back to the followed stats degrades the report to the target's\n // metadata, so leave a trace instead of degrading silently.\n log?.('warning', `stat: lstat failed for \"${requestedPath}\": ${String(error)}`, 'stat');\n stats = followedStats;\n }\n }\n\n // isSymlink above is true whenever ANY ancestor is a symlink, because it\n // compares the requested path with its fully-resolved real path. Only the\n // entry's own lstat says whether THIS path is a link, so a regular file under\n // a symlinked parent is reported as a file and no readlink is attempted.\n const isOwnSymlink = stats.isSymbolicLink();\n const symlinkTarget = isOwnSymlink\n ? await getSymlinkTarget(requestedPath, fs, signal, log)\n : undefined;\n\n return buildFileInfoResult(name, requestedPath, isOwnSymlink, stats, mimeType, symlinkTarget);\n}\n\nfunction classifyTypeCounts(results: readonly PerPathResult<FileInfo>[]): {\n fileCount: number;\n dirCount: number;\n} {\n let fileCount = 0;\n let dirCount = 0;\n for (const result of results) {\n if ('error' in result) continue;\n if (result.value.type === 'directory') dirCount += 1;\n else fileCount += 1;\n }\n return { fileCount, dirCount };\n}\n\nfunction toStatPerPathPayload(r: PerPathResult<FileInfo>): z.infer<typeof StatPerPathSchema> {\n if ('error' in r) {\n return { path: r.path, error: r.error };\n }\n const info = r.value;\n return {\n path: r.path,\n value: {\n name: info.name,\n path: info.path,\n type: info.type,\n size: info.size,\n ...(info.tokenEstimate !== undefined ? { tokenEstimate: info.tokenEstimate } : {}),\n created: info.created.toISOString(),\n modified: info.modified.toISOString(),\n accessed: info.accessed.toISOString(),\n permissions: info.permissions,\n isHidden: info.isHidden,\n ...(info.mimeType !== undefined ? { mimeType: info.mimeType } : {}),\n ...(info.symlinkTarget !== undefined ? { symlinkTarget: info.symlinkTarget } : {}),\n },\n };\n}\n\nexport const GET_FILE_INFO = defineTool({\n name: 'stat',\n title: 'Get File Info',\n description:\n 'Get metadata for one or more files or directories: size, type, permissions, MIME type, timestamps, and tokenEstimate. ' +\n 'Use tokenEstimate to pre-screen read cost before calling read. ' +\n 'Single path: pass path. Batch mode: pass paths[].',\n input: StatInputSchema,\n output: StatOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_FOUND,\n progress: (args) => {\n if (args.paths !== undefined) {\n return { label: 'Stat', subject: `${String(args.paths.length)} paths` };\n }\n return { label: 'Stat', subject: args.path ?? '' };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n const batchInput = args.path !== undefined ? { path: args.path } : { paths: args.paths ?? [] };\n\n const batch = await runOverPaths<undefined, FileInfo>(\n batchInput,\n ctx,\n async ({ path }) =>\n getFileInfo(path, {\n includeMimeType: true,\n fs: ctx.fs,\n signal: ctx.signal,\n log: ctx.log,\n }),\n { defaultErrorCode: ErrorCode.NOT_FOUND },\n );\n\n const { fileCount, dirCount } = classifyTypeCounts(batch.results);\n const perPathPayload = batch.results.map(toStatPerPathPayload);\n\n let resourceUri: string | undefined;\n const resources: ContentBlock[] = [];\n if (ctx.resourceStore && batch.summary.total > 1) {\n const { entry, link } = putJsonResource(\n ctx.resourceStore,\n `${String(batch.summary.total)} paths`,\n perPathPayload,\n );\n resourceUri = entry.uri;\n resources.push(link);\n }\n\n const text = perPathPayload\n .map((r) => {\n if (r.value) {\n const { name, type, size } = r.value;\n // A directory's own inode size says nothing about what is inside it\n // (0 on Windows, 4096 on ext4), and \"directory, 0 B\" reads as empty.\n // Use `list` for contents; report the byte size only where it means\n // something.\n if (type === 'directory') return `${name}: directory`;\n return `${name}: ${type}, ${formatBytes(size)}`;\n }\n return `${r.path}: ${r.error?.message ?? 'error'}`;\n })\n .join('\\n');\n\n return {\n structured: {\n results: perPathPayload,\n summary: batch.summary,\n fileCount,\n dirCount,\n ...(resourceUri ? { resourceUri } : {}),\n },\n text,\n ...(resources.length > 0 ? { resources } : {}),\n };\n },\n});\n"]}
1
+ {"version":3,"file":"stat.js","sourceRoot":"","sources":["../../src/tools/stat.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEhE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EACL,cAAc,EACd,SAAS,EACT,sBAAsB,EACtB,kBAAkB,EAClB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,eAAe,GAAG,uBAAuB,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAE/D,MAAM,iBAAiB,GAAG,CAAC,CAAC,YAAY,CAAC;IACvC,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gBAAgB,CAAC;IAC3C,KAAK,EAAE,cAAc,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,mCAAm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AAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,eAAe,CACrC,GAAG,CAAC,aAAa,EACjB,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,EACtC,cAAc,CACf,CAAC;YACF,WAAW,GAAG,KAAK,CAAC,GAAG,CAAC;YACxB,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC;QAED,4EAA4E;QAC5E,4EAA4E;QAC5E,6EAA6E;QAC7E,uEAAuE;QACvE,OAAO;YACL,UAAU,EAAE;gBACV,OAAO,EAAE,cAAc;gBACvB,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,SAAS;gBACT,QAAQ;gBACR,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACxC;YACD,GAAG,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/C,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { parse } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, rethrowIfAborted } from '../core/errors.js';\nimport type { FileInfo, GuardedFileSystem, Stats } from '../core/fs.js';\nimport { getFileType, isHidden } from '../core/fs.js';\nimport { detectMimeType } from '../core/mime.js';\nimport {\n FileInfoSchema,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n singleOrBatchAccessPaths,\n singleOrBatchPathsInput,\n} from '../core/schema.js';\nimport { putJsonResource } from '../core/store.js';\nimport { DEFAULT_SEARCH_TIMEOUT_MS } from '../core/util.js';\nimport type { PerPathResult } from './batch.js';\nimport { runOverPaths } from './batch.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst StatInputSchema = singleOrBatchPathsInput({ extra: {} });\n\nconst StatPerPathSchema = z.strictObject({\n path: z.string().describe('Requested path'),\n value: FileInfoSchema.optional().describe('File metadata; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst StatOutputSchema = z.strictObject({\n results: z\n .array(StatPerPathSchema)\n .describe('Per-path metadata results ordered to match the input paths'),\n summary: OperationSummarySchema,\n fileCount: NonNegInt.optional().describe('Number of regular files in the results'),\n dirCount: NonNegInt.optional().describe('Number of directories in the results'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'URI to aggregated stats.json in the resource store (present when resource store is available)',\n ),\n});\n\nfunction getPermissions(mode: number): string {\n let out = '';\n for (const shift of [6, 3, 0]) {\n const bits = (mode >> shift) & 0b111;\n out += (bits & 0b100 ? 'r' : '-') + (bits & 0b010 ? 'w' : '-') + (bits & 0b001 ? 'x' : '-');\n }\n return out;\n}\n\nfunction buildFileInfoResult(\n name: string,\n requestedPath: string,\n isSymlink: boolean,\n stats: Stats,\n mimeType: string | undefined,\n symlinkTarget: string | undefined,\n): FileInfo {\n const tokenEstimate = stats.isFile() ? Math.ceil(stats.size / 4) : undefined;\n return {\n name,\n path: requestedPath,\n type: isSymlink ? 'symlink' : getFileType(stats),\n size: stats.size,\n ...(tokenEstimate !== undefined ? { tokenEstimate } : {}),\n created: stats.birthtime,\n modified: stats.mtime,\n accessed: stats.atime,\n permissions: getPermissions(stats.mode),\n isHidden: isHidden(name),\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(symlinkTarget !== undefined ? { symlinkTarget } : {}),\n };\n}\n\nasync function getSymlinkTarget(\n pathToRead: string,\n fs: GuardedFileSystem,\n signal?: AbortSignal,\n log?: ToolCtx['log'],\n): Promise<string | undefined> {\n signal?.throwIfAborted();\n try {\n const { linkString } = await fs.readlink(pathToRead);\n return linkString;\n } catch (error) {\n rethrowIfAborted(error);\n log?.('warning', `stat: readlink failed for \"${pathToRead}\": ${String(error)}`, 'stat');\n return undefined;\n }\n}\n\ninterface FileInfoOptions {\n includeMimeType?: boolean | undefined;\n signal?: AbortSignal | undefined;\n onProgress?: (() => void) | undefined;\n fs: GuardedFileSystem;\n log?: ToolCtx['log'] | undefined;\n}\n\nasync function getFileInfo(filePath: string, options: FileInfoOptions): Promise<FileInfo> {\n const { signal, fs, log } = options;\n signal?.throwIfAborted();\n\n const {\n requestedPath,\n isSymlink,\n stats: followedStats,\n } = await fs.statDetailed(filePath, signal ? { signal } : undefined);\n\n const { base: name, ext: rawExt } = parse(requestedPath);\n const includeMimeType = options.includeMimeType !== false;\n const mimeType =\n includeMimeType && rawExt.length > 0 ? detectMimeType(requestedPath).mimeType : undefined;\n\n // For a symlink, fsStat follows the link and reports the target's metadata.\n // Report the link's own metadata instead so size/permissions/timestamps\n // describe the link the user asked about, not its target.\n let stats = followedStats;\n if (isSymlink) {\n try {\n ({ stats } = await fs.lstat(requestedPath, signal ? { signal } : undefined));\n } catch (error) {\n // A cancelled request is not a \"link metadata unavailable\" fallback.\n rethrowIfAborted(error);\n // Guarded lstat can be refused where raw lstat succeeded (e.g. an allowed\n // root that is itself a symlink, whose parent sits outside the roots).\n // Falling back to the followed stats degrades the report to the target's\n // metadata, so leave a trace instead of degrading silently.\n log?.('warning', `stat: lstat failed for \"${requestedPath}\": ${String(error)}`, 'stat');\n stats = followedStats;\n }\n }\n\n // isSymlink above is true whenever ANY ancestor is a symlink, because it\n // compares the requested path with its fully-resolved real path. Only the\n // entry's own lstat says whether THIS path is a link, so a regular file under\n // a symlinked parent is reported as a file and no readlink is attempted.\n const isOwnSymlink = stats.isSymbolicLink();\n const symlinkTarget = isOwnSymlink\n ? await getSymlinkTarget(requestedPath, fs, signal, log)\n : undefined;\n\n return buildFileInfoResult(name, requestedPath, isOwnSymlink, stats, mimeType, symlinkTarget);\n}\n\nfunction classifyTypeCounts(results: readonly PerPathResult<FileInfo>[]): {\n fileCount: number;\n dirCount: number;\n} {\n let fileCount = 0;\n let dirCount = 0;\n for (const result of results) {\n if ('error' in result) continue;\n if (result.value.type === 'directory') dirCount += 1;\n else fileCount += 1;\n }\n return { fileCount, dirCount };\n}\n\nfunction toStatPerPathPayload(r: PerPathResult<FileInfo>): z.infer<typeof StatPerPathSchema> {\n if ('error' in r) {\n return { path: r.path, error: r.error };\n }\n const info = r.value;\n return {\n path: r.path,\n value: {\n name: info.name,\n path: info.path,\n type: info.type,\n size: info.size,\n ...(info.tokenEstimate !== undefined ? { tokenEstimate: info.tokenEstimate } : {}),\n created: info.created.toISOString(),\n modified: info.modified.toISOString(),\n accessed: info.accessed.toISOString(),\n permissions: info.permissions,\n isHidden: info.isHidden,\n ...(info.mimeType !== undefined ? { mimeType: info.mimeType } : {}),\n ...(info.symlinkTarget !== undefined ? { symlinkTarget: info.symlinkTarget } : {}),\n },\n };\n}\n\nexport const GET_FILE_INFO = defineTool({\n name: 'stat',\n title: 'Get File Info',\n description:\n 'Get metadata for one or more files or directories: size, type, permissions, MIME type, timestamps, and tokenEstimate. ' +\n 'Use tokenEstimate to pre-screen read cost before calling read. ' +\n 'Single path: pass path. Batch mode: pass paths[].',\n input: StatInputSchema,\n output: StatOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_FOUND,\n progress: (args) => {\n if (args.paths !== undefined) {\n return { label: 'Stat', subject: `${String(args.paths.length)} paths` };\n }\n return { label: 'Stat', subject: args.path ?? '' };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n const batchInput = args.path !== undefined ? { path: args.path } : { paths: args.paths ?? [] };\n\n const batch = await runOverPaths<undefined, FileInfo>(\n batchInput,\n ctx,\n async ({ path }) =>\n getFileInfo(path, {\n includeMimeType: true,\n fs: ctx.fs,\n signal: ctx.signal,\n log: ctx.log,\n }),\n { defaultErrorCode: ErrorCode.NOT_FOUND },\n );\n\n const { fileCount, dirCount } = classifyTypeCounts(batch.results);\n const perPathPayload = batch.results.map(toStatPerPathPayload);\n\n let resourceUri: string | undefined;\n const resources: ContentBlock[] = [];\n if (ctx.resourceStore && batch.summary.total > 1) {\n const { entry, link } = putJsonResource(\n ctx.resourceStore,\n `${String(batch.summary.total)} paths`,\n perPathPayload,\n );\n resourceUri = entry.uri;\n resources.push(link);\n }\n\n // No `text` on purpose. The one-liner this used to build (`AGENTS.md: file,\n // 751 B`) dropped tokenEstimate, modified, mimeType and isHidden — the very\n // fields a caller asks `stat` for. Supplying no text makes this a data tool,\n // so `define.ts` renders the JSON and keeps it in `structuredContent`.\n return {\n structured: {\n results: perPathPayload,\n summary: batch.summary,\n fileCount,\n dirCount,\n ...(resourceUri ? { resourceUri } : {}),\n },\n ...(resources.length > 0 ? { resources } : {}),\n };\n },\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/transport/http.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAUxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAuBrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAyOjD,wBAAsB,eAAe,CACnC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,aAAa,EACtB,MAAM,GAAE,aAAkB,GACzB,OAAO,CAAC,MAAM,CAAC,CAgIjB"}
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/transport/http.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AASxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAuBrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAyOjD,wBAAsB,eAAe,CACnC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,aAAa,EACtB,MAAM,GAAE,aAAkB,GACzB,OAAO,CAAC,MAAM,CAAC,CAuHjB"}
@@ -5,7 +5,6 @@ import { toNodeHandler } from '@modelcontextprotocol/node';
5
5
  import { createMcpHandler, DEFAULT_REQUEST_TIMEOUT_MSEC, ProtocolErrorCode, } from '@modelcontextprotocol/server';
6
6
  import { createServer as createHttpServer } from 'node:http';
7
7
  import { formatUnknownErrorMessage } from '../core/errors.js';
8
- import { assertFleetRequestStateKey } from '../core/input-required.js';
9
8
  import { Logger } from '../core/observability.js';
10
9
  import { PageSnapshotStore } from '../core/page-store.js';
11
10
  import { PathGuard } from '../core/path.js';
@@ -183,16 +182,8 @@ function setupExpressApp(httpHost, apiKey, allowedHosts, modernNodeHandler, shar
183
182
  }
184
183
  export async function startHttpServer(port, options, config = {}) {
185
184
  const httpHost = config.httpHost ?? '127.0.0.1';
186
- const { apiKey, eventBus } = config;
187
- const fleet = config.deploymentMode === 'fleet';
185
+ const { apiKey } = config;
188
186
  assertHttpBindingPolicy(httpHost, apiKey);
189
- if (fleet && !apiKey) {
190
- throw new Error('Fleet deployment mode requires an API key.');
191
- }
192
- if (fleet && !eventBus) {
193
- throw new Error('Fleet deployment mode requires a shared event bus.');
194
- }
195
- assertFleetRequestStateKey(fleet);
196
187
  const allowedHosts = resolveAllowedHosts(httpHost, process.env['FS_ALLOWED_HOSTS']);
197
188
  assertHttpHostPolicy(httpHost, allowedHosts, parseTrueEnvFlag(process.env['FS_ALLOW_UNRESTRICTED_HOSTS'], 'FS_ALLOW_UNRESTRICTED_HOSTS'));
198
189
  const sharedRegistry = createWatcherRegistry();
@@ -219,7 +210,6 @@ export async function startHttpServer(port, options, config = {}) {
219
210
  await sharedPathGuard.recomputeAllowedDirectories();
220
211
  const modernHandler = createMcpHandler(makeHttpModernFactory(options, () => modernHandler.notify, sharedRegistry, sharedPathGuard, sharedStore, sharedPageStore, apiKey), {
221
212
  legacy: 'reject',
222
- ...(eventBus ? { bus: eventBus } : {}),
223
213
  onerror: (error) => {
224
214
  Logger.error('[HTTP] modern leg error:', formatUnknownErrorMessage(error));
225
215
  },
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/transport/http.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAM3D,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,iBAAiB,GAClB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAI7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EACL,qBAAqB,EACrB,YAAY,GAEb,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,oBAAoB,EACpB,6BAA6B,EAC7B,oBAAoB,EACpB,oBAAoB,EACpB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,OAAO,EACL,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AAErB,MAAM,sBA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AAE,EAAE;YACtB,MAAM,CAAC,KAAK,CACV,wDAAwD,EACxD,yBAAyB,CAAC,GAAG,CAAC,CAC/B,CAAC;YACF,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;QACL,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;IAEF,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,OAAO,GAAG,CAAC,GAAU,EAAE,EAAE;YAC7B,cAAc,CAAC,OAAO,EAAE,CAAC;YACzB,eAAe,CAAC,KAAK,EAAE,CAAC;YACxB,aAAa,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,QAAiB,EAAE,EAAE;gBAChD,MAAM,CAAC,KAAK,CACV,kDAAkD,EAClD,yBAAyB,CAAC,QAAQ,CAAC,CACpC,CAAC;YACJ,CAAC,CAAC,CAAC;YACH,MAAM,CAAC,GAAG,CAAC,CAAC;QACd,CAAC,CAAC;QACF,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAElC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE;YACrC,UAAU,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC5C,MAAM,CAAC,IAAI,CAAC,qCAAqC,QAAQ,IAAI,IAAI,EAAE,CAAC,CAAC;YACrE,OAAO,CAAC,UAAU,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// HTTP hosting: express app assembly, security middleware wiring, the modern\n// per-request server factory, and listen-filter watcher gating on POST /mcp.\nimport { createMcpExpressApp } from '@modelcontextprotocol/express';\nimport { toNodeHandler } from '@modelcontextprotocol/node';\nimport type {\n McpHttpHandler,\n McpServerFactory,\n ServerNotifier,\n} from '@modelcontextprotocol/server';\nimport {\n createMcpHandler,\n DEFAULT_REQUEST_TIMEOUT_MSEC,\n ProtocolErrorCode,\n} from '@modelcontextprotocol/server';\n\nimport type { Server } from 'node:http';\nimport { createServer as createHttpServer } from 'node:http';\n\nimport type { Express, NextFunction, Request, Response } from 'express';\n\nimport { formatUnknownErrorMessage } from '../core/errors.js';\nimport { assertFleetRequestStateKey } from '../core/input-required.js';\nimport { Logger } from '../core/observability.js';\nimport { PageSnapshotStore } from '../core/page-store.js';\nimport { PathGuard } from '../core/path.js';\nimport type { ServerOptions } from '../core/path.js';\nimport { parseTrueEnvFlag } from '../core/primitives.js';\nimport { ResourceStore } from '../core/store.js';\nimport { MIB, parseEnvInt } from '../core/util.js';\nimport {\n createWatcherRegistry,\n MAX_WATCHERS,\n type WatcherRegistry,\n} from '../core/watcher-registry.js';\nimport {\n assertHttpBindingPolicy,\n assertHttpHostPolicy,\n bearerAuthMiddleware,\n computeAllowedOriginHostnames,\n corsOriginMiddleware,\n corsPreflightHandler,\n createRateLimiter,\n protectedResourceUrl,\n resolveAllowedHosts,\n resolveTrustProxySetting,\n sendJsonRpcError,\n} from '../http-policy.js';\nimport { createServer } from '../server.js';\nimport type { RuntimeConfig } from './shared.js';\nimport {\n isStructurallyValidListen,\n jsonRpcRequestId,\n listenSubscriptionUris,\n prepareListenWatchers,\n} from './shared.js';\n\nconst MAX_REQUEST_BODY_BYTES = parseEnvInt('FS_MAX_REQUEST_BYTES', 4 * MIB, 1024, 256 * MIB);\n\n/**\n * The code the SDK's own non-POST rejection carries. Not a `ProtocolErrorCode`\n * member — the enum has no `-32000` — so it is pinned here to keep the local\n * 405 envelope identical to the one the handler would have produced.\n */\nconst SDK_METHOD_NOT_ALLOWED_CODE = -32000;\n\n/** Body-parser rejections and anything else that reaches the end of the chain. */\nfunction errorHandlerMiddleware(\n err: Error & { status?: number },\n _req: Request,\n res: Response,\n next: NextFunction,\n): void {\n if (res.headersSent) {\n next(err);\n return;\n }\n if (err.status === 413) {\n sendJsonRpcError(res, 413, ProtocolErrorCode.InvalidRequest, 'Request body too large');\n return;\n }\n if (err.status === 400) {\n sendJsonRpcError(res, 400, ProtocolErrorCode.ParseError, 'Invalid JSON in request body');\n return;\n }\n Logger.error('[HTTP] Unhandled middleware error:', formatUnknownErrorMessage(err));\n sendJsonRpcError(res, 500, ProtocolErrorCode.InternalError, 'Internal Server Error');\n}\n\nfunction makeHttpModernFactory(\n options: ServerOptions,\n getNotifier: () => ServerNotifier,\n sharedRegistry: WatcherRegistry,\n sharedPathGuard: PathGuard,\n sharedStore: ResourceStore,\n sharedPageStore: PageSnapshotStore,\n apiKey: string | undefined,\n): McpServerFactory {\n return async ({ era }) => {\n const notifier = getNotifier();\n const c = await createServer(options, {\n watcherRegistry: sharedRegistry,\n notifier,\n pathGuard: sharedPathGuard,\n resourceStore: sharedStore,\n pageStore: sharedPageStore,\n era,\n ...(apiKey !== undefined ? { apiKey } : {}),\n });\n const previousOnClose = c.mcp.server.onclose;\n c.mcp.server.onclose = () => {\n previousOnClose?.();\n c.disposeRuntimeState();\n };\n return c.mcp;\n };\n}\n\nfunction setupExpressApp(\n httpHost: string,\n apiKey: string | undefined,\n allowedHosts: string[],\n modernNodeHandler: (req: Request, res: Response, parsedBody?: unknown) => Promise<void>,\n sharedPathGuard: PathGuard,\n sharedRegistry: WatcherRegistry,\n notifier: ServerNotifier,\n): Express {\n const allowedOriginHostnames = computeAllowedOriginHostnames(process.env['FS_ALLOWED_ORIGINS']);\n // Read once here and passed down, like every other env-derived policy input:\n // http-policy holds no state and reads no env of its own.\n const publicUrl = process.env['FS_PUBLIC_URL'];\n\n const app = createMcpExpressApp({\n host: httpHost,\n jsonLimit: `${MAX_REQUEST_BODY_BYTES}b`,\n ...(allowedHosts.length > 0 ? { allowedHosts: [...allowedHosts] } : {}),\n ...(allowedOriginHostnames.length > 0 ? { allowedOrigins: [...allowedOriginHostnames] } : {}),\n });\n\n const trustProxy = resolveTrustProxySetting(process.env['FS_TRUST_PROXY']);\n if (trustProxy !== undefined) {\n app.set('trust proxy', trustProxy);\n }\n\n if (allowedHosts.length === 0) {\n Logger.warn(\n '[HTTP] FS_ALLOW_UNRESTRICTED_HOSTS is set: binding globally without Host validation.',\n );\n }\n\n app.options('/mcp', corsPreflightHandler(allowedOriginHostnames));\n app.use('/mcp', corsOriginMiddleware(allowedOriginHostnames));\n\n // Unconditional: the spec's rate-limit MUST is not scoped to authenticated\n // binds. A keyless bind is loopback-only, so the cap is looser, not absent.\n const rpm = parseEnvInt('FS_RATE_LIMIT_RPM', apiKey ? 120 : 6_000, 1, 100_000);\n app.use('/mcp', createRateLimiter(rpm));\n\n if (apiKey && allowedHosts.length > 0) {\n const metadataHandler = (req: Request, res: Response): void => {\n const resource = protectedResourceUrl(req, true, publicUrl);\n if (!resource) {\n // Unreachable for the unrestricted case (the gate above excludes it),\n // but defend a FS_PUBLIC_URL parse failure with a bodyless\n // 404 — a generic OAuth client cannot parse a JSON-RPC error envelope.\n res.status(404).end();\n return;\n }\n res.header('Access-Control-Allow-Origin', '*');\n res.status(200).json({\n resource: resource.href,\n bearer_methods_supported: ['header'],\n resource_name: 'filesystem-mcp',\n });\n };\n app.get(\n ['/.well-known/oauth-protected-resource', '/.well-known/oauth-protected-resource/mcp'],\n metadataHandler,\n );\n }\n\n app.get('/healthz', (_req: Request, res: Response) => {\n res.status(200).json({\n status: 'ok',\n uptime: process.uptime(),\n });\n });\n\n app.use('/mcp', bearerAuthMiddleware(apiKey, allowedHosts.length > 0, publicUrl));\n\n const resourceUpdateSink = (uri: string): void => {\n notifier.resourceUpdated(uri);\n };\n\n app.post('/mcp', (req: Request, res: Response, next: NextFunction) => {\n void (async () => {\n const parsedBody = req.body as unknown;\n // Only a structurally valid listen gets watchers, mirroring the stdio\n // gate. A malformed one cannot succeed downstream, so attaching handles\n // for it only gives the response-close release something to undo — and\n // everything that is not a listen takes no watchers either way.\n if (!isStructurallyValidListen(parsedBody)) {\n await modernNodeHandler(req, res, parsedBody);\n return;\n }\n\n // Reject an over-cap listen before the ack so the client does not believe\n // every requested URI is watched when the watcher budget is exhausted.\n // The per-URI `capped` failure below would also reject, but only after\n // creating and tearing down every watcher up to the cap.\n const requestedUris = listenSubscriptionUris(parsedBody);\n // Only URIs without a live watcher consume a slot; a re-listen to an\n // already-watched URI just retains another lease.\n const newUris = requestedUris.filter((uri) => !sharedRegistry.hasWatcher(uri));\n const available = MAX_WATCHERS - sharedRegistry.size();\n if (newUris.length > available) {\n sendJsonRpcError(\n res,\n 400,\n ProtocolErrorCode.InvalidParams,\n `subscriptions/listen names ${newUris.length} not-yet-watched URIs but only ${available} watcher slots remain (cap ${MAX_WATCHERS}). Reduce the resourceSubscriptions list.`,\n jsonRpcRequestId(parsedBody),\n );\n return;\n }\n\n const prepared = await prepareListenWatchers(\n parsedBody,\n sharedPathGuard,\n sharedRegistry,\n resourceUpdateSink,\n );\n if (!prepared.ok) {\n sendJsonRpcError(\n res,\n 400,\n ProtocolErrorCode.InvalidParams,\n prepared.message,\n jsonRpcRequestId(parsedBody),\n );\n return;\n }\n\n let released = false;\n const release = (): void => {\n if (released) return;\n released = true;\n for (const uri of prepared.acquiredUris) sharedRegistry.release(uri);\n };\n if (prepared.acquiredUris.length > 0) {\n // The attach loop awaits per-URI path validation, so the client can be\n // gone by the time it returns. `close` fires once: a listener attached\n // after it would never run and every lease this batch took would leak\n // until process shutdown.\n if (res.closed || res.destroyed || res.writableEnded) release();\n else res.once('close', release);\n }\n\n try {\n await modernNodeHandler(req, res, parsedBody);\n } catch (error) {\n release();\n throw error;\n }\n })().catch(next);\n });\n\n // Answer non-POST here rather than handing it to `modernNodeHandler`. The\n // SDK's own 405 is byte-identical to this one, but it omits the `Allow`\n // header RFC 9110 §15.5.6 requires and routes every routine GET probe through\n // the handler's `onerror` — which this server logs at error level.\n app.all('/mcp', (_req: Request, res: Response) => {\n sendJsonRpcError(res, 405, SDK_METHOD_NOT_ALLOWED_CODE, 'Method not allowed.', null, {\n Allow: 'POST, OPTIONS',\n });\n });\n\n app.use(errorHandlerMiddleware);\n\n return app;\n}\n\nexport async function startHttpServer(\n port: number,\n options: ServerOptions,\n config: RuntimeConfig = {},\n): Promise<Server> {\n const httpHost = config.httpHost ?? '127.0.0.1';\n const { apiKey, eventBus } = config;\n const fleet = config.deploymentMode === 'fleet';\n assertHttpBindingPolicy(httpHost, apiKey);\n if (fleet && !apiKey) {\n throw new Error('Fleet deployment mode requires an API key.');\n }\n if (fleet && !eventBus) {\n throw new Error('Fleet deployment mode requires a shared event bus.');\n }\n assertFleetRequestStateKey(fleet);\n const allowedHosts = resolveAllowedHosts(httpHost, process.env['FS_ALLOWED_HOSTS']);\n assertHttpHostPolicy(\n httpHost,\n allowedHosts,\n parseTrueEnvFlag(process.env['FS_ALLOW_UNRESTRICTED_HOSTS'], 'FS_ALLOW_UNRESTRICTED_HOSTS'),\n );\n\n const sharedRegistry = createWatcherRegistry();\n // One store for the whole endpoint, same lifetime and same one-credential\n // trust argument as the shared guard below: a result a tool externalized in\n // one POST must survive to the follow-up resources/read, and the modern leg\n // builds a fresh McpServer per request so a per-request store would discard\n // it immediately.\n // Fires only from a tool call, which is long after `modernHandler` below is\n // constructed, so reading it from the closure is safe (same as `getNotifier`).\n const sharedStore = new ResourceStore(() => {\n modernHandler.notify.resourcesChanged();\n });\n const sharedPageStore = new PageSnapshotStore();\n // One guard for the whole endpoint. The modern leg builds a fresh McpServer\n // per request, so a per-instance guard would discard every accepted access\n // grant the moment the request ended — re-prompting on each subsequent call\n // and leaving the listen-watcher path validating against a stale allowed set.\n // Grant scope is therefore the endpoint, not the connection: with API_KEY set\n // every caller presents the same key (one auth context by construction), and\n // without it the bind is loopback-only. Split into per-auth-context guards if\n // this ever serves more than one credential.\n const sharedPathGuard = new PathGuard(options, true);\n await sharedPathGuard.recomputeAllowedDirectories();\n\n const modernHandler: McpHttpHandler = createMcpHandler(\n makeHttpModernFactory(\n options,\n () => modernHandler.notify,\n sharedRegistry,\n sharedPathGuard,\n sharedStore,\n sharedPageStore,\n apiKey,\n ),\n {\n legacy: 'reject',\n ...(eventBus ? { bus: eventBus } : {}),\n onerror: (error: Error) => {\n Logger.error('[HTTP] modern leg error:', formatUnknownErrorMessage(error));\n },\n },\n );\n const modernNodeHandler = toNodeHandler(modernHandler);\n\n const app = setupExpressApp(\n httpHost,\n apiKey,\n allowedHosts,\n modernNodeHandler,\n sharedPathGuard,\n sharedRegistry,\n modernHandler.notify,\n );\n\n const httpServer = createHttpServer(app);\n // Must exceed the idle timeout of any proxy in front of this server, or the\n // proxy reuses connections the server already closed (intermittent 502s).\n const keepAliveMs = parseEnvInt('FS_KEEPALIVE_TIMEOUT_MS', 5_000, 1_000, 600_000);\n httpServer.keepAliveTimeout = keepAliveMs;\n httpServer.headersTimeout = keepAliveMs + 5_000;\n httpServer.requestTimeout = DEFAULT_REQUEST_TIMEOUT_MSEC;\n\n const onHttpServerError = (error: Error): void => {\n Logger.error('[HTTP] runtime server error', {\n host: httpHost,\n port,\n error: formatUnknownErrorMessage(error),\n });\n };\n httpServer.on('error', onHttpServerError);\n\n const originalClose = httpServer.close.bind(httpServer);\n httpServer.close = function (callback?: (error?: Error) => void) {\n sharedRegistry.destroy();\n sharedPageStore.clear();\n modernHandler\n .close()\n .then(() => {\n originalClose(callback);\n })\n .catch((err: unknown) => {\n Logger.error(\n '[HTTP] Error closing handler during HTTP server close:',\n formatUnknownErrorMessage(err),\n );\n originalClose(callback);\n });\n return httpServer;\n };\n\n return new Promise((resolve, reject) => {\n const onError = (err: Error) => {\n sharedRegistry.destroy();\n sharedPageStore.clear();\n modernHandler.close().catch((closeErr: unknown) => {\n Logger.error(\n '[HTTP] Error closing handler on startup failure:',\n formatUnknownErrorMessage(closeErr),\n );\n });\n reject(err);\n };\n httpServer.once('error', onError);\n\n httpServer.listen(port, httpHost, () => {\n httpServer.removeListener('error', onError);\n Logger.info(`[HTTP] Server listening on http://${httpHost}:${port}`);\n resolve(httpServer);\n });\n });\n}\n"]}
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/transport/http.ts"],"names":[],"mappings":"AAAA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,CAAC;QACd,CAAC,CAAC;QACF,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAElC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE;YACrC,UAAU,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC5C,MAAM,CAAC,IAAI,CAAC,qCAAqC,QAAQ,IAAI,IAAI,EAAE,CAAC,CAAC;YACrE,OAAO,CAAC,UAAU,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// HTTP hosting: express app assembly, security middleware wiring, the modern\n// per-request server factory, and listen-filter watcher gating on POST /mcp.\nimport { createMcpExpressApp } from '@modelcontextprotocol/express';\nimport { toNodeHandler } from '@modelcontextprotocol/node';\nimport type {\n McpHttpHandler,\n McpServerFactory,\n ServerNotifier,\n} from '@modelcontextprotocol/server';\nimport {\n createMcpHandler,\n DEFAULT_REQUEST_TIMEOUT_MSEC,\n ProtocolErrorCode,\n} from '@modelcontextprotocol/server';\n\nimport type { Server } from 'node:http';\nimport { createServer as createHttpServer } from 'node:http';\n\nimport type { Express, NextFunction, Request, Response } from 'express';\n\nimport { formatUnknownErrorMessage } from '../core/errors.js';\nimport { Logger } from '../core/observability.js';\nimport { PageSnapshotStore } from '../core/page-store.js';\nimport { PathGuard } from '../core/path.js';\nimport type { ServerOptions } from '../core/path.js';\nimport { parseTrueEnvFlag } from '../core/primitives.js';\nimport { ResourceStore } from '../core/store.js';\nimport { MIB, parseEnvInt } from '../core/util.js';\nimport {\n createWatcherRegistry,\n MAX_WATCHERS,\n type WatcherRegistry,\n} from '../core/watcher-registry.js';\nimport {\n assertHttpBindingPolicy,\n assertHttpHostPolicy,\n bearerAuthMiddleware,\n computeAllowedOriginHostnames,\n corsOriginMiddleware,\n corsPreflightHandler,\n createRateLimiter,\n protectedResourceUrl,\n resolveAllowedHosts,\n resolveTrustProxySetting,\n sendJsonRpcError,\n} from '../http-policy.js';\nimport { createServer } from '../server.js';\nimport type { RuntimeConfig } from './shared.js';\nimport {\n isStructurallyValidListen,\n jsonRpcRequestId,\n listenSubscriptionUris,\n prepareListenWatchers,\n} from './shared.js';\n\nconst MAX_REQUEST_BODY_BYTES = parseEnvInt('FS_MAX_REQUEST_BYTES', 4 * MIB, 1024, 256 * MIB);\n\n/**\n * The code the SDK's own non-POST rejection carries. Not a `ProtocolErrorCode`\n * member — the enum has no `-32000` — so it is pinned here to keep the local\n * 405 envelope identical to the one the handler would have produced.\n */\nconst SDK_METHOD_NOT_ALLOWED_CODE = -32000;\n\n/** Body-parser rejections and anything else that reaches the end of the chain. */\nfunction errorHandlerMiddleware(\n err: Error & { status?: number },\n _req: Request,\n res: Response,\n next: NextFunction,\n): void {\n if (res.headersSent) {\n next(err);\n return;\n }\n if (err.status === 413) {\n sendJsonRpcError(res, 413, ProtocolErrorCode.InvalidRequest, 'Request body too large');\n return;\n }\n if (err.status === 400) {\n sendJsonRpcError(res, 400, ProtocolErrorCode.ParseError, 'Invalid JSON in request body');\n return;\n }\n Logger.error('[HTTP] Unhandled middleware error:', formatUnknownErrorMessage(err));\n sendJsonRpcError(res, 500, ProtocolErrorCode.InternalError, 'Internal Server Error');\n}\n\nfunction makeHttpModernFactory(\n options: ServerOptions,\n getNotifier: () => ServerNotifier,\n sharedRegistry: WatcherRegistry,\n sharedPathGuard: PathGuard,\n sharedStore: ResourceStore,\n sharedPageStore: PageSnapshotStore,\n apiKey: string | undefined,\n): McpServerFactory {\n return async ({ era }) => {\n const notifier = getNotifier();\n const c = await createServer(options, {\n watcherRegistry: sharedRegistry,\n notifier,\n pathGuard: sharedPathGuard,\n resourceStore: sharedStore,\n pageStore: sharedPageStore,\n era,\n ...(apiKey !== undefined ? { apiKey } : {}),\n });\n const previousOnClose = c.mcp.server.onclose;\n c.mcp.server.onclose = () => {\n previousOnClose?.();\n c.disposeRuntimeState();\n };\n return c.mcp;\n };\n}\n\nfunction setupExpressApp(\n httpHost: string,\n apiKey: string | undefined,\n allowedHosts: string[],\n modernNodeHandler: (req: Request, res: Response, parsedBody?: unknown) => Promise<void>,\n sharedPathGuard: PathGuard,\n sharedRegistry: WatcherRegistry,\n notifier: ServerNotifier,\n): Express {\n const allowedOriginHostnames = computeAllowedOriginHostnames(process.env['FS_ALLOWED_ORIGINS']);\n // Read once here and passed down, like every other env-derived policy input:\n // http-policy holds no state and reads no env of its own.\n const publicUrl = process.env['FS_PUBLIC_URL'];\n\n const app = createMcpExpressApp({\n host: httpHost,\n jsonLimit: `${MAX_REQUEST_BODY_BYTES}b`,\n ...(allowedHosts.length > 0 ? { allowedHosts: [...allowedHosts] } : {}),\n ...(allowedOriginHostnames.length > 0 ? { allowedOrigins: [...allowedOriginHostnames] } : {}),\n });\n\n const trustProxy = resolveTrustProxySetting(process.env['FS_TRUST_PROXY']);\n if (trustProxy !== undefined) {\n app.set('trust proxy', trustProxy);\n }\n\n if (allowedHosts.length === 0) {\n Logger.warn(\n '[HTTP] FS_ALLOW_UNRESTRICTED_HOSTS is set: binding globally without Host validation.',\n );\n }\n\n app.options('/mcp', corsPreflightHandler(allowedOriginHostnames));\n app.use('/mcp', corsOriginMiddleware(allowedOriginHostnames));\n\n // Unconditional: the spec's rate-limit MUST is not scoped to authenticated\n // binds. A keyless bind is loopback-only, so the cap is looser, not absent.\n const rpm = parseEnvInt('FS_RATE_LIMIT_RPM', apiKey ? 120 : 6_000, 1, 100_000);\n app.use('/mcp', createRateLimiter(rpm));\n\n if (apiKey && allowedHosts.length > 0) {\n const metadataHandler = (req: Request, res: Response): void => {\n const resource = protectedResourceUrl(req, true, publicUrl);\n if (!resource) {\n // Unreachable for the unrestricted case (the gate above excludes it),\n // but defend a FS_PUBLIC_URL parse failure with a bodyless\n // 404 — a generic OAuth client cannot parse a JSON-RPC error envelope.\n res.status(404).end();\n return;\n }\n res.header('Access-Control-Allow-Origin', '*');\n res.status(200).json({\n resource: resource.href,\n bearer_methods_supported: ['header'],\n resource_name: 'filesystem-mcp',\n });\n };\n app.get(\n ['/.well-known/oauth-protected-resource', '/.well-known/oauth-protected-resource/mcp'],\n metadataHandler,\n );\n }\n\n app.get('/healthz', (_req: Request, res: Response) => {\n res.status(200).json({\n status: 'ok',\n uptime: process.uptime(),\n });\n });\n\n app.use('/mcp', bearerAuthMiddleware(apiKey, allowedHosts.length > 0, publicUrl));\n\n const resourceUpdateSink = (uri: string): void => {\n notifier.resourceUpdated(uri);\n };\n\n app.post('/mcp', (req: Request, res: Response, next: NextFunction) => {\n void (async () => {\n const parsedBody = req.body as unknown;\n // Only a structurally valid listen gets watchers, mirroring the stdio\n // gate. A malformed one cannot succeed downstream, so attaching handles\n // for it only gives the response-close release something to undo — and\n // everything that is not a listen takes no watchers either way.\n if (!isStructurallyValidListen(parsedBody)) {\n await modernNodeHandler(req, res, parsedBody);\n return;\n }\n\n // Reject an over-cap listen before the ack so the client does not believe\n // every requested URI is watched when the watcher budget is exhausted.\n // The per-URI `capped` failure below would also reject, but only after\n // creating and tearing down every watcher up to the cap.\n const requestedUris = listenSubscriptionUris(parsedBody);\n // Only URIs without a live watcher consume a slot; a re-listen to an\n // already-watched URI just retains another lease.\n const newUris = requestedUris.filter((uri) => !sharedRegistry.hasWatcher(uri));\n const available = MAX_WATCHERS - sharedRegistry.size();\n if (newUris.length > available) {\n sendJsonRpcError(\n res,\n 400,\n ProtocolErrorCode.InvalidParams,\n `subscriptions/listen names ${newUris.length} not-yet-watched URIs but only ${available} watcher slots remain (cap ${MAX_WATCHERS}). Reduce the resourceSubscriptions list.`,\n jsonRpcRequestId(parsedBody),\n );\n return;\n }\n\n const prepared = await prepareListenWatchers(\n parsedBody,\n sharedPathGuard,\n sharedRegistry,\n resourceUpdateSink,\n );\n if (!prepared.ok) {\n sendJsonRpcError(\n res,\n 400,\n ProtocolErrorCode.InvalidParams,\n prepared.message,\n jsonRpcRequestId(parsedBody),\n );\n return;\n }\n\n let released = false;\n const release = (): void => {\n if (released) return;\n released = true;\n for (const uri of prepared.acquiredUris) sharedRegistry.release(uri);\n };\n if (prepared.acquiredUris.length > 0) {\n // The attach loop awaits per-URI path validation, so the client can be\n // gone by the time it returns. `close` fires once: a listener attached\n // after it would never run and every lease this batch took would leak\n // until process shutdown.\n if (res.closed || res.destroyed || res.writableEnded) release();\n else res.once('close', release);\n }\n\n try {\n await modernNodeHandler(req, res, parsedBody);\n } catch (error) {\n release();\n throw error;\n }\n })().catch(next);\n });\n\n // Answer non-POST here rather than handing it to `modernNodeHandler`. The\n // SDK's own 405 is byte-identical to this one, but it omits the `Allow`\n // header RFC 9110 §15.5.6 requires and routes every routine GET probe through\n // the handler's `onerror` — which this server logs at error level.\n app.all('/mcp', (_req: Request, res: Response) => {\n sendJsonRpcError(res, 405, SDK_METHOD_NOT_ALLOWED_CODE, 'Method not allowed.', null, {\n Allow: 'POST, OPTIONS',\n });\n });\n\n app.use(errorHandlerMiddleware);\n\n return app;\n}\n\nexport async function startHttpServer(\n port: number,\n options: ServerOptions,\n config: RuntimeConfig = {},\n): Promise<Server> {\n const httpHost = config.httpHost ?? '127.0.0.1';\n const { apiKey } = config;\n assertHttpBindingPolicy(httpHost, apiKey);\n const allowedHosts = resolveAllowedHosts(httpHost, process.env['FS_ALLOWED_HOSTS']);\n assertHttpHostPolicy(\n httpHost,\n allowedHosts,\n parseTrueEnvFlag(process.env['FS_ALLOW_UNRESTRICTED_HOSTS'], 'FS_ALLOW_UNRESTRICTED_HOSTS'),\n );\n\n const sharedRegistry = createWatcherRegistry();\n // One store for the whole endpoint, same lifetime and same one-credential\n // trust argument as the shared guard below: a result a tool externalized in\n // one POST must survive to the follow-up resources/read, and the modern leg\n // builds a fresh McpServer per request so a per-request store would discard\n // it immediately.\n // Fires only from a tool call, which is long after `modernHandler` below is\n // constructed, so reading it from the closure is safe (same as `getNotifier`).\n const sharedStore = new ResourceStore(() => {\n modernHandler.notify.resourcesChanged();\n });\n const sharedPageStore = new PageSnapshotStore();\n // One guard for the whole endpoint. The modern leg builds a fresh McpServer\n // per request, so a per-instance guard would discard every accepted access\n // grant the moment the request ended — re-prompting on each subsequent call\n // and leaving the listen-watcher path validating against a stale allowed set.\n // Grant scope is therefore the endpoint, not the connection: with API_KEY set\n // every caller presents the same key (one auth context by construction), and\n // without it the bind is loopback-only. Split into per-auth-context guards if\n // this ever serves more than one credential.\n const sharedPathGuard = new PathGuard(options, true);\n await sharedPathGuard.recomputeAllowedDirectories();\n\n const modernHandler: McpHttpHandler = createMcpHandler(\n makeHttpModernFactory(\n options,\n () => modernHandler.notify,\n sharedRegistry,\n sharedPathGuard,\n sharedStore,\n sharedPageStore,\n apiKey,\n ),\n {\n legacy: 'reject',\n onerror: (error: Error) => {\n Logger.error('[HTTP] modern leg error:', formatUnknownErrorMessage(error));\n },\n },\n );\n const modernNodeHandler = toNodeHandler(modernHandler);\n\n const app = setupExpressApp(\n httpHost,\n apiKey,\n allowedHosts,\n modernNodeHandler,\n sharedPathGuard,\n sharedRegistry,\n modernHandler.notify,\n );\n\n const httpServer = createHttpServer(app);\n // Must exceed the idle timeout of any proxy in front of this server, or the\n // proxy reuses connections the server already closed (intermittent 502s).\n const keepAliveMs = parseEnvInt('FS_KEEPALIVE_TIMEOUT_MS', 5_000, 1_000, 600_000);\n httpServer.keepAliveTimeout = keepAliveMs;\n httpServer.headersTimeout = keepAliveMs + 5_000;\n httpServer.requestTimeout = DEFAULT_REQUEST_TIMEOUT_MSEC;\n\n const onHttpServerError = (error: Error): void => {\n Logger.error('[HTTP] runtime server error', {\n host: httpHost,\n port,\n error: formatUnknownErrorMessage(error),\n });\n };\n httpServer.on('error', onHttpServerError);\n\n const originalClose = httpServer.close.bind(httpServer);\n httpServer.close = function (callback?: (error?: Error) => void) {\n sharedRegistry.destroy();\n sharedPageStore.clear();\n modernHandler\n .close()\n .then(() => {\n originalClose(callback);\n })\n .catch((err: unknown) => {\n Logger.error(\n '[HTTP] Error closing handler during HTTP server close:',\n formatUnknownErrorMessage(err),\n );\n originalClose(callback);\n });\n return httpServer;\n };\n\n return new Promise((resolve, reject) => {\n const onError = (err: Error) => {\n sharedRegistry.destroy();\n sharedPageStore.clear();\n modernHandler.close().catch((closeErr: unknown) => {\n Logger.error(\n '[HTTP] Error closing handler on startup failure:',\n formatUnknownErrorMessage(closeErr),\n );\n });\n reject(err);\n };\n httpServer.once('error', onError);\n\n httpServer.listen(port, httpHost, () => {\n httpServer.removeListener('error', onError);\n Logger.info(`[HTTP] Server listening on http://${httpHost}:${port}`);\n resolve(httpServer);\n });\n });\n}\n"]}
@@ -1,4 +1,3 @@
1
- import type { ServerEventBus } from '@modelcontextprotocol/server';
2
1
  import type { PathGuard } from '../core/path.js';
3
2
  import { type WatcherRegistry } from '../core/watcher-registry.js';
4
3
  /**
@@ -12,10 +11,6 @@ export interface RuntimeConfig {
12
11
  httpHost?: string;
13
12
  /** `--api-key` or `API_KEY`. Unset means open access (loopback dev mode). */
14
13
  apiKey?: string;
15
- /** Shared change-event bus for multi-instance HTTP deployments. Caller-owned. */
16
- eventBus?: ServerEventBus;
17
- /** Explicit topology; fleet mode requires shared state and event delivery. */
18
- deploymentMode?: 'single' | 'fleet';
19
14
  }
20
15
  /**
21
16
  * True when `message` really is a `subscriptions/listen` request, not merely a
@@ -1 +1 @@
1
- {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/transport/shared.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,6BAA6B,CAAC;AAErC;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC5B,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6EAA6E;IAC7E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iFAAiF;IACjF,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1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AAgB,CAAC,UAAU,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAG5E;AAED,wFAAwF;AACxF,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,OAAO,GAAG,MAAM,EAAE,CAYpE;AAED,MAAM,MAAM,iBAAiB,GACzB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,EAAE,CAAA;CAAE,GACtD;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAoBrD;;;GAGG;AACH,wBAAsB,qBAAqB,CACzC,UAAU,EAAE,OAAO,EACnB,SAAS,EAAE,SAAS,EACpB,QAAQ,EAAE,eAAe,EACzB,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,GAC5B,OAAO,CAAC,iBAAiB,CAAC,CAY5B"}
@@ -1,3 +1,7 @@
1
+ // Pieces both transport legs share: the runtime config contract and the
2
+ // `subscriptions/listen` watcher-preparation ladder. stdio and HTTP gate the
3
+ // same message shape; only where the lease is released differs (connection
4
+ // close vs response close).
1
5
  import { specTypeSchemas } from '@modelcontextprotocol/server';
2
6
  import { formatUnknownErrorMessage } from '../core/errors.js';
3
7
  import { MAX_WATCHERS, } from '../core/watcher-registry.js';
@@ -1 +1 @@
1
- {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/transport/shared.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAE/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EACL,YAAY,GAGb,MAAM,6BAA6B,CAAC;AAmBrC;;;;;;;GAOG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAgB;IACxD,MAAM,MAAM,GAAG,eAAe,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,QAAQ,C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ACzC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC7C,OAAO,uBAAuB,GAAG,KAAK,GAAG,EAAE,CAAC;AAC9C,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,UAAmB,EACnB,SAAoB,EACpB,QAAyB,EACzB,MAA6B;IAE7B,MAAM,IAAI,GAAG,sBAAsB,CAAC,UAAU,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9D,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACf,KAAK,MAAM,KAAK,IAAI,QAAQ;gBAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACtD,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,qBAAqB,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,CAAC;QACpE,CAAC;QACD,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC;AAC9C,CAAC","sourcesContent":["// Pieces both transport legs share: the runtime config contract and the\n// `subscriptions/listen` watcher-preparation ladder. stdio and HTTP gate the\n// same message shape; only where the lease is released differs (connection\n// close vs response close).\nimport type { ServerEventBus } from '@modelcontextprotocol/server';\nimport { specTypeSchemas } from '@modelcontextprotocol/server';\n\nimport { formatUnknownErrorMessage } from '../core/errors.js';\nimport type { PathGuard } from '../core/path.js';\nimport {\n MAX_WATCHERS,\n type WatcherAttachResult,\n type WatcherRegistry,\n} from '../core/watcher-registry.js';\n\n/**\n * Runtime inputs the CLI resolves once (flag, else the operator's env var) and\n * hands the transport. Separate from `ServerOptions` because that object is\n * `PathGuard`'s constructor argument: the filesystem guard has no use for a\n * bind address and no business holding a bearer secret.\n */\nexport interface RuntimeConfig {\n /** `--http-host` or `HTTP_HOST`. The HTTP bind defaults to loopback without it. */\n httpHost?: string;\n /** `--api-key` or `API_KEY`. Unset means open access (loopback dev mode). */\n apiKey?: string;\n /** Shared change-event bus for multi-instance HTTP deployments. Caller-owned. */\n eventBus?: ServerEventBus;\n /** Explicit topology; fleet mode requires shared state and event delivery. */\n deploymentMode?: 'single' | 'fleet';\n}\n\n/**\n * True when `message` really is a `subscriptions/listen` request, not merely a\n * body carrying that method string. Both legs gate watcher attachment on this:\n * a malformed listen cannot succeed downstream, so creating and tearing down\n * `fs.watch` handles for it is pure waste — and on HTTP the teardown depended on\n * the response-close listener firing. Non-listen bodies fail it too, which is\n * the same answer `listenSubscriptionUris` gives them.\n */\nexport function isStructurallyValidListen(message: unknown): boolean {\n const result = specTypeSchemas.SubscriptionsListenRequest['~standard'].validate(message);\n return !('issues' in result);\n}\n\n/** The request id of a parsed JSON-RPC body, for error-envelope echo. */\nexport function jsonRpcRequestId(parsedBody: unknown): string | number | null {\n const id = (parsedBody as { id?: unknown } | null | undefined)?.id;\n return typeof id === 'string' || typeof id === 'number' ? id : null;\n}\n\n/** The `resourceSubscriptions` URIs of a `subscriptions/listen` body, de-duplicated. */\nexport function listenSubscriptionUris(parsedBody: unknown): string[] {\n if (typeof parsedBody !== 'object' || parsedBody === null) return [];\n const body = parsedBody as {\n method?: unknown;\n params?: { notifications?: { resourceSubscriptions?: unknown } };\n };\n if (body.method !== 'subscriptions/listen') return [];\n const uris = body.params?.notifications?.resourceSubscriptions;\n if (!Array.isArray(uris)) return [];\n // De-duplicate: one attach must yield one ref-count, or the release below\n // decrements further than it incremented and tears down a live watcher.\n return [...new Set(uris.filter((uri): uri is string => typeof uri === 'string'))];\n}\n\nexport type ListenPreparation =\n | { readonly ok: true; readonly acquiredUris: string[] }\n | { readonly ok: false; readonly message: string };\n\nconst WATCHER_FAILURE_REASONS = {\n 'bad-uri': 'unsupported resource URI',\n capped: `watcher limit ${MAX_WATCHERS} reached`,\n 'attach-failed': 'filesystem watcher could not be created',\n stale: 'subscription was cancelled during setup',\n} as const;\n\nfunction watcherFailureMessage(\n uri: string,\n result: Exclude<WatcherAttachResult, { ok: true }>,\n): string {\n const why =\n result.reason === 'invalid-path'\n ? formatUnknownErrorMessage(result.error)\n : WATCHER_FAILURE_REASONS[result.reason];\n return `Cannot subscribe to ${uri}: ${why}`;\n}\n\n/**\n * Prepare every filesystem watcher named by a `subscriptions/listen` filter.\n * The batch is all-or-nothing: a failed URI releases each prior lease.\n */\nexport async function prepareListenWatchers(\n parsedBody: unknown,\n pathGuard: PathGuard,\n registry: WatcherRegistry,\n notify: (uri: string) => void,\n): Promise<ListenPreparation> {\n const uris = listenSubscriptionUris(parsedBody);\n const acquired: string[] = [];\n for (const uri of uris) {\n const result = await registry.acquire(pathGuard, uri, notify);\n if (!result.ok) {\n for (const prior of acquired) registry.release(prior);\n return { ok: false, message: watcherFailureMessage(uri, result) };\n }\n acquired.push(uri);\n }\n return { ok: true, acquiredUris: acquired };\n}\n"]}
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/transport/shared.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,6EAA6E;AAC7E,2EAA2E;AAC3E,4BAA4B;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAE/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EACL,YAAY,GAGb,MAAM,6BAA6B,CAAC;AAerC;;;;;;;GAOG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAgB;IACxD,MAAM,MAAM,GAAG,eAAe,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzF,OAAO,CAAC,CAAC,QAAQ,IAAI,MAAM,CAAC,CAAC;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AuB,GAAG,KAAK,GAAG,EAAE,CAAC;AAC9C,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,UAAmB,EACnB,SAAoB,EACpB,QAAyB,EACzB,MAA6B;IAE7B,MAAM,IAAI,GAAG,sBAAsB,CAAC,UAAU,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9D,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACf,KAAK,MAAM,KAAK,IAAI,QAAQ;gBAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACtD,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,qBAAqB,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,CAAC;QACpE,CAAC;QACD,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC;AAC9C,CAAC","sourcesContent":["// Pieces both transport legs share: the runtime config contract and the\n// `subscriptions/listen` watcher-preparation ladder. stdio and HTTP gate the\n// same message shape; only where the lease is released differs (connection\n// close vs response close).\nimport { specTypeSchemas } from '@modelcontextprotocol/server';\n\nimport { formatUnknownErrorMessage } from '../core/errors.js';\nimport type { PathGuard } from '../core/path.js';\nimport {\n MAX_WATCHERS,\n type WatcherAttachResult,\n type WatcherRegistry,\n} from '../core/watcher-registry.js';\n\n/**\n * Runtime inputs the CLI resolves once (flag, else the operator's env var) and\n * hands the transport. Separate from `ServerOptions` because that object is\n * `PathGuard`'s constructor argument: the filesystem guard has no use for a\n * bind address and no business holding a bearer secret.\n */\nexport interface RuntimeConfig {\n /** `--http-host` or `HTTP_HOST`. The HTTP bind defaults to loopback without it. */\n httpHost?: string;\n /** `--api-key` or `API_KEY`. Unset means open access (loopback dev mode). */\n apiKey?: string;\n}\n\n/**\n * True when `message` really is a `subscriptions/listen` request, not merely a\n * body carrying that method string. Both legs gate watcher attachment on this:\n * a malformed listen cannot succeed downstream, so creating and tearing down\n * `fs.watch` handles for it is pure waste — and on HTTP the teardown depended on\n * the response-close listener firing. Non-listen bodies fail it too, which is\n * the same answer `listenSubscriptionUris` gives them.\n */\nexport function isStructurallyValidListen(message: unknown): boolean {\n const result = specTypeSchemas.SubscriptionsListenRequest['~standard'].validate(message);\n return !('issues' in result);\n}\n\n/** The request id of a parsed JSON-RPC body, for error-envelope echo. */\nexport function jsonRpcRequestId(parsedBody: unknown): string | number | null {\n const id = (parsedBody as { id?: unknown } | null | undefined)?.id;\n return typeof id === 'string' || typeof id === 'number' ? id : null;\n}\n\n/** The `resourceSubscriptions` URIs of a `subscriptions/listen` body, de-duplicated. */\nexport function listenSubscriptionUris(parsedBody: unknown): string[] {\n if (typeof parsedBody !== 'object' || parsedBody === null) return [];\n const body = parsedBody as {\n method?: unknown;\n params?: { notifications?: { resourceSubscriptions?: unknown } };\n };\n if (body.method !== 'subscriptions/listen') return [];\n const uris = body.params?.notifications?.resourceSubscriptions;\n if (!Array.isArray(uris)) return [];\n // De-duplicate: one attach must yield one ref-count, or the release below\n // decrements further than it incremented and tears down a live watcher.\n return [...new Set(uris.filter((uri): uri is string => typeof uri === 'string'))];\n}\n\nexport type ListenPreparation =\n | { readonly ok: true; readonly acquiredUris: string[] }\n | { readonly ok: false; readonly message: string };\n\nconst WATCHER_FAILURE_REASONS = {\n 'bad-uri': 'unsupported resource URI',\n capped: `watcher limit ${MAX_WATCHERS} reached`,\n 'attach-failed': 'filesystem watcher could not be created',\n stale: 'subscription was cancelled during setup',\n} as const;\n\nfunction watcherFailureMessage(\n uri: string,\n result: Exclude<WatcherAttachResult, { ok: true }>,\n): string {\n const why =\n result.reason === 'invalid-path'\n ? formatUnknownErrorMessage(result.error)\n : WATCHER_FAILURE_REASONS[result.reason];\n return `Cannot subscribe to ${uri}: ${why}`;\n}\n\n/**\n * Prepare every filesystem watcher named by a `subscriptions/listen` filter.\n * The batch is all-or-nothing: a failed URI releases each prior lease.\n */\nexport async function prepareListenWatchers(\n parsedBody: unknown,\n pathGuard: PathGuard,\n registry: WatcherRegistry,\n notify: (uri: string) => void,\n): Promise<ListenPreparation> {\n const uris = listenSubscriptionUris(parsedBody);\n const acquired: string[] = [];\n for (const uri of uris) {\n const result = await registry.acquire(pathGuard, uri, notify);\n if (!result.ok) {\n for (const prior of acquired) registry.release(prior);\n return { ok: false, message: watcherFailureMessage(uri, result) };\n }\n acquired.push(uri);\n }\n return { ok: true, acquiredUris: acquired };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@j0hanz/filesystem-mcp",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "mcpName": "io.github.j0hanz/filesystem-mcp",
5
5
  "description": "Secure filesystem MCP server for reading, writing, searching, diffing, and patching files.",
6
6
  "author": "j0hanz",
@@ -40,8 +40,7 @@
40
40
  "test": "node --test --import tsx \"__tests__/**/*.test.ts\"",
41
41
  "test:inspector": "node --test --import tsx \"__tests__/inspector-*.test.ts\"",
42
42
  "inspector": "npm run build && npx -y @modelcontextprotocol/inspector node dist/index.js",
43
- "tasks": "node scripts/tasks.mjs",
44
- "qa": "npm run build && node scripts/qa.mjs"
43
+ "tasks": "node scripts/tasks.mjs"
45
44
  },
46
45
  "keywords": [
47
46
  "mcp",