@j0hanz/filesystem-mcp 2.1.6 → 2.1.8

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 (102) hide show
  1. package/README.md +7 -7
  2. package/dist/cli.d.ts +1 -2
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +29 -34
  5. package/dist/cli.js.map +1 -1
  6. package/dist/core/concurrency.d.ts +4 -7
  7. package/dist/core/concurrency.d.ts.map +1 -1
  8. package/dist/core/concurrency.js +4 -12
  9. package/dist/core/concurrency.js.map +1 -1
  10. package/dist/core/cursor.d.ts.map +1 -1
  11. package/dist/core/cursor.js +8 -20
  12. package/dist/core/cursor.js.map +1 -1
  13. package/dist/core/fmt.d.ts +2 -1
  14. package/dist/core/fmt.d.ts.map +1 -1
  15. package/dist/core/fmt.js +8 -15
  16. package/dist/core/fmt.js.map +1 -1
  17. package/dist/core/fs.d.ts +0 -14
  18. package/dist/core/fs.d.ts.map +1 -1
  19. package/dist/core/fs.js +1 -0
  20. package/dist/core/fs.js.map +1 -1
  21. package/dist/core/glob.d.ts +0 -3
  22. package/dist/core/glob.d.ts.map +1 -1
  23. package/dist/core/glob.js +5 -27
  24. package/dist/core/glob.js.map +1 -1
  25. package/dist/core/input-required.d.ts +2 -2
  26. package/dist/core/input-required.d.ts.map +1 -1
  27. package/dist/core/input-required.js.map +1 -1
  28. package/dist/core/path-completer.d.ts.map +1 -1
  29. package/dist/core/path-completer.js +4 -27
  30. package/dist/core/path-completer.js.map +1 -1
  31. package/dist/core/path-utils.d.ts +1 -1
  32. package/dist/core/path-utils.d.ts.map +1 -1
  33. package/dist/core/path-utils.js +2 -2
  34. package/dist/core/path-utils.js.map +1 -1
  35. package/dist/core/path.d.ts +7 -9
  36. package/dist/core/path.d.ts.map +1 -1
  37. package/dist/core/path.js +24 -42
  38. package/dist/core/path.js.map +1 -1
  39. package/dist/core/read.d.ts.map +1 -1
  40. package/dist/core/read.js +6 -23
  41. package/dist/core/read.js.map +1 -1
  42. package/dist/core/schema.d.ts.map +1 -1
  43. package/dist/core/schema.js +19 -74
  44. package/dist/core/schema.js.map +1 -1
  45. package/dist/core/search.d.ts +30 -7
  46. package/dist/core/search.d.ts.map +1 -1
  47. package/dist/core/search.js +63 -21
  48. package/dist/core/search.js.map +1 -1
  49. package/dist/core/store.d.ts.map +1 -1
  50. package/dist/core/store.js +6 -17
  51. package/dist/core/store.js.map +1 -1
  52. package/dist/index.js +15 -42
  53. package/dist/index.js.map +1 -1
  54. package/dist/prompts.d.ts.map +1 -1
  55. package/dist/prompts.js +17 -25
  56. package/dist/prompts.js.map +1 -1
  57. package/dist/resources.d.ts +4 -4
  58. package/dist/resources.d.ts.map +1 -1
  59. package/dist/resources.js +7 -17
  60. package/dist/resources.js.map +1 -1
  61. package/dist/server.d.ts +1 -4
  62. package/dist/server.d.ts.map +1 -1
  63. package/dist/server.js +2 -7
  64. package/dist/server.js.map +1 -1
  65. package/dist/tools/define.d.ts.map +1 -1
  66. package/dist/tools/define.js +35 -61
  67. package/dist/tools/define.js.map +1 -1
  68. package/dist/tools/delete-file.d.ts.map +1 -1
  69. package/dist/tools/delete-file.js +30 -35
  70. package/dist/tools/delete-file.js.map +1 -1
  71. package/dist/tools/edit.d.ts.map +1 -1
  72. package/dist/tools/edit.js +8 -13
  73. package/dist/tools/edit.js.map +1 -1
  74. package/dist/tools/list.d.ts.map +1 -1
  75. package/dist/tools/list.js +3 -7
  76. package/dist/tools/list.js.map +1 -1
  77. package/dist/tools/move.d.ts.map +1 -1
  78. package/dist/tools/move.js +2 -4
  79. package/dist/tools/move.js.map +1 -1
  80. package/dist/tools/progress.d.ts +1 -1
  81. package/dist/tools/progress.d.ts.map +1 -1
  82. package/dist/tools/progress.js.map +1 -1
  83. package/dist/tools/read.d.ts.map +1 -1
  84. package/dist/tools/read.js +36 -42
  85. package/dist/tools/read.js.map +1 -1
  86. package/dist/tools/replace-in-files.d.ts.map +1 -1
  87. package/dist/tools/replace-in-files.js +25 -42
  88. package/dist/tools/replace-in-files.js.map +1 -1
  89. package/dist/tools/search-content.d.ts.map +1 -1
  90. package/dist/tools/search-content.js +3 -25
  91. package/dist/tools/search-content.js.map +1 -1
  92. package/dist/tools/stat.d.ts.map +1 -1
  93. package/dist/tools/stat.js +9 -37
  94. package/dist/tools/stat.js.map +1 -1
  95. package/dist/transport/http-policy.d.ts +18 -15
  96. package/dist/transport/http-policy.d.ts.map +1 -1
  97. package/dist/transport/http-policy.js +29 -39
  98. package/dist/transport/http-policy.js.map +1 -1
  99. package/dist/transport/http.d.ts.map +1 -1
  100. package/dist/transport/http.js +29 -39
  101. package/dist/transport/http.js.map +1 -1
  102. package/package.json +4 -7
