@j0hanz/filesystem-mcp 2.1.5 → 2.1.6

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 (112) hide show
  1. package/dist/cli.d.ts.map +1 -1
  2. package/dist/cli.js +6 -13
  3. package/dist/cli.js.map +1 -1
  4. package/dist/core/diff.d.ts +6 -0
  5. package/dist/core/diff.d.ts.map +1 -0
  6. package/dist/core/diff.js +21 -0
  7. package/dist/core/diff.js.map +1 -0
  8. package/dist/core/errors.d.ts +0 -20
  9. package/dist/core/errors.d.ts.map +1 -1
  10. package/dist/core/errors.js +9 -60
  11. package/dist/core/errors.js.map +1 -1
  12. package/dist/core/file-uri.d.ts +18 -2
  13. package/dist/core/file-uri.d.ts.map +1 -1
  14. package/dist/core/file-uri.js +34 -6
  15. package/dist/core/file-uri.js.map +1 -1
  16. package/dist/core/fs.d.ts +1 -2
  17. package/dist/core/fs.d.ts.map +1 -1
  18. package/dist/core/fs.js +3 -22
  19. package/dist/core/fs.js.map +1 -1
  20. package/dist/core/glob.d.ts +1 -6
  21. package/dist/core/glob.d.ts.map +1 -1
  22. package/dist/core/glob.js +0 -9
  23. package/dist/core/glob.js.map +1 -1
  24. package/dist/core/input-required.d.ts +2 -4
  25. package/dist/core/input-required.d.ts.map +1 -1
  26. package/dist/core/input-required.js +3 -4
  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 +1 -6
  30. package/dist/core/path-completer.js.map +1 -1
  31. package/dist/core/path.d.ts +4 -8
  32. package/dist/core/path.d.ts.map +1 -1
  33. package/dist/core/path.js +13 -26
  34. package/dist/core/path.js.map +1 -1
  35. package/dist/core/primitives.d.ts +8 -2
  36. package/dist/core/primitives.d.ts.map +1 -1
  37. package/dist/core/primitives.js +10 -2
  38. package/dist/core/primitives.js.map +1 -1
  39. package/dist/core/read.d.ts +0 -15
  40. package/dist/core/read.d.ts.map +1 -1
  41. package/dist/core/read.js +12 -41
  42. package/dist/core/read.js.map +1 -1
  43. package/dist/core/schema.d.ts +1 -16
  44. package/dist/core/schema.d.ts.map +1 -1
  45. package/dist/core/schema.js +7 -41
  46. package/dist/core/schema.js.map +1 -1
  47. package/dist/core/search.d.ts +10 -3
  48. package/dist/core/search.d.ts.map +1 -1
  49. package/dist/core/search.js +19 -13
  50. package/dist/core/search.js.map +1 -1
  51. package/dist/core/sensitive.d.ts.map +1 -1
  52. package/dist/core/sensitive.js +7 -15
  53. package/dist/core/sensitive.js.map +1 -1
  54. package/dist/core/store.d.ts +0 -1
  55. package/dist/core/store.d.ts.map +1 -1
  56. package/dist/core/store.js +0 -1
  57. package/dist/core/store.js.map +1 -1
  58. package/dist/index.js +1 -8
  59. package/dist/index.js.map +1 -1
  60. package/dist/prompts.d.ts.map +1 -1
  61. package/dist/prompts.js +13 -28
  62. package/dist/prompts.js.map +1 -1
  63. package/dist/tools/batch.d.ts +5 -78
  64. package/dist/tools/batch.d.ts.map +1 -1
  65. package/dist/tools/batch.js +6 -115
  66. package/dist/tools/batch.js.map +1 -1
  67. package/dist/tools/create.d.ts.map +1 -1
  68. package/dist/tools/create.js +8 -18
  69. package/dist/tools/create.js.map +1 -1
  70. package/dist/tools/define.d.ts +1 -4
  71. package/dist/tools/define.d.ts.map +1 -1
  72. package/dist/tools/define.js +1 -22
  73. package/dist/tools/define.js.map +1 -1
  74. package/dist/tools/delete-file.d.ts.map +1 -1
  75. package/dist/tools/delete-file.js +6 -6
  76. package/dist/tools/delete-file.js.map +1 -1
  77. package/dist/tools/diff.d.ts.map +1 -1
  78. package/dist/tools/diff.js +3 -10
  79. package/dist/tools/diff.js.map +1 -1
  80. package/dist/tools/edit.d.ts.map +1 -1
  81. package/dist/tools/edit.js +39 -71
  82. package/dist/tools/edit.js.map +1 -1
  83. package/dist/tools/index.d.ts +0 -1
  84. package/dist/tools/index.d.ts.map +1 -1
  85. package/dist/tools/index.js +0 -1
  86. package/dist/tools/index.js.map +1 -1
  87. package/dist/tools/list.js +2 -1
  88. package/dist/tools/list.js.map +1 -1
  89. package/dist/tools/move.d.ts.map +1 -1
  90. package/dist/tools/move.js +162 -116
  91. package/dist/tools/move.js.map +1 -1
  92. package/dist/tools/patch.d.ts.map +1 -1
  93. package/dist/tools/patch.js +5 -23
  94. package/dist/tools/patch.js.map +1 -1
  95. package/dist/tools/read.d.ts.map +1 -1
  96. package/dist/tools/read.js +20 -21
  97. package/dist/tools/read.js.map +1 -1
  98. package/dist/tools/replace-in-files.d.ts.map +1 -1
  99. package/dist/tools/replace-in-files.js +23 -38
  100. package/dist/tools/replace-in-files.js.map +1 -1
  101. package/dist/tools/search-content.d.ts.map +1 -1
  102. package/dist/tools/search-content.js +10 -31
  103. package/dist/tools/search-content.js.map +1 -1
  104. package/dist/tools/search-files.d.ts.map +1 -1
  105. package/dist/tools/search-files.js +1 -2
  106. package/dist/tools/search-files.js.map +1 -1
  107. package/dist/tools/stat.d.ts.map +1 -1
  108. package/dist/tools/stat.js +4 -3
  109. package/dist/tools/stat.js.map +1 -1
  110. package/dist/transport/http-policy.js +1 -1
  111. package/dist/transport/http-policy.js.map +1 -1
  112. package/package.json +1 -1
@@ -1,9 +1,10 @@
1
1
  import { RE2 } from '@adguard/re2-wasm';
2
- import type { StoppedReason } from './concurrency.js';
3
2
  import type { PathGuard } from './path.js';
4
3
  interface SearchResult {
5
4
  file: string;
6
5
  line: number;
6
+ /** 0-indexed column of the first occurrence on the line. */
7
+ column: number;
7
8
  content: string;
8
9
  matchCount?: number;
9
10
  }
@@ -71,7 +72,12 @@ export interface SearchContentOutcome {
71
72
  skippedInaccessible: number;
72
73
  /** Files skipped unread because they exceed maxFileSize. */
73
74
  skippedTooLarge: number;
74
- stoppedReason?: StoppedReason;
75
+ /**
76
+ * `StoppedReason` narrowed to the stops these scans can produce: both call
77
+ * only `hitMaxResults`/`hitAbort` (see concurrency.ts) — never
78
+ * `hitMaxFiles`, which belongs to `replace_text`'s per-file cap.
79
+ */
80
+ stoppedReason?: 'maxResults' | 'timeout';
75
81
  };
76
82
  }
77
83
  /**
@@ -97,7 +103,8 @@ export declare function searchFiles(directory: string, pattern: string, excludeP
97
103
  filesScanned: number;
98
104
  truncated: boolean;
99
105
  skippedInaccessible: number;
100
- stoppedReason?: StoppedReason;
106
+ /** Narrowed like SearchContentOutcome's — scans never hit `hitMaxFiles`. */
107
+ stoppedReason?: 'maxResults' | 'timeout';
101
108
  };
102
109
  }>;
103
110
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/core/search.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAGxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAI3C,UAAU,YAAY;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,KAAK,GAAG,GAAG,CAAC;AACxB,MAAM,WAAW,mBAAmB;IAClC,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAKD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,KAAK,CAWtF;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,SAAS,GAAG,IAAI,CAOxD;AAkBD,MAAM,WAAW,oBAAoB;IACnC,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,EAAE,C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AA;KAAE,EAAE,CAAC;IAC5B,OAAO,EAAE;QACP,OAAO,EAAE,MAAM,CAAC;QAChB,YAAY,EAAE,MAAM,CAAC;QACrB,SAAS,EAAE,OAAO,CAAC;QACnB,mBAAmB,EAAE,MAAM,CAAC;QAC5B,4EAA4E;QAC5E,aAAa,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;KAC1C,CAAC;CACH,CAAC,CA+CD"}
@@ -1,4 +1,5 @@
1
1
  import { stat as fsStat, readFile } from 'node:fs/promises';
2
+ import { basename } from 'node:path';
2
3
  import { RE2 } from '@adguard/re2-wasm';
3
4
  import { StopReasonTracker } from './concurrency.js';
4
5
  import { globEntries } from './glob.js';
@@ -56,21 +57,25 @@ export function freeRegex(regex) {
56
57
  }
57
58
  }
58
59
  /**
59
- * Count non-overlapping occurrences of a global regex in a single line. Guards
60
- * zero-length matches (e.g. `a*`) so they cannot loop forever.
60
+ * Find non-overlapping occurrences of a global regex in a single line, reporting
61
+ * the first match's column alongside the count. Guards zero-length matches
62
+ * (e.g. `a*`) so they cannot loop forever.
61
63
  */