@@ -1 +1 @@
1
- {"version":3,"file":"search.js","sourceRoot":"","sources":["../../src/core/search.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAGrC,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAExC,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAkB,MAAM,WAAW,CAAC;AAExD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAgB/C,+EAA+E;AAC/E,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAErC;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,YAAY,CAAC,OAAe,EAAE,UAA+B,EAAE;IAC7E,MAAM,KAAK,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACnD,IAAI,CAAC;QACH,OAAO,IAAI,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACjC,CA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AC,IAAI,EAAE,CAAC,CAAC;IACrC,CAAC;IAED,yEAAyE;IACzE,mEAAmE;IACnE,IAAI,OAAO,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;QAC9B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC3E,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACvD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAE,CAAC;IACxC,IAAI,OAAO,CAAC,MAAM,IAAI,UAAU;QAAE,OAAO,CAAC,aAAa,EAAE,CAAC;IAC1D,IAAI,QAAQ,CAAC,cAAc;QAAE,OAAO,CAAC,QAAQ,EAAE,CAAC;IAChD,qEAAqE;IACrE,oEAAoE;IACpE,MAAM,aAAa,GAAG,OAAO,CAAC,OAAO,EAA0C,CAAC;IAEhF,OAAO;QACL,QAAQ,EAAE,SAAS;QACnB,OAAO;QACP,OAAO,EAAE;YACP,OAAO,EAAE,OAAO,CAAC,MAAM;YACvB,YAAY;YACZ,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,mBAAmB,EAAE,QAAQ,CAAC,mBAAmB;YACjD,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5C;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { stat as fsStat, readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\n\nimport type { RE2ExecArray } from '@adguard/re2-wasm';\nimport { RE2 } from '@adguard/re2-wasm';\n\nimport { StopReasonTracker } from './concurrency.js';\nimport { globEntries, type GlobEntry } from './glob.js';\nimport type { PathGuard } from './path.js';\nimport { escapeRegexLiteral } from './primitives.js';\nimport { getMaxTextFileSize } from './util.js';\n\ninterface SearchResult {\n file: string;\n line: number;\n /** 0-indexed column of the first occurrence on the line. */\n column: number;\n content: string;\n matchCount?: number;\n}\n\nexport type Regex = RE2;\nexport interface RegexCompileOptions {\n caseSensitive?: boolean;\n}\n\n/** Occurrence-counting bound, so one pathological line cannot spin forever. */\nconst MAX_MATCHES_PER_LINE = 100_000;\n\n/**\n * Compile a pattern on RE2 rather than on V8's irregexp.\n *\n * Patterns arrive from the MCP client, so a backtracking engine would let one\n * request pin the event loop with no way out: an abort signal cannot preempt a\n * synchronous `exec`, and on stdio that wedges the whole server. RE2 matches in\n * time linear in the input and cannot backtrack at all, so the hazard is gone\n * rather than bounded.\n *\n * RE2 rejects the constructs the tool schema documents as unsupported —\n * lookahead, lookbehind, backreferences — with its own {@link SyntaxError},\n * which the tool layer turns into a normal tool error. It always matches in\n * Unicode mode and requires the `u` flag to say so.\n *\n * Every compiled pattern owns memory in re2-wasm's fixed 16 MB heap, which\n * `ALLOW_MEMORY_GROWTH` is off for. re2-wasm never frees it and a\n * FinalizationRegistry does not keep up (V8 sees no pressure from the wasm\n * heap), so exhaustion is an emscripten `abort()` that kills regex search for\n * the rest of the process. Every caller MUST pass the result to\n * {@link freeRegex} when it is done with it.\n */\nexport function compileRegex(pattern: string, options: RegexCompileOptions = {}): Regex {\n const flags = options.caseSensitive ? 'gu' : 'giu';\n try {\n return new RE2(pattern, flags);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n throw new SyntaxError(\n `${error.message} — lookahead, lookbehind, and backreferences are not supported.`,\n { cause: error },\n );\n }\n}\n\n/**\n * Release a compiled pattern's wasm memory. re2-wasm exposes no disposal of its\n * own, so this reaches the embind handle it holds privately; a version that\n * renames the field degrades to the pre-existing leak rather than throwing.\n * Idempotent — a second call on an already-freed handle is swallowed. Using a\n * {@link Regex} after freeing it is undefined behaviour in the wasm heap, so\n * free only in a `finally` that owns the compile.\n */\nexport function freeRegex(regex: Regex | undefined): void {\n const handle = (regex as unknown as { wrapper?: { delete?: () => void } } | undefined)?.wrapper;\n try {\n handle?.delete?.();\n } catch {\n // already deleted, or a re2-wasm build without embind disposal\n }\n}\n\n/**\n * Find non-overlapping occurrences of a global regex in a single line, reporting\n * the first match's column alongside the count. Guards zero-length matches\n * (e.g. `a*`) so they cannot loop forever.\n */\nfunction findLineMatches(\n regex: Regex,\n line: string,\n): { count: number; column: number } | undefined {\n regex.lastIndex = 0;\n let count = 0;\n let column = -1;\n let match: RE2ExecArray | null;\n while ((match = regex.exec(line)) !== null) {\n if (column === -1) column = match.index;\n count++;\n if (match.index === regex.lastIndex) regex.lastIndex++; // advance past zero-length match\n if (count >= MAX_MATCHES_PER_LINE) break;\n }\n return count > 0 ? { count, column } : undefined;\n}\n\nexport interface SearchContentOptions {\n caseSensitive?: boolean;\n isRegex?: boolean;\n maxResults?: number;\n filePattern?: string;\n excludePatterns?: string[];\n respectGitignore?: boolean;\n includeHidden?: boolean;\n maxDepth?: number;\n maxFileSize?: number;\n signal?: AbortSignal;\n}\n\nexport interface SearchContentOutcome {\n basePath: string;\n matches: SearchResult[];\n summary: {\n /**\n * Matching *lines*, one per entry in `matches` — not pattern occurrences.\n * A line with three occurrences counts once here and reports 3 in its own\n * `SearchResult.matchCount`.\n */\n matchingLines: number;\n filesScanned: number;\n filesMatched: number;\n truncated: boolean;\n /** Files the guard rejected or that could not be stat'd. */\n skippedInaccessible: number;\n /** Files skipped unread because they exceed maxFileSize. */\n skippedTooLarge: number;\n /**\n * `StoppedReason` narrowed to the stops these scans can produce: both call\n * only `hitMaxResults`/`hitAbort` (see concurrency.ts) — never\n * `hitMaxFiles`, which belongs to `replace_text`'s per-file cap.\n */\n stoppedReason?: 'maxResults' | 'timeout';\n };\n}\n\n/**\n * Owns the compiled pattern's lifetime. Pass `precompiled` to skip compiling\n * here — the caller compiled the same pattern with the same flags and keeps\n * owning the {@link freeRegex} call in that case.\n */\nexport async function searchContent(\n directory: string,\n pattern: string,\n options: SearchContentOptions,\n pathGuard: PathGuard,\n precompiled?: Regex,\n): Promise<SearchContentOutcome> {\n const regex =\n precompiled ??\n compileRegex(options.isRegex ? pattern || '' : escapeRegexLiteral(pattern || ''), {\n caseSensitive: Boolean(options.caseSensitive),\n });\n try {\n const matches: SearchResult[] = [];\n const maxResults = options.maxResults ?? 100;\n const maxFileSize = options.maxFileSize ?? getMaxTextFileSize();\n\n const entries = globEntries({\n cwd: directory,\n pattern: options.filePattern ?? '**/*',\n excludePatterns: options.excludePatterns ?? [],\n includeHidden: Boolean(options.includeHidden),\n respectGitignore: Boolean(options.respectGitignore),\n maxDepth: options.maxDepth ?? 100,\n suppressErrors: true,\n });\n\n let filesScanned = 0;\n let filesMatched = 0;\n let matchingLines = 0;\n let skippedTooLarge = 0;\n const counters = { skippedInaccessible: 0, stoppedByAbort: false };\n\n for await (const entry of guardedEntries(entries, pathGuard, options.signal, counters)) {\n if (matches.length >= maxResults) break;\n\n // Skip oversized files before reading to avoid unbounded memory use. Count\n // them: \"no matches\" for a reason other than the pattern must be visible.\n try {\n const stats = await fsStat(entry.path);\n if (stats.size > maxFileSize) {\n skippedTooLarge++;\n continue;\n }\n } catch {\n counters.skippedInaccessible++;\n continue;\n }\n\n filesScanned++;\n\n try {\n const content = await readFile(entry.path, { encoding: 'utf-8', signal: options.signal });\n const lines = content.split('\\n');\n let matchedFile = false;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line === undefined) continue;\n // One scan per line: findLineMatches resets lastIndex itself, so it\n // doubles as the \"does this line match\" test.\n const found = findLineMatches(regex, line);\n if (found) {\n matchedFile = true;\n matchingLines++;\n matches.push({\n file: entry.path,\n line: i + 1,\n column: found.column,\n content: line,\n matchCount: found.count,\n });\n if (matches.length >= maxResults) break;\n }\n }\n if (matchedFile) filesMatched++;\n } catch {\n // A read failure while the signal is aborted IS the abort, not an\n // unreadable file — stop rather than spend another iteration and then\n // report a cut-short scan as complete.\n if (options.signal?.aborted) {\n counters.stoppedByAbort = true;\n break;\n }\n // ignore read errors (e.g. binary files)\n }\n }\n\n const tracker = new StopReasonTracker();\n if (matches.length >= maxResults) tracker.hitMaxResults();\n if (counters.stoppedByAbort) tracker.hitAbort();\n // resolve() is StoppedReason | undefined, but this scan only records\n // maxResults/timeout stops (see the summary type's narrowing note).\n const stoppedReason = tracker.resolve() as 'maxResults' | 'timeout' | undefined;\n\n return {\n basePath: directory,\n matches,\n summary: {\n matchingLines,\n filesScanned,\n filesMatched,\n truncated: tracker.truncated,\n skippedInaccessible: counters.skippedInaccessible,\n skippedTooLarge,\n ...(stoppedReason ? { stoppedReason } : {}),\n },\n };\n } finally {\n if (precompiled === undefined) freeRegex(regex);\n }\n}\n\nasync function* guardedEntries(\n entries: AsyncIterable<GlobEntry>,\n pathGuard: PathGuard,\n signal: AbortSignal | undefined,\n counters: { skippedInaccessible: number; stoppedByAbort: boolean },\n): AsyncGenerator<GlobEntry> {\n // The signal carries both client cancellation and the tool's search timeout,\n // so an abort means \"return what we have, marked incomplete\" rather than\n // throw — but it must never be reported as a finished scan.\n for await (const entry of entries) {\n if (signal?.aborted) {\n counters.stoppedByAbort = true;\n return;\n }\n try {\n await pathGuard.validateExistingPath(entry.path);\n } catch {\n counters.skippedInaccessible++;\n continue;\n }\n yield entry;\n }\n}\n\nexport async function searchFiles(\n directory: string,\n pattern: string,\n excludePatterns: string[],\n options: {\n maxResults?: number;\n includeHidden?: boolean;\n sortBy?: 'name' | 'path';\n respectGitignore?: boolean;\n maxDepth?: number;\n signal?: AbortSignal;\n },\n pathGuard: PathGuard,\n): Promise<{\n basePath: string;\n results: { path: string }[];\n summary: {\n matched: number;\n filesScanned: number;\n truncated: boolean;\n skippedInaccessible: number;\n /** Narrowed like SearchContentOutcome's — scans never hit `hitMaxFiles`. */\n stoppedReason?: 'maxResults' | 'timeout';\n };\n}> {\n const maxResults = options.maxResults ?? 100;\n const entries = globEntries({\n cwd: directory,\n pattern,\n excludePatterns,\n includeHidden: Boolean(options.includeHidden),\n respectGitignore: Boolean(options.respectGitignore),\n maxDepth: options.maxDepth ?? 100,\n suppressErrors: true,\n });\n const results: { path: string }[] = [];\n let filesScanned = 0;\n const counters = { skippedInaccessible: 0, stoppedByAbort: false };\n\n for await (const entry of guardedEntries(entries, pathGuard, options.signal, counters)) {\n if (results.length >= maxResults) break;\n filesScanned++;\n results.push({ path: entry.path });\n }\n\n // Sorting — only name / path are supported; size / modified were removed\n // (the glob never collected stats, so they were always undefined).\n if (options.sortBy === 'name') {\n results.sort((a, b) => basename(a.path).localeCompare(basename(b.path)));\n } else {\n results.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n const tracker = new StopReasonTracker();\n if (results.length >= maxResults) tracker.hitMaxResults();\n if (counters.stoppedByAbort) tracker.hitAbort();\n // resolve() is StoppedReason | undefined, but this scan only records\n // maxResults/timeout stops (see the summary type's narrowing note).\n const stoppedReason = tracker.resolve() as 'maxResults' | 'timeout' | undefined;\n\n return {\n basePath: directory,\n results,\n summary: {\n matched: results.length,\n filesScanned,\n truncated: tracker.truncated,\n skippedInaccessible: counters.skippedInaccessible,\n ...(stoppedReason ? { stoppedReason } : {}),\n },\n };\n}\n"]}
1
+ {"version":3,"file":"search.js","sourceRoot":"","sources":["../../src/core/search.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAGrC,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAExC,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAkB,MAAM,WAAW,CAAC;AAExD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,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QAAQ,EAAE,CAAC;IAChD,qEAAqE;IACrE,oEAAoE;IACpE,MAAM,aAAa,GAAG,OAAO,CAAC,OAAO,EAA0C,CAAC;IAEhF,OAAO;QACL,QAAQ,EAAE,SAAS;QACnB,OAAO;QACP,OAAO,EAAE;YACP,OAAO,EAAE,OAAO,CAAC,MAAM;YACvB,YAAY;YACZ,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,mBAAmB,EAAE,QAAQ,CAAC,mBAAmB;YACjD,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5C;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { stat as fsStat, readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\n\nimport type { RE2ExecArray } from '@adguard/re2-wasm';\nimport { RE2 } from '@adguard/re2-wasm';\n\nimport { StopReasonTracker } from './concurrency.js';\nimport { globEntries, type GlobEntry } from './glob.js';\nimport type { PathGuard } from './path.js';\nimport { escapeRegexLiteral } from './primitives.js';\nimport { getMaxTextFileSize } from './util.js';\n\ninterface SearchResult {\n file: string;\n line: number;\n /** 0-indexed column of the first occurrence on the line. */\n column: number;\n content: string;\n matchCount?: number;\n}\n\nexport type Regex = RE2;\nexport interface RegexCompileOptions {\n caseSensitive?: boolean;\n}\n\n/** Occurrence-counting bound, so one pathological line cannot spin forever. */\nconst MAX_MATCHES_PER_LINE = 100_000;\n\n/**\n * Compile a pattern on RE2 rather than on V8's irregexp.\n *\n * Patterns arrive from the MCP client, so a backtracking engine would let one\n * request pin the event loop with no way out: an abort signal cannot preempt a\n * synchronous `exec`, and on stdio that wedges the whole server. RE2 matches in\n * time linear in the input and cannot backtrack at all, so the hazard is gone\n * rather than bounded.\n *\n * RE2 rejects the constructs the tool schema documents as unsupported —\n * lookahead, lookbehind, backreferences — with its own {@link SyntaxError},\n * which the tool layer turns into a normal tool error. It always matches in\n * Unicode mode and requires the `u` flag to say so.\n *\n * Every compiled pattern owns memory in re2-wasm's fixed 16 MB heap, which\n * `ALLOW_MEMORY_GROWTH` is off for. re2-wasm never frees it and a\n * FinalizationRegistry does not keep up (V8 sees no pressure from the wasm\n * heap), so exhaustion is an emscripten `abort()` that kills regex search for\n * the rest of the process. Every caller MUST pass the result to\n * {@link freeRegex} when it is done with it.\n */\nexport function compileRegex(pattern: string, options: RegexCompileOptions = {}): Regex {\n const flags = options.caseSensitive ? 'gu' : 'giu';\n try {\n return new RE2(pattern, flags);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n throw new SyntaxError(\n `${error.message} — lookahead, lookbehind, and backreferences are not supported.`,\n { cause: error },\n );\n }\n}\n\n/**\n * Release a compiled pattern's wasm memory. re2-wasm exposes no disposal of its\n * own, so this reaches the embind handle it holds privately; a version that\n * renames the field degrades to the pre-existing leak rather than throwing.\n * Idempotent — a second call on an already-freed handle is swallowed. Using a\n * {@link Regex} after freeing it is undefined behaviour in the wasm heap, so\n * free only in a `finally` that owns the compile.\n */\nexport function freeRegex(regex: Regex | undefined): void {\n const handle = (regex as unknown as { wrapper?: { delete?: () => void } } | undefined)?.wrapper;\n try {\n handle?.delete?.();\n } catch {\n // already deleted, or a re2-wasm build without embind disposal\n }\n}\n\nexport interface RegexMatch {\n /** The matched text. */\n text: string;\n /** Capture groups, 1-indexed in the pattern, 0-indexed here. */\n groups: (string | undefined)[];\n /** Named capture groups, when the pattern declares any. */\n named: Record<string, string> | undefined;\n /** Start offset in UTF-16 code units — usable with `String.prototype.slice`. */\n start: number;\n /** End offset in UTF-16 code units. */\n end: number;\n}\n\n/** Code-point length of `text`, i.e. its UTF-16 length minus its surrogate pairs. */\nfunction codePointLength(text: string): number {\n let length = 0;\n for (let i = 0; i < text.length; i++) {\n if ((text.charCodeAt(i) & 0xfc00) === 0xd800 && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n i++;\n }\n length++;\n }\n return length;\n}\n\n/**\n * Iterate a global pattern's non-overlapping matches with offsets JS can use.\n *\n * re2-wasm reports `index` and `lastIndex` in **code points**, while every JS\n * string operation indexes in UTF-16 code units. The two agree only until the\n * first astral character (most emoji), past which every offset is short by one\n * per surrogate pair — slicing on the raw index cuts into the middle of\n * neighbouring text. Its `lastIndex` bookkeeping is worse still: it adds the\n * match's UTF-16 length to a code-point index, so an astral character inside a\n * match can skip the next one. This is the single place that corrects both; no\n * caller should read `match.index` or `regex.lastIndex` directly.\n *\n * Zero-length matches (e.g. `a*`) advance by one code point so they cannot loop\n * forever. The regex is global and shared across calls, so `lastIndex` is reset\n * on entry.\n */\nexport function* execMatches(regex: Regex, text: string): Generator<RegexMatch, undefined> {\n regex.lastIndex = 0;\n // Cursor into `text`, carried forward across matches: RE2 reports them in\n // ascending order, so the walk is O(text) in total rather than per match.\n let cursorCp = 0;\n let cursorU16 = 0;\n let match: RE2ExecArray | null;\n while ((match = regex.exec(text)) !== null) {\n while (cursorCp < match.index && cursorU16 < text.length) {\n const isPair =\n (text.charCodeAt(cursorU16) & 0xfc00) === 0xd800 &&\n (text.charCodeAt(cursorU16 + 1) & 0xfc00) === 0xdc00;\n cursorU16 += isPair ? 2 : 1;\n cursorCp++;\n }\n const matched = match[0] ?? '';\n const start = cursorU16;\n yield {\n text: matched,\n groups: match.slice(1),\n named: match.groups,\n start,\n end: start + matched.length,\n };\n // Own the advance rather than trusting the wrapper's mixed-unit arithmetic.\n regex.lastIndex = match.index + (matched.length === 0 ? 1 : codePointLength(matched));\n }\n}\n\n/**\n * Find non-overlapping occurrences of a global regex in a single line, reporting\n * the first match's column alongside the count.\n */\nfunction findLineMatches(\n regex: Regex,\n line: string,\n): { count: number; column: number } | undefined {\n let count = 0;\n let column = -1;\n for (const match of execMatches(regex, line)) {\n if (column === -1) column = match.start;\n count++;\n if (count >= MAX_MATCHES_PER_LINE) break;\n }\n return count > 0 ? { count, column } : undefined;\n}\n\nexport interface SearchContentOptions {\n caseSensitive?: boolean;\n isRegex?: boolean;\n maxResults?: number;\n filePattern?: string;\n excludePatterns?: string[];\n respectGitignore?: boolean;\n includeHidden?: boolean;\n maxDepth?: number;\n signal?: AbortSignal;\n}\n\nexport interface SearchContentOutcome {\n basePath: string;\n matches: SearchResult[];\n summary: {\n /**\n * Matching *lines*, one per entry in `matches` — not pattern occurrences.\n * A line with three occurrences counts once here and reports 3 in its own\n * `SearchResult.matchCount`.\n */\n matchingLines: number;\n filesScanned: number;\n filesMatched: number;\n truncated: boolean;\n /** Files the guard rejected or that could not be stat'd. */\n skippedInaccessible: number;\n /** Files skipped unread because they exceed maxFileSize. */\n skippedTooLarge: number;\n /**\n * `StoppedReason` narrowed to the stops these scans can produce: both call\n * only `hitMaxResults`/`hitAbort` (see concurrency.ts) — never\n * `hitMaxFiles`, which belongs to `replace_text`'s per-file cap.\n */\n stoppedReason?: 'maxResults' | 'timeout';\n };\n}\n\nexport async function searchContent(\n directory: string,\n pattern: string,\n options: SearchContentOptions,\n pathGuard: PathGuard,\n): Promise<SearchContentOutcome> {\n const regex = compileRegex(options.isRegex ? pattern || '' : escapeRegexLiteral(pattern || ''), {\n caseSensitive: Boolean(options.caseSensitive),\n });\n try {\n const matches: SearchResult[] = [];\n const maxResults = options.maxResults ?? 100;\n const maxFileSize = getMaxTextFileSize();\n\n const entries = globEntries({\n cwd: directory,\n pattern: options.filePattern ?? '**/*',\n excludePatterns: options.excludePatterns ?? [],\n includeHidden: Boolean(options.includeHidden),\n respectGitignore: Boolean(options.respectGitignore),\n maxDepth: options.maxDepth ?? 100,\n suppressErrors: true,\n });\n\n let filesScanned = 0;\n let filesMatched = 0;\n let matchingLines = 0;\n let skippedTooLarge = 0;\n const counters = { skippedInaccessible: 0, stoppedByAbort: false };\n\n for await (const entry of guardedEntries(entries, pathGuard, options.signal, counters)) {\n if (matches.length >= maxResults) break;\n\n // Skip oversized files before reading to avoid unbounded memory use. Count\n // them: \"no matches\" for a reason other than the pattern must be visible.\n try {\n const stats = await fsStat(entry.path);\n if (stats.size > maxFileSize) {\n skippedTooLarge++;\n continue;\n }\n } catch {\n counters.skippedInaccessible++;\n continue;\n }\n\n filesScanned++;\n\n try {\n const content = await readFile(entry.path, { encoding: 'utf-8', signal: options.signal });\n const lines = content.split('\\n');\n let matchedFile = false;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line === undefined) continue;\n // One scan per line: findLineMatches resets lastIndex itself, so it\n // doubles as the \"does this line match\" test.\n const found = findLineMatches(regex, line);\n if (found) {\n matchedFile = true;\n matchingLines++;\n matches.push({\n file: entry.path,\n line: i + 1,\n column: found.column,\n content: line,\n matchCount: found.count,\n });\n if (matches.length >= maxResults) break;\n }\n }\n if (matchedFile) filesMatched++;\n } catch {\n // A read failure while the signal is aborted IS the abort, not an\n // unreadable file — stop rather than spend another iteration and then\n // report a cut-short scan as complete.\n if (options.signal?.aborted) {\n counters.stoppedByAbort = true;\n break;\n }\n // ignore read errors (e.g. binary files)\n }\n }\n\n const tracker = new StopReasonTracker();\n if (matches.length >= maxResults) tracker.hitMaxResults();\n if (counters.stoppedByAbort) tracker.hitAbort();\n // resolve() is StoppedReason | undefined, but this scan only records\n // maxResults/timeout stops (see the summary type's narrowing note).\n const stoppedReason = tracker.resolve() as 'maxResults' | 'timeout' | undefined;\n\n return {\n basePath: directory,\n matches,\n summary: {\n matchingLines,\n filesScanned,\n filesMatched,\n truncated: tracker.truncated,\n skippedInaccessible: counters.skippedInaccessible,\n skippedTooLarge,\n ...(stoppedReason ? { stoppedReason } : {}),\n },\n };\n } finally {\n freeRegex(regex);\n }\n}\n\nasync function* guardedEntries(\n entries: AsyncIterable<GlobEntry>,\n pathGuard: PathGuard,\n signal: AbortSignal | undefined,\n counters: { skippedInaccessible: number; stoppedByAbort: boolean },\n): AsyncGenerator<GlobEntry> {\n // The signal carries both client cancellation and the tool's search timeout,\n // so an abort means \"return what we have, marked incomplete\" rather than\n // throw — but it must never be reported as a finished scan.\n for await (const entry of entries) {\n if (signal?.aborted) {\n counters.stoppedByAbort = true;\n return;\n }\n try {\n await pathGuard.validateExistingPath(entry.path);\n } catch {\n counters.skippedInaccessible++;\n continue;\n }\n yield entry;\n }\n}\n\nexport async function searchFiles(\n directory: string,\n pattern: string,\n excludePatterns: string[],\n options: {\n maxResults?: number;\n includeHidden?: boolean;\n sortBy?: 'name' | 'path';\n respectGitignore?: boolean;\n maxDepth?: number;\n signal?: AbortSignal;\n },\n pathGuard: PathGuard,\n): Promise<{\n basePath: string;\n results: { path: string }[];\n summary: {\n matched: number;\n filesScanned: number;\n truncated: boolean;\n skippedInaccessible: number;\n /** Narrowed like SearchContentOutcome's — scans never hit `hitMaxFiles`. */\n stoppedReason?: 'maxResults' | 'timeout';\n };\n}> {\n const maxResults = options.maxResults ?? 100;\n const entries = globEntries({\n cwd: directory,\n pattern,\n excludePatterns,\n includeHidden: Boolean(options.includeHidden),\n respectGitignore: Boolean(options.respectGitignore),\n maxDepth: options.maxDepth ?? 100,\n suppressErrors: true,\n });\n const results: { path: string }[] = [];\n let filesScanned = 0;\n const counters = { skippedInaccessible: 0, stoppedByAbort: false };\n\n for await (const entry of guardedEntries(entries, pathGuard, options.signal, counters)) {\n if (results.length >= maxResults) break;\n filesScanned++;\n results.push({ path: entry.path });\n }\n\n // Sorting — only name / path are supported; size / modified were removed\n // (the glob never collected stats, so they were always undefined).\n if (options.sortBy === 'name') {\n results.sort((a, b) => basename(a.path).localeCompare(basename(b.path)));\n } else {\n results.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n const tracker = new StopReasonTracker();\n if (results.length >= maxResults) tracker.hitMaxResults();\n if (counters.stoppedByAbort) tracker.hitAbort();\n // resolve() is StoppedReason | undefined, but this scan only records\n // maxResults/timeout stops (see the summary type's narrowing note).\n const stoppedReason = tracker.resolve() as 'maxResults' | 'timeout' | undefined;\n\n return {\n basePath: directory,\n results,\n summary: {\n matched: results.length,\n filesScanned,\n truncated: tracker.truncated,\n skippedInaccessible: counters.skippedInaccessible,\n ...(stoppedReason ? { stoppedReason } : {}),\n },\n };\n}\n"]}
@@ -1 +1 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EAAE,YAAY,CAAC;CACpB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,aAAa,EACpB,IAAI,EAAE,MAAM,EAIZ,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,OAAO,EAAE,GAClD,kBAAkB,CAuBpB"}
@@ -1,6 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { ErrorCode, FsError } from './errors.js';
3
- import { Logger } from './observability.js';
4
3
  import { MIB } from './util.js';