62
- function countLineMatches(regex, line) {
64
+ function findLineMatches(regex, line) {
63
65
  regex.lastIndex = 0;
64
66
  let count = 0;
67
+ let column = -1;
65
68
  let match;
66
69
  while ((match = regex.exec(line)) !== null) {
70
+ if (column === -1)
71
+ column = match.index;
67
72
  count++;
68
73
  if (match.index === regex.lastIndex)
69
74
  regex.lastIndex++; // advance past zero-length match
70
75
  if (count >= MAX_MATCHES_PER_LINE)
71
76
  break;
72
77
  }
73
- return count;
78
+ return count > 0 ? { count, column } : undefined;
74
79
  }
75
80
  /**
76
81
  * Owns the compiled pattern's lifetime. Pass `precompiled` to skip compiling
@@ -125,17 +130,18 @@ export async function searchContent(directory, pattern, options, pathGuard, prec
125
130
  const line = lines[i];
126
131
  if (line === undefined)
127
132
  continue;
128
- // One scan per line: countLineMatches resets lastIndex itself, so it
133
+ // One scan per line: findLineMatches resets lastIndex itself, so it
129
134
  // doubles as the "does this line match" test.
130
- const occurrences = countLineMatches(regex, line);
131
- if (occurrences > 0) {
135
+ const found = findLineMatches(regex, line);
136
+ if (found) {
132
137
  matchedFile = true;
133
138
  matchingLines++;
134
139
  matches.push({
135
140
  file: entry.path,
136
141
  line: i + 1,
142
+ column: found.column,
137
143
  content: line,
138
- matchCount: occurrences,
144
+ matchCount: found.count,
139
145
  });
140
146
  if (matches.length >= maxResults)
141
147
  break;
@@ -160,6 +166,8 @@ export async function searchContent(directory, pattern, options, pathGuard, prec
160
166
  tracker.hitMaxResults();
161
167
  if (counters.stoppedByAbort)
162
168
  tracker.hitAbort();
169
+ // resolve() is StoppedReason | undefined, but this scan only records
170
+ // maxResults/timeout stops (see the summary type's narrowing note).
163
171
  const stoppedReason = tracker.resolve();
164
172
  return {
165
173
  basePath: directory,
@@ -222,11 +230,7 @@ export async function searchFiles(directory, pattern, excludePatterns, options,
222
230
  // Sorting — only name / path are supported; size / modified were removed
223
231
  // (the glob never collected stats, so they were always undefined).
224
232
  if (options.sortBy === 'name') {
225
- results.sort((a, b) => {
226
- const aName = a.path.split(/[/\\]/).pop() ?? '';
227
- const bName = b.path.split(/[/\\]/).pop() ?? '';
228
- return aName.localeCompare(bName);
229
- });
233
+ results.sort((a, b) => basename(a.path).localeCompare(basename(b.path)));
230
234
  }
231
235
  else {
232
236
  results.sort((a, b) => a.path.localeCompare(b.path));
@@ -236,6 +240,8 @@ export async function searchFiles(directory, pattern, excludePatterns, options,
236
240
  tracker.hitMaxResults();
237
241
  if (counters.stoppedByAbort)
238
242
  tracker.hitAbort();
243
+ // resolve() is StoppedReason | undefined, but this scan only records
244
+ // maxResults/timeout stops (see the summary type's narrowing note).
239
245
  const stoppedReason = tracker.resolve();
240
246
  return {
241
247
  basePath: directory,
@@ -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,kBAA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CAAC;IAExC,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';\n\nimport type { RE2ExecArray } from '@adguard/re2-wasm';\nimport { RE2 } from '@adguard/re2-wasm';\n\nimport { StopReasonTracker } from './concurrency.js';\nimport type { StoppedReason } 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 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 * Count non-overlapping occurrences of a global regex in a single line. Guards\n * zero-length matches (e.g. `a*`) so they cannot loop forever.\n */\nfunction countLineMatches(regex: Regex, line: string): number {\n regex.lastIndex = 0;\n let count = 0;\n let match: RE2ExecArray | null;\n while ((match = regex.exec(line)) !== null) {\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;\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 stoppedReason?: StoppedReason;\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: countLineMatches resets lastIndex itself, so it\n // doubles as the \"does this line match\" test.\n const occurrences = countLineMatches(regex, line);\n if (occurrences > 0) {\n matchedFile = true;\n matchingLines++;\n matches.push({\n file: entry.path,\n line: i + 1,\n content: line,\n matchCount: occurrences,\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 const stoppedReason = tracker.resolve();\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 stoppedReason?: StoppedReason;\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) => {\n const aName = a.path.split(/[/\\\\]/).pop() ?? '';\n const bName = b.path.split(/[/\\\\]/).pop() ?? '';\n return aName.localeCompare(bName);\n });\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 const stoppedReason = tracker.resolve();\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,EA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AO;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 +1 @@
1
- {"version":3,"file":"sensitive.d.ts","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AA+JA,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;gBAElC,QAAQ,GAAE,SAAS,MAAM,EAA6B;IAIlE,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAWvC"}
1
+ {"version":3,"file":"sensitive.d.ts","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AAiJA,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;gBAElC,QAAQ,GAAE,SAAS,MAAM,EAA6B;IAIlE,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAWvC"}
@@ -30,23 +30,15 @@ function compilePatternGlobs(normalizedPattern) {
30
30
  }
31
31
  return Array.from(globs);
32
32
  }
33
- function compilePatterns(patterns) {
34
- const deduped = Array.from(new Set(patterns.map((p) => p.trim()).filter((p) => p.length > 0)));
35
- return deduped.map((pattern) => {
36
- const normalized = normalizeForMatch(pattern);
37
- const matchesPath = normalized.includes('/');
38
- return {
39
- globs: matchesPath ? compilePatternGlobs(normalized) : [normalized],
40
- matchesPath,
41
- };
42
- });
43
- }
44
33
  function toPatternSet(patterns) {
45
34
  const pathGlobs = new Set();
46
35
  const nameGlobs = new Set();
47
- for (const pattern of patterns) {
48
- const target = pattern.matchesPath ? pathGlobs : nameGlobs;
49
- for (const glob of pattern.globs) {
36
+ const deduped = Array.from(new Set(patterns.map((p) => p.trim()).filter((p) => p.length > 0)));
37
+ for (const pattern of deduped) {
38
+ const normalized = normalizeForMatch(pattern);
39
+ const matchesPath = normalized.includes('/');
40
+ const target = matchesPath ? pathGlobs : nameGlobs;
41
+ for (const glob of matchesPath ? compilePatternGlobs(normalized) : [normalized]) {
50
42
  target.add(glob);
51
43
  }
52
44
  }
@@ -127,7 +119,7 @@ function buildSensitivePatterns() {
127
119
  export class SensitiveMatcher {
128
120
  patterns;
129
121
  constructor(patterns = buildSensitivePatterns()) {
130
- this.patterns = toPatternSet(compilePatterns(patterns));
122
+ this.patterns = toPatternSet(patterns);
131
123
  }
132
124
  isSensitive(filePath) {
133
125
  if (this.patterns.pathGlobs.length === 0 && this.patterns.nameGlobs.length === 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"sensitive.js","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,2EAA2E;AAC3E,wEAAwE;AACxE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAErF,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAE9B,SAAS,iBAAiB,CAAC,KAAa;IACtC,4EAA4E;IAC5E,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AACrD,CAAC;AAYD,SAAS,0BAA0B,CAAC,iBAAyB;IAC3D,OAAO,CACL,iBAAiB,CAAC,MAAM,IAAI,CAAC;QAC7B,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,UAAU;QAC9C,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,kBAAkB;QACtD,OAAO,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CACzC,CAAC;AACJ,CAAC;AAED,SAAS,mBAAmB,CAAC,iBAAyB;IACpD,MAAM,KAAK,GAAG,IAAI,GAAG,CAAS,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAEnD,MAAM,QAAQ,GACZ,iBA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CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,0BAA0B,CAAC;QACrD,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,YAAY,CAAC,CAAC;KAC9C,CAAC;AACJ,CAAC;AAED,MAAM,OAAO,gBAAgB;IACV,QAAQ,CAAqB;IAE9C,YAAY,WAA8B,sBAAsB,EAAE;QAChE,IAAI,CAAC,QAAQ,GAAG,YAAY,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC1D,CAAC;IAED,WAAW,CAAC,QAAgB;QAC1B,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjF,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QAChF,MAAM,cAAc,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;QACtD,OAAO,CACL,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;YACvD,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC,CACxE,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Sensitive-file denylist policy: the compiled pattern set, the path\n// normalization that feeds it, and the NTFS alternate-data-stream stripping\n// Windows needs. Split out of path.ts so the denylist has its own home — it\n// shares only isAlpha / toPosixPath / IS_WINDOWS with the primitives in\n// primitives.ts, not the allowed-directory assembly. path-completer.ts and\n// glob.ts reach it through PathGuard.isSensitive, which delegates here.\nimport { normalize, posix, sep } from 'node:path';\n\nimport { cli } from './config.js';\nimport { IS_WINDOWS, isAlpha, parseTrueEnvFlag, toPosixPath } from './primitives.js';\n\nconst CHAR_COLON = 58;\nconst CHAR_FORWARD_SLASH = 47;\n\nfunction normalizeForMatch(input: string): string {\n // Always lowercase for case-insensitive denylist matching on all platforms.\n return toPosixPath(normalize(input)).toLowerCase();\n}\n\ninterface CompiledPattern {\n globs: readonly string[];\n matchesPath: boolean;\n}\n\ninterface CompiledPatternSet {\n pathGlobs: readonly string[];\n nameGlobs: readonly string[];\n}\n\nfunction isWindowsAbsolutePosixPath(normalizedPattern: string): boolean {\n return (\n normalizedPattern.length >= 3 &&\n normalizedPattern.charCodeAt(1) === CHAR_COLON &&\n normalizedPattern.charCodeAt(2) === CHAR_FORWARD_SLASH &&\n isAlpha(normalizedPattern.charCodeAt(0))\n );\n}\n\nfunction compilePatternGlobs(normalizedPattern: string): readonly string[] {\n const globs = new Set<string>([normalizedPattern]);\n\n const isRooted =\n normalizedPattern.startsWith('**/') || isWindowsAbsolutePosixPath(normalizedPattern);\n if (!isRooted) {\n const withoutRoot = normalizedPattern.replace(/^\\/+/, '');\n if (withoutRoot) {\n globs.add(`**/${withoutRoot}`);\n }\n }\n\n return Array.from(globs);\n}\n\nfunction compilePatterns(patterns: readonly string[]): CompiledPattern[] {\n const deduped = Array.from(new Set(patterns.map((p) => p.trim()).filter((p) => p.length > 0)));\n return deduped.map((pattern) => {\n const normalized = normalizeForMatch(pattern);\n const matchesPath = normalized.includes('/');\n return {\n globs: matchesPath ? compilePatternGlobs(normalized) : [normalized],\n matchesPath,\n };\n });\n}\n\nfunction toPatternSet(patterns: readonly CompiledPattern[]): CompiledPatternSet {\n const pathGlobs = new Set<string>();\n const nameGlobs = new Set<string>();\n\n for (const pattern of patterns) {\n const target = pattern.matchesPath ? pathGlobs : nameGlobs;\n for (const glob of pattern.globs) {\n target.add(glob);\n }\n }\n\n return {\n pathGlobs: [...pathGlobs],\n nameGlobs: [...nameGlobs],\n };\n}\n\nfunction matchesAnyGlob(globs: readonly string[], candidate: string): boolean {\n if (globs.length === 0) return false;\n\n for (const glob of globs) {\n if (posix.matchesGlob(candidate, glob)) return true;\n }\n\n return false;\n}\n\n// Strip NTFS alternate-data-stream suffixes (the \":stream\" after a segment)\n// before denylist matching, so `.env:secret` is caught as `.env`. Preserves the\n// drive-letter colon in the first segment of an absolute path. Also trims\n// trailing dots/spaces: Win32 strips them at the syscall boundary (a request\n// to create `.env ` actually creates `.env`), so without trimming them here the\n// exact-name patterns (`.env`, `.npmrc`) are bypassed on Windows. Mirrors the\n// precedent in getReservedDeviceName (path.ts) which trims for the same reason.\nfunction stripAlternateDataStreams(filePath: string): string {\n const parts = filePath.split(/[\\\\/]/);\n const stripped = parts.map((segment, i) => {\n if (\n i === 0 &&\n segment.length === 2 &&\n isAlpha(segment.charCodeAt(0)) &&\n segment.charCodeAt(1) === CHAR_COLON\n ) {\n return segment;\n }\n const colonIdx = segment.indexOf(':');\n const withoutStream = colonIdx !== -1 ? segment.slice(0, colonIdx) : segment;\n // Win32 strips trailing dots and spaces at the syscall boundary, so a\n // request for \".env \" creates \".env\". Strip them before denylist matching\n // or the exact-name patterns (\".env\", \".npmrc\") are bypassed on Windows.\n return trimTrailingDotsAndSpaces(withoutStream);\n });\n return stripped.join(sep);\n}\n\nconst trimTrailingDotsAndSpaces = (segment: string): string => segment.replace(/[. ]+$/, '');\n\nconst DEFAULT_SENSITIVE_PATTERNS = [\n '.env',\n '.env.*',\n '.npmrc',\n '.pypirc',\n '.aws/credentials',\n '.aws/config',\n '.mcpregistry_*_token',\n '*.pem',\n '*.key',\n '*.p12',\n '*.pfx',\n '*.crt',\n '*.cer',\n '*id_rsa*',\n '*id_dsa*',\n] as const;\n\nfunction buildSensitivePatterns(): readonly string[] {\n const allowSensitive =\n cli.allowSensitive ?? parseTrueEnvFlag(process.env['FS_ALLOW_SENSITIVE'], 'FS_ALLOW_SENSITIVE');\n const envValue = process.env['FS_DENYLIST'];\n const envDenylist = envValue\n ? envValue\n .split(/[,\\n]/u)\n .map((t) => t.trim())\n .filter((t) => t.length > 0)\n : [];\n const flagDenylist = cli.denyPatterns ?? [];\n // FS_ALLOW_SENSITIVE suppresses built-ins only; deny entries (env and --deny)\n // always apply. Set-dedupe so a pattern in both sources matches once.\n return [\n ...(allowSensitive ? [] : DEFAULT_SENSITIVE_PATTERNS),\n ...new Set([...envDenylist, ...flagDenylist]),\n ];\n}\n\nexport class SensitiveMatcher {\n private readonly patterns: CompiledPatternSet;\n\n constructor(patterns: readonly string[] = buildSensitivePatterns()) {\n this.patterns = toPatternSet(compilePatterns(patterns));\n }\n\n isSensitive(filePath: string): boolean {\n if (this.patterns.pathGlobs.length === 0 && this.patterns.nameGlobs.length === 0) {\n return false;\n }\n const pathToCheck = IS_WINDOWS ? stripAlternateDataStreams(filePath) : filePath;\n const normalizedPath = normalizeForMatch(pathToCheck);\n return (\n matchesAnyGlob(this.patterns.pathGlobs, normalizedPath) ||\n matchesAnyGlob(this.patterns.nameGlobs, posix.basename(normalizedPath))\n );\n }\n}\n"]}
1
+ {"version":3,"file":"sensitive.js","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,2EAA2E;AAC3E,wEAAwE;AACxE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAErF,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAE9B,SAAS,iBAAiB,CAAC,KAAa;IACtC,4EAA4E;IAC5E,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AACrD,CAAC;AAOD,SAAS,0BAA0B,CAAC,iBAAyB;IAC3D,OAAO,CACL,iBAAiB,CAAC,MAAM,IA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AAE,CAAC;IACP,MAAM,YAAY,GAAG,GAAG,CAAC,YAAY,IAAI,EAAE,CAAC;IAC5C,8EAA8E;IAC9E,sEAAsE;IACtE,OAAO;QACL,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,0BAA0B,CAAC;QACrD,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,YAAY,CAAC,CAAC;KAC9C,CAAC;AACJ,CAAC;AAED,MAAM,OAAO,gBAAgB;IACV,QAAQ,CAAqB;IAE9C,YAAY,WAA8B,sBAAsB,EAAE;QAChE,IAAI,CAAC,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IACzC,CAAC;IAED,WAAW,CAAC,QAAgB;QAC1B,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjF,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QAChF,MAAM,cAAc,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;QACtD,OAAO,CACL,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;YACvD,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC,CACxE,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Sensitive-file denylist policy: the compiled pattern set, the path\n// normalization that feeds it, and the NTFS alternate-data-stream stripping\n// Windows needs. Split out of path.ts so the denylist has its own home — it\n// shares only isAlpha / toPosixPath / IS_WINDOWS with the primitives in\n// primitives.ts, not the allowed-directory assembly. path-completer.ts and\n// glob.ts reach it through PathGuard.isSensitive, which delegates here.\nimport { normalize, posix, sep } from 'node:path';\n\nimport { cli } from './config.js';\nimport { IS_WINDOWS, isAlpha, parseTrueEnvFlag, toPosixPath } from './primitives.js';\n\nconst CHAR_COLON = 58;\nconst CHAR_FORWARD_SLASH = 47;\n\nfunction normalizeForMatch(input: string): string {\n // Always lowercase for case-insensitive denylist matching on all platforms.\n return toPosixPath(normalize(input)).toLowerCase();\n}\n\ninterface CompiledPatternSet {\n pathGlobs: readonly string[];\n nameGlobs: readonly string[];\n}\n\nfunction isWindowsAbsolutePosixPath(normalizedPattern: string): boolean {\n return (\n normalizedPattern.length >= 3 &&\n normalizedPattern.charCodeAt(1) === CHAR_COLON &&\n normalizedPattern.charCodeAt(2) === CHAR_FORWARD_SLASH &&\n isAlpha(normalizedPattern.charCodeAt(0))\n );\n}\n\nfunction compilePatternGlobs(normalizedPattern: string): readonly string[] {\n const globs = new Set<string>([normalizedPattern]);\n\n const isRooted =\n normalizedPattern.startsWith('**/') || isWindowsAbsolutePosixPath(normalizedPattern);\n if (!isRooted) {\n const withoutRoot = normalizedPattern.replace(/^\\/+/, '');\n if (withoutRoot) {\n globs.add(`**/${withoutRoot}`);\n }\n }\n\n return Array.from(globs);\n}\n\nfunction toPatternSet(patterns: readonly string[]): CompiledPatternSet {\n const pathGlobs = new Set<string>();\n const nameGlobs = new Set<string>();\n\n const deduped = Array.from(new Set(patterns.map((p) => p.trim()).filter((p) => p.length > 0)));\n for (const pattern of deduped) {\n const normalized = normalizeForMatch(pattern);\n const matchesPath = normalized.includes('/');\n const target = matchesPath ? pathGlobs : nameGlobs;\n for (const glob of matchesPath ? compilePatternGlobs(normalized) : [normalized]) {\n target.add(glob);\n }\n }\n\n return {\n pathGlobs: [...pathGlobs],\n nameGlobs: [...nameGlobs],\n };\n}\n\nfunction matchesAnyGlob(globs: readonly string[], candidate: string): boolean {\n if (globs.length === 0) return false;\n\n for (const glob of globs) {\n if (posix.matchesGlob(candidate, glob)) return true;\n }\n\n return false;\n}\n\n// Strip NTFS alternate-data-stream suffixes (the \":stream\" after a segment)\n// before denylist matching, so `.env:secret` is caught as `.env`. Preserves the\n// drive-letter colon in the first segment of an absolute path. Also trims\n// trailing dots/spaces: Win32 strips them at the syscall boundary (a request\n// to create `.env ` actually creates `.env`), so without trimming them here the\n// exact-name patterns (`.env`, `.npmrc`) are bypassed on Windows. Mirrors the\n// precedent in getReservedDeviceName (path.ts) which trims for the same reason.\nfunction stripAlternateDataStreams(filePath: string): string {\n const parts = filePath.split(/[\\\\/]/);\n const stripped = parts.map((segment, i) => {\n if (\n i === 0 &&\n segment.length === 2 &&\n isAlpha(segment.charCodeAt(0)) &&\n segment.charCodeAt(1) === CHAR_COLON\n ) {\n return segment;\n }\n const colonIdx = segment.indexOf(':');\n const withoutStream = colonIdx !== -1 ? segment.slice(0, colonIdx) : segment;\n // Win32 strips trailing dots and spaces at the syscall boundary, so a\n // request for \".env \" creates \".env\". Strip them before denylist matching\n // or the exact-name patterns (\".env\", \".npmrc\") are bypassed on Windows.\n return trimTrailingDotsAndSpaces(withoutStream);\n });\n return stripped.join(sep);\n}\n\nconst trimTrailingDotsAndSpaces = (segment: string): string => segment.replace(/[. ]+$/, '');\n\nconst DEFAULT_SENSITIVE_PATTERNS = [\n '.env',\n '.env.*',\n '.npmrc',\n '.pypirc',\n '.aws/credentials',\n '.aws/config',\n '.mcpregistry_*_token',\n '*.pem',\n '*.key',\n '*.p12',\n '*.pfx',\n '*.crt',\n '*.cer',\n '*id_rsa*',\n '*id_dsa*',\n] as const;\n\nfunction buildSensitivePatterns(): readonly string[] {\n const allowSensitive =\n cli.allowSensitive ?? parseTrueEnvFlag(process.env['FS_ALLOW_SENSITIVE'], 'FS_ALLOW_SENSITIVE');\n const envValue = process.env['FS_DENYLIST'];\n const envDenylist = envValue\n ? envValue\n .split(/[,\\n]/u)\n .map((t) => t.trim())\n .filter((t) => t.length > 0)\n : [];\n const flagDenylist = cli.denyPatterns ?? [];\n // FS_ALLOW_SENSITIVE suppresses built-ins only; deny entries (env and --deny)\n // always apply. Set-dedupe so a pattern in both sources matches once.\n return [\n ...(allowSensitive ? [] : DEFAULT_SENSITIVE_PATTERNS),\n ...new Set([...envDenylist, ...flagDenylist]),\n ];\n}\n\nexport class SensitiveMatcher {\n private readonly patterns: CompiledPatternSet;\n\n constructor(patterns: readonly string[] = buildSensitivePatterns()) {\n this.patterns = toPatternSet(patterns);\n }\n\n isSensitive(filePath: string): boolean {\n if (this.patterns.pathGlobs.length === 0 && this.patterns.nameGlobs.length === 0) {\n return false;\n }\n const pathToCheck = IS_WINDOWS ? stripAlternateDataStreams(filePath) : filePath;\n const normalizedPath = normalizeForMatch(pathToCheck);\n return (\n matchesAnyGlob(this.patterns.pathGlobs, normalizedPath) ||\n matchesAnyGlob(this.patterns.nameGlobs, posix.basename(normalizedPath))\n );\n }\n}\n"]}
@@ -4,7 +4,6 @@ interface ResourceEntry {
4
4
  name: string;
5
5
  mimeType: string;
6
6
  size: number;
7
- storedAt: string;
8
7
  expiresAt: string;
9
8
  text: string;
10
9
  }
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/core/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAQjE,UAAU,aAAa;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAeD,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoC;IAC1D,OAAO,CAAC,WAAW,CAAK;IAExB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA2B;gBAE7C,aAAa,CAAC,EAAE,MAAM,IAAI;IAItC,OAAO,CAAC,eAAe;IAIvB,OA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CAAC,QAAQ,CAAC,aAAa,CAA2B;gBAE7C,aAAa,CAAC,EAAE,MAAM,IAAI;IAItC,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,OAAO;IAQf,OAAO,CAAC,WAAW;IAUnB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,mBAAmB;IAa3B,OAAO,CAAC,aAAa;IAerB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa;IAuBpC,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,aAAa;IAoBjF;;;;;;;OAOG;IACH,IAAI,IAAI,MAAM,EAAE;CAIjB;AAED,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE;QACL,GAAG,EAAE,MAAM,CAAC;QACZ,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,CAAC;QACjB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,IAAI,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"}
@@ -100,7 +100,6 @@ export class ResourceStore {
100
100
  name: params.name,
101
101
  mimeType: params.mimeType ?? 'text/plain',
102
102
  size: entryBytes,
103
- storedAt: storedAt.toISOString(),
104
103
  expiresAt: new Date(storedAt.getTime() + ENTRY_TTL_MS).toISOString(),
105
104
  text: params.text,
106
105
  };
@@ -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,O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AAG;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 { 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 storedAt: string;\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 storedAt: storedAt.toISOString(),\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,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAWhC,MAA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,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"]}
package/dist/index.js CHANGED
@@ -29,7 +29,6 @@ async function shutdown(reason, exitCode = 0) {
29
29
  }
30
30
  shutdownStarted = true;
31
31
  process.exitCode = exitCode;
32
- let keepForceExitTimer = true;
33
32
  const timer = setTimeout(() => {
34
33
  logRuntimeFailure('shutdown_timeout', 'process', 'shutdown', `Shutdown timed out (${reason}), forcing exit.`);
35
34
  process.exit(exitCode);
@@ -60,15 +59,9 @@ async function shutdown(reason, exitCode = 0) {
60
59
  logRuntimeFailure('shutdown_mcp_error', 'process', 'shutdown', error);
61
60
  }
62
61
  }
63
- keepForceExitTimer = false;
64
- }
65
- catch (error) {
66
- logRuntimeFailure('shutdown_error', 'process', 'shutdown', error);
67
62
  }
68
63
  finally {
69
- if (!keepForceExitTimer) {
70
- clearTimeout(timer);
71
- }
64
+ clearTimeout(timer);
72
65
  }
73
66
  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port 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 let keepForceExitTimer = true;\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 keepForceExitTimer = false;\n } catch (error: unknown) {\n logRuntimeFailure('shutdown_error', 'process', 'shutdown', error);\n } finally {\n if (!keepForceExitTimer) {\n clearTimeout(timer);\n }\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,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7D,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE;QACtB,MAAM,MAAM,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAA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elcontextprotocol/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 +1 @@
1
- {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,SAAS,EAGV,MAAM,8BAA8B,CAAC;AAWtC,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,CA+C/D"}
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"}
package/dist/prompts.js CHANGED
@@ -1,6 +1,5 @@
1
- import { completable, ProtocolError } from '@modelcontextprotocol/server';
1
+ import { completable } from '@modelcontextprotocol/server';
2
2
  import * as z from 'zod/v4';
3
- import { formatUnknownErrorMessage, fsErrorCode, hasErrorShape } from './core/errors.js';
4
3
  import { Logger } from './core/observability.js';
5
4
  import { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';
6
5
  // --- Helpers ---
@@ -34,33 +33,19 @@ export function registerPrompts(deps) {
34
33
  topic: topicArg(topics, `Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`).optional(),
35
34
  }),
36
35
  }, ({ topic }) => {
37
- try {
38
- const lowerTopic = topic?.toLowerCase();
39
- const section = lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;
40
- if (topic && !section) {
41
- Logger.debug('get-help: unknown topic requested', { topic });
42
- }
43
- const text = section ??
44
- (topic
45
- ? `Section '${topic}' not found. Available: ${topics.join(', ')}\n\n${instructions}`
46
- : instructions);
47
- return {
48
- description: INSTRUCTIONS_SUMMARY,
49
- messages: [userText(text)],
50
- };
51
- }
52
- catch (error) {
53
- if (hasErrorShape(error, 'ProtocolError'))
54
- throw error;
55
- const message = formatUnknownErrorMessage(error);
56
- Logger.error(`Prompt handler failed: ${message}`, {
57
- promptName: 'get-help',
58
- error,
59
- });
60
- const protocolError = new ProtocolError(fsErrorCode(error), message);
61
- protocolError.cause = error;
62
- throw protocolError;
36
+ const lowerTopic = topic?.toLowerCase();
37
+ const section = lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;
38
+ if (topic && !section) {
39
+ Logger.debug('get-help: unknown topic requested', { topic });
63
40
  }
41
+ const text = section ??
42
+ (topic
43
+ ? `Section '${topic}' not found. Available: ${topics.join(', ')}\n\n${instructions}`
44
+ : instructions);
45
+ return {
46
+ description: INSTRUCTIONS_SUMMARY,
47
+ messages: [userText(text)],
48
+ };
64
49
  });
65
50
  }
66
51
  //# sourceMappingURL=prompts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAE1E,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACzF,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AA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YAC5B,MAAM,aAAa,CAAC;QACtB,CAAC;IACH,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n GetPromptResult,\n McpServer,\n PromptMessage,\n TextContent,\n} from '@modelcontextprotocol/server';\nimport { completable, ProtocolError } from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { formatUnknownErrorMessage, fsErrorCode, hasErrorShape } from './core/errors.js';\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 try {\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 } catch (error) {\n if (hasErrorShape(error, 'ProtocolError')) throw error;\n const message = formatUnknownErrorMessage(error);\n Logger.error(`Prompt handler failed: ${message}`, {\n promptName: 'get-help',\n error,\n });\n const protocolError = new ProtocolError(fsErrorCode(error), message);\n protocolError.cause = error;\n throw protocolError;\n }\n },\n );\n}\n"]}
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,C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,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,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"]}