5
4
  const MAX_ENTRIES = 64;
6
5
  const MAX_TOTAL_BYTES = 25 * MIB;
@@ -48,26 +47,16 @@ export class ResourceStore {
48
47
  this.removeEntry(first.value.uri);
49
48
  }
50
49
  pruneExpiredEntries(now = Date.now()) {
51
- const toRemove = [];
50
+ const before = this.byUri.size;
52
51
  for (const entry of this.byUri.values()) {
53
- if (isExpired(entry, now)) {
54
- toRemove.push(entry.uri);
55
- }
52
+ if (isExpired(entry, now))
53
+ this.removeEntry(entry.uri);
56
54
  }
57
- for (const uri of toRemove) {
58
- this.removeEntry(uri);
59
- }
60
- return toRemove.length > 0;
55
+ return this.byUri.size !== before;
61
56
  }
62
57
  enforceLimits() {
63
- while (this.byUri.size > MAX_ENTRIES) {
64
- this.evictOldest();
65
- }
66
- while (this._totalBytes > MAX_TOTAL_BYTES) {
67
- if (this.byUri.size === 0) {
68
- Logger.error(`[resource-store] enforceLimits invariant violation: totalBytes=${this._totalBytes} but entryCount=0`);
69
- break;
70
- }
58
+ while (this.byUri.size > 0 &&
59
+ (this.byUri.size > MAX_ENTRIES || this._totalBytes > MAX_TOTAL_BYTES)) {
71
60
  this.evictOldest();
72
61
  }
73
62
  }
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/core/store.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,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ACxB,SAAS,EAAE,KAAK,CAAC,SAAS;SAC3B;QACD,IAAI,EAAE;YACJ,IAAI,EAAE,eAAe;YACrB,GAAG,EAAE,KAAK,CAAC,GAAG;YACd,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,WAAW,EAAE,EAAE,QAAQ,EAAE,CAAC,MAAM,CAAC,EAAE;SACpC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { randomUUID } from 'node:crypto';\n\nimport { ErrorCode, FsError } from './errors.js';\nimport { Logger } from './observability.js';\nimport { MIB } from './util.js';\n\ninterface ResourceEntry {\n uri: string;\n name: string;\n mimeType: string;\n size: number;\n expiresAt: string;\n text: string;\n}\n\nconst MAX_ENTRIES = 64;\nconst MAX_TOTAL_BYTES = 25 * MIB;\nconst MAX_ENTRY_BYTES = 10 * MIB;\nconst ENTRY_TTL_MS = 60 * 1000;\n\nfunction isExpired(entry: ResourceEntry, now = Date.now()): boolean {\n const expiresAt = Date.parse(entry.expiresAt);\n if (!Number.isFinite(expiresAt)) {\n return true;\n }\n return expiresAt <= now;\n}\n\nexport class ResourceStore {\n private readonly byUri = new Map<string, ResourceEntry>();\n private _totalBytes = 0;\n\n private readonly onListChanged: (() => void) | undefined;\n\n constructor(onListChanged?: () => void) {\n this.onListChanged = onListChanged;\n }\n\n private emitListChanged(changed: boolean): void {\n if (changed) this.onListChanged?.();\n }\n\n private bumpLru(uri: string, entry: ResourceEntry): void {\n if (!this.byUri.has(uri)) {\n return;\n }\n this.byUri.delete(uri);\n this.byUri.set(uri, entry);\n }\n\n private removeEntry(uri: string): ResourceEntry | undefined {\n const existing = this.byUri.get(uri);\n if (!existing) {\n return undefined;\n }\n this._totalBytes -= existing.size;\n this.byUri.delete(uri);\n return existing;\n }\n\n private evictOldest(): void {\n const first = this.byUri.values().next();\n if (first.done) {\n return;\n }\n this.removeEntry(first.value.uri);\n }\n\n private pruneExpiredEntries(now = Date.now()): boolean {\n const toRemove: string[] = [];\n for (const entry of this.byUri.values()) {\n if (isExpired(entry, now)) {\n toRemove.push(entry.uri);\n }\n }\n for (const uri of toRemove) {\n this.removeEntry(uri);\n }\n return toRemove.length > 0;\n }\n\n private enforceLimits(): void {\n while (this.byUri.size > MAX_ENTRIES) {\n this.evictOldest();\n }\n while (this._totalBytes > MAX_TOTAL_BYTES) {\n if (this.byUri.size === 0) {\n Logger.error(\n `[resource-store] enforceLimits invariant violation: totalBytes=${this._totalBytes} but entryCount=0`,\n );\n break;\n }\n this.evictOldest();\n }\n }\n\n getEntry(uri: string): ResourceEntry {\n const existing = this.byUri.get(uri);\n\n if (!existing) {\n throw new FsError(\n ErrorCode.NOT_FOUND,\n `Resource not found: ${uri}. Re-run the tool to regenerate.`,\n );\n }\n\n if (isExpired(existing)) {\n this.removeEntry(uri);\n this.emitListChanged(true);\n throw new FsError(\n ErrorCode.NOT_FOUND,\n `Resource expired: ${uri}. Re-run the tool to regenerate.`,\n );\n }\n\n this.bumpLru(uri, existing);\n return existing;\n }\n\n private checkBeforePut(entryBytes: number): void {\n const changed = this.pruneExpiredEntries();\n if (entryBytes > MAX_ENTRY_BYTES) {\n this.emitListChanged(changed);\n throw new FsError(ErrorCode.TOO_LARGE, `Resource too large to cache (${entryBytes} bytes).`);\n }\n }\n\n putText(params: { name: string; mimeType?: string; text: string }): ResourceEntry {\n const entryBytes = Buffer.byteLength(params.text, 'utf8');\n this.checkBeforePut(entryBytes);\n\n const storedAt = new Date();\n const entry: ResourceEntry = {\n uri: `filesystem-mcp://result/${randomUUID()}`,\n name: params.name,\n mimeType: params.mimeType ?? 'text/plain',\n size: entryBytes,\n expiresAt: new Date(storedAt.getTime() + ENTRY_TTL_MS).toISOString(),\n text: params.text,\n };\n this.byUri.set(entry.uri, entry);\n this._totalBytes += entryBytes;\n this.enforceLimits();\n this.emitListChanged(true);\n return entry;\n }\n\n /**\n * Returns live URIs currently in the store.\n * Side effect: prunes expired entries before returning.\n *\n * Deliberately silent: this is the read path `resources/list` runs through,\n * and the caller is already receiving the post-prune list. Emitting here\n * would tell the client its list changed while handing it that same list.\n */\n keys(): string[] {\n this.pruneExpiredEntries();\n return Array.from(this.byUri.keys());\n }\n}\n\nexport interface JsonResourceResult {\n entry: {\n uri: string;\n size: number;\n mimeType: string;\n expiresAt: string;\n };\n link: ContentBlock;\n}\n\n/**\n * Owner of the externalize-a-payload rule: a tool whose inline response is\n * truncated publishes the full value to the resource store as pretty-printed\n * JSON and hands back the URI to reach it by, plus the link block that offers\n * it to the user.\n */\nexport function putJsonResource(\n store: ResourceStore,\n name: string,\n // `Record<string, unknown> | readonly unknown[]`, not `unknown` or `object`:\n // JSON.stringify returns undefined for undefined and for functions, and `null`\n // is excluded so non-string payloads cannot enter the store's text entry.\n value: Record<string, unknown> | readonly unknown[],\n): JsonResourceResult {\n const entry = store.putText({\n name,\n mimeType: 'application/json',\n text: JSON.stringify(value, null, 2),\n });\n\n return {\n entry: {\n uri: entry.uri,\n size: entry.size,\n mimeType: entry.mimeType,\n expiresAt: entry.expiresAt,\n },\n link: {\n type: 'resource_link',\n uri: entry.uri,\n name: entry.name,\n mimeType: entry.mimeType,\n size: entry.size,\n annotations: { audience: ['user'] },\n },\n };\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/core/store.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAWhC,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,eAAe,GAAG,EAAE,GAAG,GAAG,CAAC;AACjC,MAAM,eAAe,GAAG,EAAE,GAAG,GAAG,CAAC;AACjC,MAAM,YAAY,GAAG,EAAE,GAAG,IAAI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AAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;;OAOG;IACH,IAAI;QACF,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IACvC,CAAC;CACF;AAYD;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAC7B,KAAoB,EACpB,IAAY;AACZ,6EAA6E;AAC7E,+EAA+E;AAC/E,0EAA0E;AAC1E,KAAmD;IAEnD,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC;QAC1B,IAAI;QACJ,QAAQ,EAAE,kBAAkB;QAC5B,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;KACrC,CAAC,CAAC;IAEH,OAAO;QACL,KAAK,EAAE;YACL,GAAG,EAAE,KAAK,CAAC,GAAG;YACd,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,SAAS,EAAE,KAAK,CAAC,SAAS;SAC3B;QACD,IAAI,EAAE;YACJ,IAAI,EAAE,eAAe;YACrB,GAAG,EAAE,KAAK,CAAC,GAAG;YACd,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,WAAW,EAAE,EAAE,QAAQ,EAAE,CAAC,MAAM,CAAC,EAAE;SACpC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { randomUUID } from 'node:crypto';\n\nimport { ErrorCode, FsError } from './errors.js';\nimport { MIB } from './util.js';\n\ninterface ResourceEntry {\n uri: string;\n name: string;\n mimeType: string;\n size: number;\n expiresAt: string;\n text: string;\n}\n\nconst MAX_ENTRIES = 64;\nconst MAX_TOTAL_BYTES = 25 * MIB;\nconst MAX_ENTRY_BYTES = 10 * MIB;\nconst ENTRY_TTL_MS = 60 * 1000;\n\nfunction isExpired(entry: ResourceEntry, now = Date.now()): boolean {\n const expiresAt = Date.parse(entry.expiresAt);\n if (!Number.isFinite(expiresAt)) {\n return true;\n }\n return expiresAt <= now;\n}\n\nexport class ResourceStore {\n private readonly byUri = new Map<string, ResourceEntry>();\n private _totalBytes = 0;\n\n private readonly onListChanged: (() => void) | undefined;\n\n constructor(onListChanged?: () => void) {\n this.onListChanged = onListChanged;\n }\n\n private emitListChanged(changed: boolean): void {\n if (changed) this.onListChanged?.();\n }\n\n private bumpLru(uri: string, entry: ResourceEntry): void {\n if (!this.byUri.has(uri)) {\n return;\n }\n this.byUri.delete(uri);\n this.byUri.set(uri, entry);\n }\n\n private removeEntry(uri: string): ResourceEntry | undefined {\n const existing = this.byUri.get(uri);\n if (!existing) {\n return undefined;\n }\n this._totalBytes -= existing.size;\n this.byUri.delete(uri);\n return existing;\n }\n\n private evictOldest(): void {\n const first = this.byUri.values().next();\n if (first.done) {\n return;\n }\n this.removeEntry(first.value.uri);\n }\n\n private pruneExpiredEntries(now = Date.now()): boolean {\n const before = this.byUri.size;\n for (const entry of this.byUri.values()) {\n if (isExpired(entry, now)) this.removeEntry(entry.uri);\n }\n return this.byUri.size !== before;\n }\n\n private enforceLimits(): void {\n while (\n this.byUri.size > 0 &&\n (this.byUri.size > MAX_ENTRIES || this._totalBytes > MAX_TOTAL_BYTES)\n ) {\n this.evictOldest();\n }\n }\n\n getEntry(uri: string): ResourceEntry {\n const existing = this.byUri.get(uri);\n\n if (!existing) {\n throw new FsError(\n ErrorCode.NOT_FOUND,\n `Resource not found: ${uri}. Re-run the tool to regenerate.`,\n );\n }\n\n if (isExpired(existing)) {\n this.removeEntry(uri);\n this.emitListChanged(true);\n throw new FsError(\n ErrorCode.NOT_FOUND,\n `Resource expired: ${uri}. Re-run the tool to regenerate.`,\n );\n }\n\n this.bumpLru(uri, existing);\n return existing;\n }\n\n private checkBeforePut(entryBytes: number): void {\n const changed = this.pruneExpiredEntries();\n if (entryBytes > MAX_ENTRY_BYTES) {\n this.emitListChanged(changed);\n throw new FsError(ErrorCode.TOO_LARGE, `Resource too large to cache (${entryBytes} bytes).`);\n }\n }\n\n putText(params: { name: string; mimeType?: string; text: string }): ResourceEntry {\n const entryBytes = Buffer.byteLength(params.text, 'utf8');\n this.checkBeforePut(entryBytes);\n\n const storedAt = new Date();\n const entry: ResourceEntry = {\n uri: `filesystem-mcp://result/${randomUUID()}`,\n name: params.name,\n mimeType: params.mimeType ?? 'text/plain',\n size: entryBytes,\n expiresAt: new Date(storedAt.getTime() + ENTRY_TTL_MS).toISOString(),\n text: params.text,\n };\n this.byUri.set(entry.uri, entry);\n this._totalBytes += entryBytes;\n this.enforceLimits();\n this.emitListChanged(true);\n return entry;\n }\n\n /**\n * Returns live URIs currently in the store.\n * Side effect: prunes expired entries before returning.\n *\n * Deliberately silent: this is the read path `resources/list` runs through,\n * and the caller is already receiving the post-prune list. Emitting here\n * would tell the client its list changed while handing it that same list.\n */\n keys(): string[] {\n this.pruneExpiredEntries();\n return Array.from(this.byUri.keys());\n }\n}\n\nexport interface JsonResourceResult {\n entry: {\n uri: string;\n size: number;\n mimeType: string;\n expiresAt: string;\n };\n link: ContentBlock;\n}\n\n/**\n * Owner of the externalize-a-payload rule: a tool whose inline response is\n * truncated publishes the full value to the resource store as pretty-printed\n * JSON and hands back the URI to reach it by, plus the link block that offers\n * it to the user.\n */\nexport function putJsonResource(\n store: ResourceStore,\n name: string,\n // `Record<string, unknown> | readonly unknown[]`, not `unknown` or `object`:\n // JSON.stringify returns undefined for undefined and for functions, and `null`\n // is excluded so non-string payloads cannot enter the store's text entry.\n value: Record<string, unknown> | readonly unknown[],\n): JsonResourceResult {\n const entry = store.putText({\n name,\n mimeType: 'application/json',\n text: JSON.stringify(value, null, 2),\n });\n\n return {\n entry: {\n uri: entry.uri,\n size: entry.size,\n mimeType: entry.mimeType,\n expiresAt: entry.expiresAt,\n },\n link: {\n type: 'resource_link',\n uri: entry.uri,\n name: entry.name,\n mimeType: entry.mimeType,\n size: entry.size,\n annotations: { audience: ['user'] },\n },\n };\n}\n"]}
package/dist/index.js CHANGED
@@ -35,29 +35,17 @@ async function shutdown(reason, exitCode = 0) {
35
35
  }, SHUTDOWN_TIMEOUT_MS);
36
36
  timer.unref();
37
37
  try {
38
- if (activeHttpServer) {
39
- const server = activeHttpServer;
40
- try {
41
- await new Promise((resolve, reject) => {
42
- server.close((err) => {
43
- if (err)
44
- reject(err);
45
- else
46
- resolve();
47
- });
48
- });
49
- }
50
- catch (error) {
51
- logRuntimeFailure('shutdown_http_error', 'process', 'shutdown', error);
52
- }
38
+ try {
39
+ await activeHttpServer?.[Symbol.asyncDispose]();
53
40
  }
54
- if (activeStdioHandle) {
55
- try {
56
- await activeStdioHandle.close();
57
- }
58
- catch (error) {
59
- logRuntimeFailure('shutdown_mcp_error', 'process', 'shutdown', error);
60
- }
41
+ catch (error) {
42
+ logRuntimeFailure('shutdown_http_error', 'process', 'shutdown', error);
43
+ }
44
+ try {
45
+ await activeStdioHandle?.close();
46
+ }
47
+ catch (error) {
48
+ logRuntimeFailure('shutdown_mcp_error', 'process', 'shutdown', error);
61
49
  }
62
50
  }
63
51
  finally {
@@ -65,37 +53,22 @@ async function shutdown(reason, exitCode = 0) {
65
53
  }
66
54
  }
67
55
  async function main() {
68
- let allowedDirs;
69
- let allowCwd;
70
- let port;
71
- let readOnly;
72
- let printConfig;
73
- let json;
74
- let httpHost;
75
- let cliApiKey;
56
+ let parsed;
76
57
  try {
77
- const parsed = await parseArgs();
78
- allowedDirs = parsed.allowedDirs;
79
- allowCwd = parsed.allowCwd;
80
- port = parsed.port;
81
- readOnly = parsed.readOnly;
82
- printConfig = parsed.printConfig;
83
- json = parsed.json;
84
- httpHost = parsed.httpHost;
85
- cliApiKey = parsed.apiKey;
58
+ parsed = await parseArgs();
86
59
  }
87
60
  catch (error) {
88
61
  if (error instanceof CliExitError) {
89
62
  if (error.message.length > 0) {
90
63
  logRuntimeFailure('cli_exit', 'startup', 'parse_args', error.message);
91
64
  }
92
- process.exitCode = error.exitCode;
65
+ process.exitCode = 1;
93
66
  return;
94
67
  }
95
68
  throw error;
96
69
  }
70
+ const { allowedDirs, allowCwd, port, readOnly, printConfig, json, httpHost, apiKey } = parsed;
97
71
  if (printConfig) {
98
- const apiKey = cliApiKey;
99
72
  await runPrintConfig({
100
73
  allowedDirs,
101
74
  allowCwd,
@@ -122,7 +95,7 @@ async function main() {
122
95
  const serverOptions = { allowCwd, cliAllowedDirs: allowedDirs, readOnly };
123
96
  const runtimeConfig = {
124
97
  ...(httpHost !== undefined ? { httpHost } : {}),
125
- ...(cliApiKey !== undefined ? { apiKey: cliApiKey } : {}),
98
+ ...(apiKey !== undefined ? { apiKey } : {}),
126
99
  };
127
100
  if (port !== undefined) {
128
101
  activeHttpServer = await startHttpServer(port, serverOptions, runtimeConfig);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAKA,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACnE,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE9D,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;AAEzB,MAAM,mBAAmB,GAAG,IAAI,CAAC;AACjC,IAAI,iBAAgD,CAAC;AACrD,IAAI,gBAAyC,CAAC;AAC9C,IAAI,eAAe,GAAG,KAAK,CAAC;AAE5B,SAAS,YAAY,CAAC,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B,EAAE,CAAC,CAAC,CAAC;AACxC,CAAC,CAAC,CAAC;AAEH,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC9B,iBAAiB,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACrD,KAAK,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n// Type-only imports are erased at runtime — safe to keep static.\nimport type { StdioServerHandle } from '@modelcontextprotocol/server/stdio';\n\nimport type * as http from 'node:http';\nimport process from 'node:process';\n\nimport * as z from 'zod/v4';\n\nimport { CliExitError, parseArgs, runPrintConfig } from './cli.js';\nimport { NO_POSITIONAL_ROOTS_GUIDANCE } from './core/config.js';\nimport { logRuntimeFailure } from './core/observability.js';\nimport { startHttpServer, startServer } from './transport.js';\n\nz.config(z.locales.en());\n\nconst SHUTDOWN_TIMEOUT_MS = 5000;\nlet activeStdioHandle: StdioServerHandle | undefined;\nlet activeHttpServer: http.Server | undefined;\nlet shutdownStarted = false;\n\nfunction isStdinEvent(event: NodeJS.Signals | 'end' | 'close'): boolean {\n return event === 'end' || event === 'close';\n}\n\nfunction registerShutdownTrigger(event: NodeJS.Signals | 'end' | 'close'): void {\n const target = isStdinEvent(event) ? process.stdin : process;\n target.once(event, () => {\n const reason = isStdinEvent(event) ? `stdin ${event}` : event;\n void shutdown(reason, 0);\n });\n}\n\nasync function shutdown(reason: string, exitCode = 0): Promise<void> {\n if (shutdownStarted) {\n if (reason === 'SIGINT' || reason === 'SIGTERM') {\n process.exit(130);\n }\n return;\n }\n shutdownStarted = true;\n\n process.exitCode = exitCode;\n\n const timer = setTimeout(() => {\n logRuntimeFailure(\n 'shutdown_timeout',\n 'process',\n 'shutdown',\n `Shutdown timed out (${reason}), forcing exit.`,\n );\n process.exit(exitCode);\n }, SHUTDOWN_TIMEOUT_MS);\n timer.unref();\n\n try {\n if (activeHttpServer) {\n const server = activeHttpServer;\n try {\n await new Promise<void>((resolve, reject) => {\n server.close((err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n } catch (error: unknown) {\n logRuntimeFailure('shutdown_http_error', 'process', 'shutdown', error);\n }\n }\n if (activeStdioHandle) {\n try {\n await activeStdioHandle.close();\n } catch (error: unknown) {\n logRuntimeFailure('shutdown_mcp_error', 'process', 'shutdown', error);\n }\n }\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function main(): Promise<void> {\n let allowedDirs: string[];\n let allowCwd: boolean;\n let port: number | undefined;\n let readOnly: boolean;\n let printConfig: boolean;\n let json: boolean;\n let httpHost: string | undefined;\n let cliApiKey: string | undefined;\n\n try {\n const parsed = await parseArgs();\n allowedDirs = parsed.allowedDirs;\n allowCwd = parsed.allowCwd;\n port = parsed.port;\n readOnly = parsed.readOnly;\n printConfig = parsed.printConfig;\n json = parsed.json;\n httpHost = parsed.httpHost;\n cliApiKey = parsed.apiKey;\n } catch (error: unknown) {\n if (error instanceof CliExitError) {\n if (error.message.length > 0) {\n logRuntimeFailure('cli_exit', 'startup', 'parse_args', error.message);\n }\n process.exitCode = error.exitCode;\n return;\n }\n throw error;\n }\n\n if (printConfig) {\n const apiKey = cliApiKey;\n await runPrintConfig({\n allowedDirs,\n allowCwd,\n readOnly,\n json,\n ...(port !== undefined ? { port } : {}),\n ...(httpHost !== undefined ? { httpHost } : {}),\n ...(apiKey !== undefined ? { apiKey } : {}),\n });\n return;\n }\n\n if (allowedDirs.length > 0) {\n console.error('Allowed directories (from CLI):');\n for (const dir of allowedDirs) {\n console.error(`- ${dir}`);\n }\n } else {\n console.error(NO_POSITIONAL_ROOTS_GUIDANCE);\n }\n\n if (readOnly) {\n console.error('Read-only mode: mutating tools disabled.');\n }\n\n const serverOptions = { allowCwd, cliAllowedDirs: allowedDirs, readOnly };\n const runtimeConfig = {\n ...(httpHost !== undefined ? { httpHost } : {}),\n ...(cliApiKey !== undefined ? { apiKey: cliApiKey } : {}),\n };\n\n if (port !== undefined) {\n activeHttpServer = await startHttpServer(port, serverOptions, runtimeConfig);\n } else {\n registerShutdownTrigger('end');\n registerShutdownTrigger('close');\n activeStdioHandle = startServer(serverOptions, runtimeConfig);\n }\n}\n\nregisterShutdownTrigger('SIGTERM');\nregisterShutdownTrigger('SIGINT');\n\nprocess.once('unhandledRejection', (reason: unknown) => {\n logRuntimeFailure('unhandled_rejection', 'process', 'unhandledRejection', reason);\n void shutdown('unhandledRejection', 1);\n});\n\nprocess.once('uncaughtException', (error: Error) => {\n logRuntimeFailure('uncaught_exception', 'process', 'uncaughtException', error);\n void shutdown('uncaughtException', 1);\n});\n\nmain().catch((error: unknown) => {\n logRuntimeFailure('fatal', 'startup', 'main', error);\n void shutdown('fatal', 1);\n});\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAKA,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACnE,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE9D,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;AAEzB,MAAM,mBAAmB,GAAG,IAAI,CAAC;AACjC,IAAI,iBAAgD,CAAC;AACrD,IAAI,gBAAyC,CAAC;AAC9C,IAAI,eAAe,GAAG,KAAK,CAAC;AAE5B,SAAS,YAAY,CAAC,KAAuC;IAC3D,OAAO,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,OAAO,CAAC;AAC9C,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAuC;IACtE,MAAM,MAAM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B,CAAC,qBAAqB,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,CAAC,CAAC;IAClF,KAAK,QAAQ,CAAC,oBAAoB,EAAE,CAAC,CAAC,CAAC;AACzC,CAAC,CAAC,CAAC;AAEH,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC,KAAY,EAAE,EAAE;IACjD,iBAAiB,CAAC,oBAAoB,EAAE,SAAS,EAAE,mBAAmB,EAAE,KAAK,CAAC,CAAC;IAC/E,KAAK,QAAQ,CAAC,mBAAmB,EAAE,CAAC,CAAC,CAAC;AACxC,CAAC,CAAC,CAAC;AAEH,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC9B,iBAAiB,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACrD,KAAK,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n// Type-only imports are erased at runtime — safe to keep static.\nimport type { StdioServerHandle } from '@modelcontextprotocol/server/stdio';\n\nimport type * as http from 'node:http';\nimport process from 'node:process';\n\nimport * as z from 'zod/v4';\n\nimport { CliExitError, parseArgs, runPrintConfig } from './cli.js';\nimport { NO_POSITIONAL_ROOTS_GUIDANCE } from './core/config.js';\nimport { logRuntimeFailure } from './core/observability.js';\nimport { startHttpServer, startServer } from './transport.js';\n\nz.config(z.locales.en());\n\nconst SHUTDOWN_TIMEOUT_MS = 5000;\nlet activeStdioHandle: StdioServerHandle | undefined;\nlet activeHttpServer: http.Server | undefined;\nlet shutdownStarted = false;\n\nfunction isStdinEvent(event: NodeJS.Signals | 'end' | 'close'): boolean {\n return event === 'end' || event === 'close';\n}\n\nfunction registerShutdownTrigger(event: NodeJS.Signals | 'end' | 'close'): void {\n const target = isStdinEvent(event) ? process.stdin : process;\n target.once(event, () => {\n const reason = isStdinEvent(event) ? `stdin ${event}` : event;\n void shutdown(reason, 0);\n });\n}\n\nasync function shutdown(reason: string, exitCode = 0): Promise<void> {\n if (shutdownStarted) {\n if (reason === 'SIGINT' || reason === 'SIGTERM') {\n process.exit(130);\n }\n return;\n }\n shutdownStarted = true;\n\n process.exitCode = exitCode;\n\n const timer = setTimeout(() => {\n logRuntimeFailure(\n 'shutdown_timeout',\n 'process',\n 'shutdown',\n `Shutdown timed out (${reason}), forcing exit.`,\n );\n process.exit(exitCode);\n }, SHUTDOWN_TIMEOUT_MS);\n timer.unref();\n\n try {\n try {\n await activeHttpServer?.[Symbol.asyncDispose]();\n } catch (error: unknown) {\n logRuntimeFailure('shutdown_http_error', 'process', 'shutdown', error);\n }\n try {\n await activeStdioHandle?.close();\n } catch (error: unknown) {\n logRuntimeFailure('shutdown_mcp_error', 'process', 'shutdown', error);\n }\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function main(): Promise<void> {\n let parsed: Awaited<ReturnType<typeof parseArgs>>;\n try {\n parsed = await parseArgs();\n } catch (error: unknown) {\n if (error instanceof CliExitError) {\n if (error.message.length > 0) {\n logRuntimeFailure('cli_exit', 'startup', 'parse_args', error.message);\n }\n process.exitCode = 1;\n return;\n }\n throw error;\n }\n const { allowedDirs, allowCwd, port, readOnly, printConfig, json, httpHost, apiKey } = parsed;\n\n if (printConfig) {\n await runPrintConfig({\n allowedDirs,\n allowCwd,\n readOnly,\n json,\n ...(port !== undefined ? { port } : {}),\n ...(httpHost !== undefined ? { httpHost } : {}),\n ...(apiKey !== undefined ? { apiKey } : {}),\n });\n return;\n }\n\n if (allowedDirs.length > 0) {\n console.error('Allowed directories (from CLI):');\n for (const dir of allowedDirs) {\n console.error(`- ${dir}`);\n }\n } else {\n console.error(NO_POSITIONAL_ROOTS_GUIDANCE);\n }\n\n if (readOnly) {\n console.error('Read-only mode: mutating tools disabled.');\n }\n\n const serverOptions = { allowCwd, cliAllowedDirs: allowedDirs, readOnly };\n const runtimeConfig = {\n ...(httpHost !== undefined ? { httpHost } : {}),\n ...(apiKey !== undefined ? { apiKey } : {}),\n };\n\n if (port !== undefined) {\n activeHttpServer = await startHttpServer(port, serverOptions, runtimeConfig);\n } else {\n registerShutdownTrigger('end');\n registerShutdownTrigger('close');\n activeStdioHandle = startServer(serverOptions, runtimeConfig);\n }\n}\n\nregisterShutdownTrigger('SIGTERM');\nregisterShutdownTrigger('SIGINT');\n\nprocess.once('unhandledRejection', (reason: unknown) => {\n logRuntimeFailure('unhandled_rejection', 'process', 'unhandledRejection', reason);\n void shutdown('unhandledRejection', 1);\n});\n\nprocess.once('uncaughtException', (error: Error) => {\n logRuntimeFailure('uncaught_exception', 'process', 'uncaughtException', error);\n void shutdown('uncaughtException', 1);\n});\n\nmain().catch((error: unknown) => {\n logRuntimeFailure('fatal', 'startup', 'main', error);\n void shutdown('fatal', 1);\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,SAAS,EAGV,MAAM,8BAA8B,CAAC;AAUtC,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AA+BD,wBAAgB,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAmC/D"}
1
+ {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAS/E,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AAID,wBAAgB,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAgD/D"}
package/dist/prompts.js CHANGED
@@ -1,26 +1,6 @@
1
1
  import { completable } from '@modelcontextprotocol/server';
2
2
  import * as z from 'zod/v4';
3
- import { Logger } from './core/observability.js';
4
3
  import { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';
5
- // --- Helpers ---
6
- function topicArg(topics, description) {
7
- return completable(
8
- // No content validation beyond non-empty: the handler resolves a topic by
9
- // `Object.hasOwn` against a frozen record, so anything unrecognized already
10
- // falls through to the not-found reply without reaching an interpreter.
11
- z.string().min(1, { message: 'Topic required' }).describe(description), (value) => {
12
- const lower = value.toLowerCase();
13
- return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];
14
- });
15
- }
16
- function userText(text) {
17
- const content = {
18
- type: 'text',
19
- text,
20
- annotations: { audience: ['assistant'], priority: 1 },
21
- };
22
- return { role: 'user', content };
23
- }
24
4
  // --- Prompt entries ---
25
5
  export function registerPrompts(deps) {
26
6
  const sections = buildSectionsRecord(deps.readOnly ?? false);
@@ -30,21 +10,33 @@ export function registerPrompts(deps) {
30
10
  title: 'Get Help',
31
11
  description: INSTRUCTIONS_SUMMARY,
32
12
  argsSchema: z.strictObject({
33
- topic: topicArg(topics, `Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`).optional(),
13
+ topic: completable(
14
+ // No content validation beyond non-empty: the handler resolves a topic by
15
+ // `Object.hasOwn` against a frozen record, so anything unrecognized already
16
+ // falls through to the not-found reply without reaching an interpreter.
17
+ z
18
+ .string()
19
+ .min(1, { message: 'Topic required' })
20
+ .describe(`Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`), (value) => {
21
+ const lower = value.toLowerCase();
22
+ return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];
23
+ }).optional(),
34
24
  }),
35
25
  }, ({ topic }) => {
36
26
  const lowerTopic = topic?.toLowerCase();
37
27
  const section = lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;
38
- if (topic && !section) {
39
- Logger.debug('get-help: unknown topic requested', { topic });
40
- }
41
28
  const text = section ??
42
29
  (topic
43
30
  ? `Section '${topic}' not found. Available: ${topics.join(', ')}\n\n${instructions}`
44
31
  : instructions);
45
32
  return {
46
33
  description: INSTRUCTIONS_SUMMARY,
47
- messages: [userText(text)],
34
+ messages: [
35
+ {
36
+ role: 'user',
37
+ content: { type: 'text', text, annotations: { audience: ['assistant'], priority: 1 } },
38
+ },
39
+ ],
48
40
  };
49
41
  });
50
42
  }
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAE3D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAS9F,kBAAkB;AAElB,SAAS,QAAQ,CACf,MAAyB,EACzB,WAAmB;IAEnB,OAAO,WAAW;IAChB,0EAA0E;IAC1E,4EAA4E;IAC5E,wEAAwE;IACxE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,EACtE,CAAC,KAAK,EAAE,EAAE;QACR,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;QAClC,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;IACzE,CAAC,CACF,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAC,IAAY;IAC5B,MAAM,OAAO,GAAgB;QAC3B,IAAI,EAAE,MAAM;QACZ,IAAI;QACJ,WAAW,EAAE,EAAE,QAAQ,EAAE,CAAC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C;QACpB,OAAO;YACL,WAAW,EAAE,oBAAoB;YACjC,QAAQ,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n GetPromptResult,\n McpServer,\n PromptMessage,\n TextContent,\n} from '@modelcontextprotocol/server';\nimport { completable } from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { Logger } from './core/observability.js';\nimport { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';\n\n// --- Types ---\n\ninterface PromptRegistrarDeps {\n readonly server: McpServer;\n readonly readOnly?: boolean;\n}\n\n// --- Helpers ---\n\nfunction topicArg(\n topics: readonly string[],\n description: string,\n): ReturnType<typeof completable<z.ZodString>> {\n return completable(\n // No content validation beyond non-empty: the handler resolves a topic by\n // `Object.hasOwn` against a frozen record, so anything unrecognized already\n // falls through to the not-found reply without reaching an interpreter.\n z.string().min(1, { message: 'Topic required' }).describe(description),\n (value) => {\n const lower = value.toLowerCase();\n return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];\n },\n );\n}\n\nfunction userText(text: string): PromptMessage {\n const content: TextContent = {\n type: 'text',\n text,\n annotations: { audience: ['assistant'], priority: 1 },\n };\n return { role: 'user', content };\n}\n\n// --- Prompt entries ---\n\nexport function registerPrompts(deps: PromptRegistrarDeps): void {\n const sections = buildSectionsRecord(deps.readOnly ?? false);\n const instructions = renderSections(sections);\n const topics = Object.keys(sections);\n\n deps.server.registerPrompt(\n 'get-help',\n {\n title: 'Get Help',\n description: INSTRUCTIONS_SUMMARY,\n argsSchema: z.strictObject({\n topic: topicArg(\n topics,\n `Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`,\n ).optional(),\n }),\n },\n ({ topic }: { topic?: string | undefined }): GetPromptResult => {\n const lowerTopic = topic?.toLowerCase();\n const section =\n lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;\n if (topic && !section) {\n Logger.debug('get-help: unknown topic requested', { topic });\n }\n const text =\n section ??\n (topic\n ? `Section '${topic}' not found. Available: ${topics.join(', ')}\\n\\n${instructions}`\n : instructions);\n return {\n description: INSTRUCTIONS_SUMMARY,\n messages: [userText(text)],\n };\n },\n );\n}\n"]}
1
+ {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAE3D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAS9F,yBAAyB;AAEzB,MAAM,UAAU,eAAe,CAAC,IAAyB;IACvD,MAAM,QAAQ,GAAG,mBAAmB,CAAC,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,CAAC;IAC7D,MAAM,YAAY,GAAG,cAAc,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAErC,IAAI,CAAC,MAAM,CAAC,cAAc,CACxB,UAAU,EACV;QACE,KAAK,EAAE,UAAU;QACjB,WAAW,EAAE,oBAAoB;QACjC,UAAU,EAAE,CAAC,CAAC,YAAY,CAAC;YACzB,KAAK,EAAE,WAAW;YAChB,0EAA0E;YAC1E,4EAA4E;YAC5E,wEAAwE;YACxE,CAAC;iBACE,MAAM,EAAE;iBACR,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC;iBACrC,QAAQ,CACP,+CAA+C,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,qCAAqC,CACtG,EACH,CAAC,KAAK,EAAE,EAAE;gBACR,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;gBAClC,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;YACzE,CAAC,CACF,CAAC,QAAQ,EAAE;SACb,CAAC;KACH,EACD,CAAC,EAAE,KAAK,EAAkC,EAAmB,EAAE;QAC7D,MAAM,UAAU,GAAG,KAAK,EAAE,WAAW,EAAE,CAAC;QACxC,MAAM,OAAO,GACX,UAAU,IAAI,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACvF,MAAM,IAAI,GACR,OAAO;YACP,CAAC,KAAK;gBACJ,CAAC,CAAC,YAAY,KAAK,2BAA2B,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,YAAY,EAAE;gBACpF,CAAC,CAAC,YAAY,CAAC,CAAC;QACpB,OAAO;YACL,WAAW,EAAE,oBAAoB;YACjC,QAAQ,EAAE;gBACR;oBACE,IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,QAAQ,EAAE,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE;iBACvF;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { GetPromptResult, McpServer } from '@modelcontextprotocol/server';\nimport { completable } from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';\n\n// --- Types ---\n\ninterface PromptRegistrarDeps {\n readonly server: McpServer;\n readonly readOnly?: boolean;\n}\n\n// --- Prompt entries ---\n\nexport function registerPrompts(deps: PromptRegistrarDeps): void {\n const sections = buildSectionsRecord(deps.readOnly ?? false);\n const instructions = renderSections(sections);\n const topics = Object.keys(sections);\n\n deps.server.registerPrompt(\n 'get-help',\n {\n title: 'Get Help',\n description: INSTRUCTIONS_SUMMARY,\n argsSchema: z.strictObject({\n topic: completable(\n // No content validation beyond non-empty: the handler resolves a topic by\n // `Object.hasOwn` against a frozen record, so anything unrecognized already\n // falls through to the not-found reply without reaching an interpreter.\n z\n .string()\n .min(1, { message: 'Topic required' })\n .describe(\n `Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`,\n ),\n (value) => {\n const lower = value.toLowerCase();\n return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];\n },\n ).optional(),\n }),\n },\n ({ topic }: { topic?: string | undefined }): GetPromptResult => {\n const lowerTopic = topic?.toLowerCase();\n const section =\n lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;\n const text =\n section ??\n (topic\n ? `Section '${topic}' not found. Available: ${topics.join(', ')}\\n\\n${instructions}`\n : instructions);\n return {\n description: INSTRUCTIONS_SUMMARY,\n messages: [\n {\n role: 'user',\n content: { type: 'text', text, annotations: { audience: ['assistant'], priority: 1 } },\n },\n ],\n };\n },\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { CacheHint, McpServer, ReadResourceResult, Resource, Role, ServerContext, ServerNotifier } from '@modelcontextprotocol/server';
1
+ import type { CacheHint, CompleteResourceTemplateCallback, McpServer, ReadResourceResult, Resource, Role, ServerContext, ServerNotifier } from '@modelcontextprotocol/server';
2
2
  import type { PathGuard } from './core/path.js';
3
3
  import type { ResourceStore } from './core/store.js';
4
4
  import { type WatcherRegistry } from './core/watcher-registry.js';
@@ -60,9 +60,9 @@ interface StaticResourceContract extends BaseResourceContract {
60
60
  interface TemplateResourceContract extends BaseResourceContract {
61
61
  uriTemplate: string;
62
62
  uri?: never;
63
- complete?: (variable: string, value: string, ctx?: {
64
- arguments?: Record<string, string>;
65
- }) => Promise<string[]> | string[];
63
+ complete?: {
64
+ path: CompleteResourceTemplateCallback;
65
+ };
66
66
  }
67
67
  type ResourceContract = StaticResourceContract | TemplateResourceContract;
68
68
  export declare function getResourceContracts(options: ResourceRegistrationOptions): ResourceContract[];
@@ -1 +1 @@
1
- {"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,SAAS,EACT,kBAAkB,EAClB,QAAQ,EAER,IAAI,EACJ,aAAa,EACb,cAAc,EAGf,MAAM,8BAA8B,CAAC;AA4BtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAGL,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AAYpC,MAAM,WAAW,2BAA2B;IAC1C,aAAa,EAAE,aAAa,CAAC;IAC7B,SAAS,EAAE,SAAS,CAAC;IACrB,8FAA8F;IAC9F,QAAQ,EAAE,OAAO,CAAC;IAClB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,+CAA+C;IAC/C,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,qFAAqF;IACrF,GAAG,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC1B;;;;OAIG;IACH,UAAU,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAC;CACnC;AAED,KAAK,qBAAqB,GAAG,IAAI,CAAC,2BAA2B,EAAE,WAAW,GAAG,UAAU,CAAC,GAAG;IACzF,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B,CAAC;AAoBF,UAAU,oBAAoB;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAA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IAC3D,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,CAAC,EAAE,KAAK,CAAC;IACpB,QAAQ,CAAC,EAAE,KAAK,CAAC;CAClB;AAED,8EAA8E;AAC9E,UAAU,wBAAyB,SAAQ,oBAAoB;IAC7D,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,KAAK,CAAC;IACZ,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,gCAAgC,CAAA;KAAE,CAAC;CACvD;AAED,KAAK,gBAAgB,GAAG,sBAAsB,GAAG,wBAAwB,CAAC;AAqP1E,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,gBAAgB,EAAE,CAM7F;AA4BD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,qBAAqB,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CAAE,CAiJlF"}
package/dist/resources.js CHANGED
@@ -1,4 +1,4 @@
1
- import { checkResourceAllowed, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate, resourceUrlFromServerUrl, UriTemplate, } from '@modelcontextprotocol/server';
1
+ import { checkResourceAllowed, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate, resourceUrlFromServerUrl, } from '@modelcontextprotocol/server';
2
2
  import { ErrorCode, formatUnknownErrorMessage, fsErrorCode, hasErrorShape, isFsError, } from './core/errors.js';
3
3
  import { decodeFileUriPath, encodeFileUriPath, extractPath, FILESYSTEM_FILE_URI_TEMPLATE, } from './core/file-uri.js';
4
4
  import { GuardedFileSystem } from './core/fs.js';
@@ -110,14 +110,14 @@ function createFilesystemResource(options) {
110
110
  ],
111
111
  };
112
112
  },
113
- async complete(variable, value) {
114
- if (variable !== 'path')
115
- return [];
113
+ complete: {
116
114
  // Both ends speak the `{+path}` form (see encodeFileUriPath), not raw OS
117
115
  // paths: the partial arriving here is whatever this returned last, so the
118
116
  // decode mirrors the encode. An undecodable partial is matched as typed.
119
- const suggestions = await completer.suggest(decodeFileUriPath(value) ?? value);
120
- return suggestions.map(encodeFileUriPath);
117
+ path: async (value) => {
118
+ const suggestions = await completer.suggest(decodeFileUriPath(value) ?? value);
119
+ return suggestions.map(encodeFileUriPath);
120
+ },
121
121
  },
122
122
  subscribe(uri, notify) {
123
123
  // Already subscribed on this connection: the watcher is live and the sink
@@ -285,17 +285,7 @@ export function registerResources(deps) {
285
285
  if (contract.uriTemplate) {
286
286
  const template = new ResourceTemplate(contract.uriTemplate, {
287
287
  list: contract.list,
288
- ...(contract.complete
289
- ? {
290
- complete: Object.fromEntries(new UriTemplate(contract.uriTemplate).variableNames.map((varName) => [
291
- varName,
292
- (value, ctx) => {
293
- const completeFn = contract.complete;
294
- return completeFn ? completeFn(varName, value, ctx) : [];
295
- },
296
- ])),
297
- }
298
- : {}),
288
+ ...(contract.complete ? { complete: contract.complete } : {}),
299
289
  });
300
290
  server.registerResource(contract.name, template, config, wrapRead(contract));
301
291
  }