@j0hanz/filesystem-mcp 2.1.1 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/dist/cli-help.js +1 -1
  3. package/dist/cli-help.js.map +1 -1
  4. package/dist/core/cursor.d.ts +37 -0
  5. package/dist/core/cursor.d.ts.map +1 -1
  6. package/dist/core/cursor.js +34 -0
  7. package/dist/core/cursor.js.map +1 -1
  8. package/dist/tools/batch.d.ts +20 -0
  9. package/dist/tools/batch.d.ts.map +1 -1
  10. package/dist/tools/batch.js +17 -0
  11. package/dist/tools/batch.js.map +1 -1
  12. package/dist/tools/create.js +3 -3
  13. package/dist/tools/create.js.map +1 -1
  14. package/dist/tools/define.d.ts +6 -0
  15. package/dist/tools/define.d.ts.map +1 -1
  16. package/dist/tools/define.js +1 -29
  17. package/dist/tools/define.js.map +1 -1
  18. package/dist/tools/delete-file.d.ts.map +1 -1
  19. package/dist/tools/delete-file.js +4 -1
  20. package/dist/tools/delete-file.js.map +1 -1
  21. package/dist/tools/edit.d.ts.map +1 -1
  22. package/dist/tools/edit.js +2 -1
  23. package/dist/tools/edit.js.map +1 -1
  24. package/dist/tools/list.d.ts.map +1 -1
  25. package/dist/tools/list.js +54 -66
  26. package/dist/tools/list.js.map +1 -1
  27. package/dist/tools/move.d.ts.map +1 -1
  28. package/dist/tools/move.js +5 -2
  29. package/dist/tools/move.js.map +1 -1
  30. package/dist/tools/read.d.ts.map +1 -1
  31. package/dist/tools/read.js +2 -1
  32. package/dist/tools/read.js.map +1 -1
  33. package/dist/tools/replace-in-files.d.ts.map +1 -1
  34. package/dist/tools/replace-in-files.js +4 -2
  35. package/dist/tools/replace-in-files.js.map +1 -1
  36. package/dist/tools/search-content.d.ts.map +1 -1
  37. package/dist/tools/search-content.js +58 -87
  38. package/dist/tools/search-content.js.map +1 -1
  39. package/dist/tools/search-files.d.ts.map +1 -1
  40. package/dist/tools/search-files.js +41 -59
  41. package/dist/tools/search-files.js.map +1 -1
  42. package/dist/tools/stat.d.ts.map +1 -1
  43. package/dist/tools/stat.js +2 -1
  44. package/dist/tools/stat.js.map +1 -1
  45. package/dist/{http-policy.d.ts → transport/http-policy.d.ts} +4 -4
  46. package/dist/transport/http-policy.d.ts.map +1 -0
  47. package/dist/{http-policy.js → transport/http-policy.js} +13 -9
  48. package/dist/transport/http-policy.js.map +1 -0
  49. package/dist/transport/http.d.ts.map +1 -1
  50. package/dist/transport/http.js +12 -2
  51. package/dist/transport/http.js.map +1 -1
  52. package/dist/transport/shared.d.ts +14 -0
  53. package/dist/transport/shared.d.ts.map +1 -1
  54. package/dist/transport/shared.js +13 -5
  55. package/dist/transport/shared.js.map +1 -1
  56. package/dist/transport/stdio.d.ts.map +1 -1
  57. package/dist/transport/stdio.js +58 -20
  58. package/dist/transport/stdio.js.map +1 -1
  59. package/package.json +1 -1
  60. package/dist/http-policy.d.ts.map +0 -1
  61. package/dist/http-policy.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { basename } from 'node:path';
2
2
  import * as z from 'zod/v4';
3
3
  import { timedSignal } from '../core/concurrency.js';
4
- import { createFirstPage, readNextPage } from '../core/cursor.js';
4
+ import { paginate } from '../core/cursor.js';
5
5
  import { ErrorCode } from '../core/errors.js';
6
6
  import { DEFAULT_EXCLUDE_PATTERNS, globEntries, isIgnoredByGitignore, loadRootGitignore, resolveEntryType, } from '../core/glob.js';
7
7
  import { toPosixRelative } from '../core/path.js';
@@ -137,7 +137,7 @@ const ListInputSchema = z.strictObject({
137
137
  .describe(`Max directory depth to traverse (default: ${String(DEFAULT_LIST_DEPTH)} = top-level only; increase to recurse deeper)`),
138
138
  maxEntries: PositiveInt.max(MAX_LIST_ENTRIES)
139
139
  .default(DEFAULT_LIST_ENTRIES)
140
- .describe(`Page size (default: ${String(DEFAULT_LIST_ENTRIES)}). Continue with nextCursor; resourceUri is only for hard-cap overflow.`),
140
+ .describe(`Page size (default: ${String(DEFAULT_LIST_ENTRIES)}). Continue with nextCursor; an incomplete first page also carries resourceUri for the whole list.`),
141
141
  includeHidden: includeHiddenField(),
142
142
  includeIgnored: includeIgnoredField(),
143
143
  cursor: CursorSchema,
@@ -162,9 +162,9 @@ const ListOutputSchema = z.strictObject({
162
162
  resourceUri: z
163
163
  .string()
164
164
  .optional()
165
- .describe('URI to the full entry list in the resource store; first page only, when total entries exceed the ' +
166
- 'hard cap (the same cap that bounds pagination; page via nextCursor below it). The stored list is ' +
167
- 'itself capped at that limit and marked truncated if exceeded.'),
165
+ .describe('URI to the full entry list in the resource store; first page only, whenever the response is ' +
166
+ 'incomplete more pages follow, or the hard cap cut the listing. The stored list is itself ' +
167
+ 'bounded by that cap and marked truncated if exceeded.'),
168
168
  nextCursor: NextCursorSchema,
169
169
  });
170
170
  function listQueryKey(args, path) {
@@ -176,7 +176,7 @@ function listQueryKey(args, path) {
176
176
  includeIgnored: args.includeIgnored,
177
177
  });
178
178
  }
179
- function listOutput(entries, metadata, nextCursor) {
179
+ function listOutput(entries, metadata, nextCursor, resourceUri) {
180
180
  return {
181
181
  path: metadata.path,
182
182
  entries: [...entries],
@@ -184,7 +184,7 @@ function listOutput(entries, metadata, nextCursor) {
184
184
  totalEntries: metadata.totalEntries,
185
185
  totalFiles: metadata.totalFiles,
186
186
  totalDirectories: metadata.totalDirectories,
187
- ...(metadata.resourceUri ? { resourceUri: metadata.resourceUri } : {}),
187
+ ...(resourceUri !== undefined ? { resourceUri } : {}),
188
188
  ...(nextCursor !== undefined ? { nextCursor } : {}),
189
189
  };
190
190
  }
@@ -192,74 +192,62 @@ async function handleList(args, ctx) {
192
192
  const path = args.path;
193
193
  const resolvedPath = ctx.fs.pathGuard.resolvePathOrRoot(path);
194
194
  const queryKey = listQueryKey(args, resolvedPath);
195
- if (args.cursor !== undefined) {
196
- const paged = readNextPage({
197
- store: ctx.pageStore,
198
- queryKey,
199
- cursor: args.cursor,
200
- pageSize: args.maxEntries,
201
- });
202
- // First page only: the overflow entry runs on ResourceStore's own TTL and
203
- // LRU, not this snapshot's, so replaying it hands back a dead pointer.
204
- const { resourceUri: _firstPageOnly, ...pageMetadata } = paged.metadata;
205
- return {
206
- structured: listOutput(paged.page, pageMetadata, paged.nextCursor),
207
- markdown: renderMarkdown(basename(paged.metadata.path), [...paged.page]),
208
- };
209
- }
210
- const validDir = await ctx.fs.pathGuard.validateExistingDirectory(resolvedPath);
211
- const result = await collect(validDir, {
212
- maxDepth: args.maxDepth,
213
- includeHidden: args.includeHidden,
214
- includeIgnored: args.includeIgnored,
215
- signal: timedSignal(ctx.signal, DEFAULT_SEARCH_TIMEOUT_MS),
216
- pathGuard: ctx.fs.pathGuard,
217
- entryCap: MAX_LIST_ENTRIES,
218
- ...(ctx.onProgress ? { onProgress: ctx.onProgress } : {}),
219
- });
220
- let resourceUri;
221
- let link;
222
- if (result.totalEntries > result.entries.length && ctx.resourceStore) {
223
- const fullMarkdown = renderMarkdown(basename(validDir), result.entries);
224
- const fullTruncated = result.totalEntries > result.entries.length;
225
- const fullOutput = {
226
- entries: result.entries,
227
- markdown: fullMarkdown,
228
- totalEntries: result.totalEntries,
229
- totalFiles: result.totalFiles,
230
- totalDirectories: result.totalDirectories,
231
- ...(fullTruncated ? { truncated: true } : {}),
232
- };
233
- const res = putJsonResource(ctx.resourceStore, `${basename(validDir)} tree`, fullOutput);
234
- resourceUri = res.entry.uri;
235
- link = res.link;
236
- }
237
- const metadata = {
238
- path: validDir,
239
- totalEntries: result.totalEntries,
240
- totalFiles: result.totalFiles,
241
- totalDirectories: result.totalDirectories,
242
- ...(resourceUri ? { resourceUri } : {}),
243
- };
244
- const paged = createFirstPage({
195
+ const { resourceStore } = ctx;
196
+ const paged = await paginate({
245
197
  store: ctx.pageStore,
246
198
  queryKey,
247
- items: result.entries,
248
- metadata,
199
+ cursor: args.cursor,
249
200
  pageSize: args.maxEntries,
201
+ produce: async () => {
202
+ const validDir = await ctx.fs.pathGuard.validateExistingDirectory(resolvedPath);
203
+ const result = await collect(validDir, {
204
+ maxDepth: args.maxDepth,
205
+ includeHidden: args.includeHidden,
206
+ includeIgnored: args.includeIgnored,
207
+ signal: timedSignal(ctx.signal, DEFAULT_SEARCH_TIMEOUT_MS),
208
+ pathGuard: ctx.fs.pathGuard,
209
+ entryCap: MAX_LIST_ENTRIES,
210
+ ...(ctx.onProgress ? { onProgress: ctx.onProgress } : {}),
211
+ });
212
+ return {
213
+ items: result.entries,
214
+ metadata: {
215
+ path: validDir,
216
+ totalEntries: result.totalEntries,
217
+ totalFiles: result.totalFiles,
218
+ totalDirectories: result.totalDirectories,
219
+ },
220
+ truncated: result.totalEntries > result.entries.length,
221
+ };
222
+ },
223
+ externalize: resourceStore
224
+ ? (entries, metadata) => {
225
+ const name = basename(metadata.path);
226
+ // The stored tree is the whole collected set — itself bounded by the
227
+ // hard cap, and marked when the cap cut it.
228
+ const fullOutput = {
229
+ entries,
230
+ markdown: renderMarkdown(name, entries),
231
+ totalEntries: metadata.totalEntries,
232
+ totalFiles: metadata.totalFiles,
233
+ totalDirectories: metadata.totalDirectories,
234
+ ...(metadata.totalEntries > entries.length ? { truncated: true } : {}),
235
+ };
236
+ return putJsonResource(resourceStore, `${name} tree`, fullOutput);
237
+ }
238
+ : undefined,
250
239
  });
251
- const output = listOutput(paged.page, metadata, paged.nextCursor);
252
240
  return {
253
- structured: output,
254
- markdown: renderMarkdown(basename(validDir), [...paged.page]),
255
- ...(link ? { link } : {}),
241
+ structured: listOutput(paged.page, paged.metadata, paged.nextCursor, paged.resource?.entry.uri),
242
+ markdown: renderMarkdown(basename(paged.metadata.path), [...paged.page]),
243
+ ...(paged.resource ? { link: paged.resource.link } : {}),
256
244
  };
257
245
  }
258
246
  export const LIST = defineTool({
259
247
  name: 'list',
260
248
  title: 'List',
261
249
  description: 'List sorted directory entries and an ASCII tree. maxDepth=1 is top-level. ' +
262
- 'maxEntries sets page size; continue with nextCursor. resourceUri is only for hard-cap overflow.',
250
+ 'maxEntries sets page size; continue with nextCursor. An incomplete first page also carries resourceUri for the whole list.',
263
251
  input: ListInputSchema,
264
252
  output: ListOutputSchema,
265
253
  // Not published: every field is a plainly-named scalar (`entryCount`,
@@ -281,7 +269,7 @@ export const LIST = defineTool({
281
269
  accessPaths: (args) => (args.path ? [args.path] : []),
282
270
  run: async (args, ctx) => {
283
271
  const { structured, markdown, link } = await handleList(args, ctx);
284
- // The tree is what the model reads; nextCursor and the overflow notice used
272
+ // The tree is what the model reads; nextCursor and the full-list URI used
285
273
  // to reach it only through the structured half, which now ships as _meta.
286
274
  // Both ride the text so paging needs no second lookup.
287
275
  const trailer = [];
@@ -289,7 +277,7 @@ export const LIST = defineTool({
289
277
  trailer.push(`nextCursor: ${structured.nextCursor}`);
290
278
  }
291
279
  if (structured.resourceUri !== undefined) {
292
- trailer.push(`truncated: ${String(structured.entryCount)} of ${String(structured.totalEntries)} entries shown; full tree at ${structured.resourceUri}`);
280
+ trailer.push(`${String(structured.entryCount)} of ${String(structured.totalEntries)} entries shown; full tree at ${structured.resourceUri}`);
293
281
  }
294
282
  return {
295
283
  structured,
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","sourceRoot":"","sources":["../../src/tools/list.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EACL,wBAAwB,EACxB,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EACL,YAAY,EACZ,QAAQ,IAAI,YAAY,EACxB,kBAA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CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACvC,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { timedSignal } from '../core/concurrency.js';\nimport { createFirstPage, readNextPage } from '../core/cursor.js';\nimport { ErrorCode } from '../core/errors.js';\nimport type { EntryType } from '../core/glob.js';\nimport {\n DEFAULT_EXCLUDE_PATTERNS,\n globEntries,\n isIgnoredByGitignore,\n loadRootGitignore,\n resolveEntryType,\n} from '../core/glob.js';\nimport type { PathGuard } from '../core/path.js';\nimport { toPosixRelative } from '../core/path.js';\nimport {\n CursorSchema,\n FileType as FileTypeEnum,\n includeHiddenField,\n includeIgnoredField,\n NextCursorSchema,\n NonNegInt,\n OptionalPath,\n PositiveInt,\n} from '../core/schema.js';\nimport { putJsonResource } from '../core/store.js';\nimport {\n DEFAULT_SEARCH_TIMEOUT_MS,\n DEFAULT_TREE_ENTRIES,\n MAX_LIST_ENTRIES,\n MAX_TREE_DEPTH,\n} from '../core/util.js';\nimport { defineTool, type ToolCtx } from './define.js';\n\ninterface CollectedEntry {\n name: string;\n relativePath: string; // POSIX\n type: EntryType;\n}\n\ninterface CollectOptions {\n maxDepth: number;\n includeHidden: boolean;\n includeIgnored: boolean;\n signal: AbortSignal;\n pathGuard: PathGuard;\n /** Upper bound on the stored, paginable entry array. */\n entryCap: number;\n onProgress?: (progress: { current: number; total?: number }) => void;\n}\n\ninterface CollectResult {\n entries: CollectedEntry[];\n totalEntries: number;\n totalFiles: number;\n totalDirectories: number;\n}\n\nfunction entryTypeRank(type: EntryType): number {\n if (type === 'directory') return 0;\n return 1;\n}\n\nfunction compareEntries(a: CollectedEntry, b: CollectedEntry): number {\n // Compare by parent directory first (depth-level grouping)\n const slashA = a.relativePath.lastIndexOf('/');\n const slashB = b.relativePath.lastIndexOf('/');\n const parentA = slashA === -1 ? '' : a.relativePath.slice(0, slashA);\n const parentB = slashB === -1 ? '' : b.relativePath.slice(0, slashB);\n\n if (parentA !== parentB) return parentA.localeCompare(parentB);\n\n // Within same parent: dirs first, then alphabetical\n const rankDiff = entryTypeRank(a.type) - entryTypeRank(b.type);\n if (rankDiff !== 0) return rankDiff;\n return a.name.localeCompare(b.name);\n}\n\nasync function collect(rootPath: string, options: CollectOptions): Promise<CollectResult> {\n const gitignoreMatcher = options.includeIgnored\n ? null\n : await loadRootGitignore(rootPath, options.signal);\n\n const entries: CollectedEntry[] = [];\n let scanned = 0;\n let totalEntries = 0;\n let totalFiles = 0;\n let totalDirectories = 0;\n\n for await (const entry of globEntries({\n cwd: rootPath,\n pattern: '**/*',\n excludePatterns: options.includeIgnored ? [] : DEFAULT_EXCLUDE_PATTERNS,\n includeHidden: options.includeHidden,\n baseNameMatch: false,\n // ListInputSchema.maxDepth is 1-based (1 = top-level only); the shared\n // globEntries primitive is now 0-based, so subtract one here. options.maxDepth\n // is guaranteed >= 1 by its PositiveInt schema, so this never underflows.\n maxDepth: options.maxDepth - 1,\n onlyFiles: false,\n })) {\n options.signal.throwIfAborted();\n scanned++;\n options.onProgress?.({ current: scanned });\n\n const entryType: EntryType = resolveEntryType(entry.dirent);\n const isDir = entryType === 'directory';\n const relPath = toPosixRelative(rootPath, entry.path);\n const name = basename(relPath);\n\n if (\n gitignoreMatcher &&\n isIgnoredByGitignore(gitignoreMatcher, rootPath, entry.path, {\n isDirectory: isDir,\n })\n ) {\n continue;\n }\n const accessible = await options.pathGuard.isEntryAccessible(entry.path, entryType, [rootPath]);\n if (!accessible) continue;\n\n totalEntries++;\n if (entryType === 'directory') {\n totalDirectories++;\n } else {\n totalFiles++;\n }\n\n const collectedEntry: CollectedEntry = {\n name,\n relativePath: relPath,\n type: entryType,\n };\n\n if (entries.length < options.entryCap) {\n entries.push(collectedEntry);\n }\n }\n\n options.signal.throwIfAborted();\n entries.sort(compareEntries);\n\n return {\n entries,\n totalEntries,\n totalFiles,\n totalDirectories,\n };\n}\n\nconst TEE = '├── ';\nconst ELBOW = '└── ';\nconst PIPE = '│ ';\nconst INDENT = ' ';\n\nfunction renderMarkdown(rootName: string, entries: CollectedEntry[]): string {\n if (entries.length === 0) return rootName;\n\n // Group entries by parent path\n const childrenOf = new Map<string, CollectedEntry[]>();\n for (const entry of entries) {\n const slash = entry.relativePath.lastIndexOf('/');\n const parentKey = slash === -1 ? '' : entry.relativePath.slice(0, slash);\n if (!childrenOf.has(parentKey)) childrenOf.set(parentKey, []);\n const children = childrenOf.get(parentKey);\n if (children) children.push(entry);\n }\n\n const lines: string[] = [rootName];\n\n function renderChildren(parentKey: string, prefix: string): void {\n const children = childrenOf.get(parentKey);\n if (!children) return;\n\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (!child) continue;\n const isLast = i === children.length - 1;\n const connector = isLast ? ELBOW : TEE;\n lines.push(prefix + connector + child.name);\n\n const childKey = child.relativePath;\n const nextPrefix = prefix + (isLast ? INDENT : PIPE);\n renderChildren(childKey, nextPrefix);\n }\n }\n\n renderChildren('', '');\n return lines.join('\\n');\n}\n\nconst DEFAULT_LIST_DEPTH = 1;\nconst DEFAULT_LIST_ENTRIES = DEFAULT_TREE_ENTRIES;\n\nconst ListInputSchema = z.strictObject({\n path: OptionalPath.describe('Directory to list (default: first allowed root)'),\n maxDepth: PositiveInt.max(MAX_TREE_DEPTH)\n .default(DEFAULT_LIST_DEPTH)\n .describe(\n `Max directory depth to traverse (default: ${String(DEFAULT_LIST_DEPTH)} = top-level only; increase to recurse deeper)`,\n ),\n maxEntries: PositiveInt.max(MAX_LIST_ENTRIES)\n .default(DEFAULT_LIST_ENTRIES)\n .describe(\n `Page size (default: ${String(DEFAULT_LIST_ENTRIES)}). Continue with nextCursor; resourceUri is only for hard-cap overflow.`,\n ),\n includeHidden: includeHiddenField(),\n includeIgnored: includeIgnoredField(),\n cursor: CursorSchema,\n});\n\nconst ListOutputSchema = z.strictObject({\n path: z.string().optional().describe('Resolved absolute path of the listed directory'),\n entries: z\n .array(\n z.strictObject({\n name: z.string().describe('Entry basename'),\n relativePath: z.string().describe('POSIX path relative to the listed directory'),\n type: FileTypeEnum.describe('Entry type: file, directory, symlink, or other'),\n }),\n )\n .describe('Inline directory entries sorted directories-first then alphabetically by name'),\n // No `markdown` field: the ASCII tree is the call's text content already, and\n // carrying it here too doubled every list response for a string the client\n // has in hand. The stored full-tree resource still holds its own copy — that\n // one is a *different* (uncapped) tree and is never sent inline.\n entryCount: NonNegInt.describe('Number of entries included in this response'),\n totalEntries: NonNegInt.describe('Total entries found before the maxEntries cap was applied'),\n totalFiles: NonNegInt.describe('Total number of files found'),\n totalDirectories: NonNegInt.describe('Total number of directories found'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'URI to the full entry list in the resource store; first page only, when total entries exceed the ' +\n 'hard cap (the same cap that bounds pagination; page via nextCursor below it). The stored list is ' +\n 'itself capped at that limit and marked truncated if exceeded.',\n ),\n nextCursor: NextCursorSchema,\n});\n\ninterface ListPageMetadata {\n readonly path: string;\n readonly totalEntries: number;\n readonly totalFiles: number;\n readonly totalDirectories: number;\n readonly resourceUri?: string;\n}\n\nfunction listQueryKey(args: z.infer<typeof ListInputSchema>, path: string): string {\n return JSON.stringify({\n method: 'list',\n path,\n maxDepth: args.maxDepth,\n includeHidden: args.includeHidden,\n includeIgnored: args.includeIgnored,\n });\n}\n\nfunction listOutput(\n entries: readonly CollectedEntry[],\n metadata: ListPageMetadata,\n nextCursor: string | undefined,\n): z.infer<typeof ListOutputSchema> {\n return {\n path: metadata.path,\n entries: [...entries],\n entryCount: entries.length,\n totalEntries: metadata.totalEntries,\n totalFiles: metadata.totalFiles,\n totalDirectories: metadata.totalDirectories,\n ...(metadata.resourceUri ? { resourceUri: metadata.resourceUri } : {}),\n ...(nextCursor !== undefined ? { nextCursor } : {}),\n };\n}\n\nasync function handleList(\n args: z.infer<typeof ListInputSchema>,\n ctx: ToolCtx,\n): Promise<{\n structured: z.infer<typeof ListOutputSchema>;\n markdown: string;\n link?: ContentBlock;\n}> {\n const path = args.path;\n const resolvedPath = ctx.fs.pathGuard.resolvePathOrRoot(path);\n const queryKey = listQueryKey(args, resolvedPath);\n\n if (args.cursor !== undefined) {\n const paged = readNextPage<CollectedEntry, ListPageMetadata>({\n store: ctx.pageStore,\n queryKey,\n cursor: args.cursor,\n pageSize: args.maxEntries,\n });\n // First page only: the overflow entry runs on ResourceStore's own TTL and\n // LRU, not this snapshot's, so replaying it hands back a dead pointer.\n const { resourceUri: _firstPageOnly, ...pageMetadata } = paged.metadata;\n return {\n structured: listOutput(paged.page, pageMetadata, paged.nextCursor),\n markdown: renderMarkdown(basename(paged.metadata.path), [...paged.page]),\n };\n }\n\n const validDir = await ctx.fs.pathGuard.validateExistingDirectory(resolvedPath);\n const result = await collect(validDir, {\n maxDepth: args.maxDepth,\n includeHidden: args.includeHidden,\n includeIgnored: args.includeIgnored,\n signal: timedSignal(ctx.signal, DEFAULT_SEARCH_TIMEOUT_MS),\n pathGuard: ctx.fs.pathGuard,\n entryCap: MAX_LIST_ENTRIES,\n ...(ctx.onProgress ? { onProgress: ctx.onProgress } : {}),\n });\n let resourceUri: string | undefined;\n let link: ContentBlock | undefined;\n if (result.totalEntries > result.entries.length && ctx.resourceStore) {\n const fullMarkdown = renderMarkdown(basename(validDir), result.entries);\n const fullTruncated = result.totalEntries > result.entries.length;\n const fullOutput = {\n entries: result.entries,\n markdown: fullMarkdown,\n totalEntries: result.totalEntries,\n totalFiles: result.totalFiles,\n totalDirectories: result.totalDirectories,\n ...(fullTruncated ? { truncated: true } : {}),\n };\n const res = putJsonResource(ctx.resourceStore, `${basename(validDir)} tree`, fullOutput);\n resourceUri = res.entry.uri;\n link = res.link;\n }\n\n const metadata: ListPageMetadata = {\n path: validDir,\n totalEntries: result.totalEntries,\n totalFiles: result.totalFiles,\n totalDirectories: result.totalDirectories,\n ...(resourceUri ? { resourceUri } : {}),\n };\n const paged = createFirstPage<CollectedEntry, ListPageMetadata>({\n store: ctx.pageStore,\n queryKey,\n items: result.entries,\n metadata,\n pageSize: args.maxEntries,\n });\n const output = listOutput(paged.page, metadata, paged.nextCursor);\n\n return {\n structured: output,\n markdown: renderMarkdown(basename(validDir), [...paged.page]),\n ...(link ? { link } : {}),\n };\n}\n\nexport const LIST = defineTool({\n name: 'list',\n title: 'List',\n description:\n 'List sorted directory entries and an ASCII tree. maxDepth=1 is top-level. ' +\n 'maxEntries sets page size; continue with nextCursor. resourceUri is only for hard-cap overflow.',\n input: ListInputSchema,\n output: ListOutputSchema,\n // Not published: every field is a plainly-named scalar (`entryCount`,\n // `totalFiles`, `nextCursor`) that one sample response teaches, and the\n // schema costs 1599 chars of every session start. Publishing is reserved for\n // the value-XOR-error union shape a sample cannot convey.\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_DIRECTORY,\n progress: (args) => ({\n label: 'List',\n subject: args.path ? basename(args.path) : '.',\n }),\n accessPaths: (args) => (args.path ? [args.path] : []),\n run: async (args, ctx) => {\n const { structured, markdown, link } = await handleList(args, ctx);\n // The tree is what the model reads; nextCursor and the overflow notice used\n // to reach it only through the structured half, which now ships as _meta.\n // Both ride the text so paging needs no second lookup.\n const trailer: string[] = [];\n if (structured.nextCursor !== undefined) {\n trailer.push(`nextCursor: ${structured.nextCursor}`);\n }\n if (structured.resourceUri !== undefined) {\n trailer.push(\n `truncated: ${String(structured.entryCount)} of ${String(structured.totalEntries)} entries shown; full tree at ${structured.resourceUri}`,\n );\n }\n return {\n structured,\n text: trailer.length > 0 ? `${markdown}\\n\\n${trailer.join('\\n')}` : markdown,\n ...(link ? { resources: [link] } : {}),\n };\n },\n});\n"]}
1
+ {"version":3,"file":"list.js","sourceRoot":"","sources":["../../src/tools/list.ts"],"names":[],"mappings":"AAEA,OAAO,E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} from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { timedSignal } from '../core/concurrency.js';\nimport { paginate } from '../core/cursor.js';\nimport { ErrorCode } from '../core/errors.js';\nimport type { EntryType } from '../core/glob.js';\nimport {\n DEFAULT_EXCLUDE_PATTERNS,\n globEntries,\n isIgnoredByGitignore,\n loadRootGitignore,\n resolveEntryType,\n} from '../core/glob.js';\nimport type { PathGuard } from '../core/path.js';\nimport { toPosixRelative } from '../core/path.js';\nimport {\n CursorSchema,\n FileType as FileTypeEnum,\n includeHiddenField,\n includeIgnoredField,\n NextCursorSchema,\n NonNegInt,\n OptionalPath,\n PositiveInt,\n} from '../core/schema.js';\nimport type { JsonResourceResult } from '../core/store.js';\nimport { putJsonResource } from '../core/store.js';\nimport {\n DEFAULT_SEARCH_TIMEOUT_MS,\n DEFAULT_TREE_ENTRIES,\n MAX_LIST_ENTRIES,\n MAX_TREE_DEPTH,\n} from '../core/util.js';\nimport { defineTool, type ToolCtx } from './define.js';\n\ninterface CollectedEntry {\n name: string;\n relativePath: string; // POSIX\n type: EntryType;\n}\n\ninterface CollectOptions {\n maxDepth: number;\n includeHidden: boolean;\n includeIgnored: boolean;\n signal: AbortSignal;\n pathGuard: PathGuard;\n /** Upper bound on the stored, paginable entry array. */\n entryCap: number;\n onProgress?: (progress: { current: number; total?: number }) => void;\n}\n\ninterface CollectResult {\n entries: CollectedEntry[];\n totalEntries: number;\n totalFiles: number;\n totalDirectories: number;\n}\n\nfunction entryTypeRank(type: EntryType): number {\n if (type === 'directory') return 0;\n return 1;\n}\n\nfunction compareEntries(a: CollectedEntry, b: CollectedEntry): number {\n // Compare by parent directory first (depth-level grouping)\n const slashA = a.relativePath.lastIndexOf('/');\n const slashB = b.relativePath.lastIndexOf('/');\n const parentA = slashA === -1 ? '' : a.relativePath.slice(0, slashA);\n const parentB = slashB === -1 ? '' : b.relativePath.slice(0, slashB);\n\n if (parentA !== parentB) return parentA.localeCompare(parentB);\n\n // Within same parent: dirs first, then alphabetical\n const rankDiff = entryTypeRank(a.type) - entryTypeRank(b.type);\n if (rankDiff !== 0) return rankDiff;\n return a.name.localeCompare(b.name);\n}\n\nasync function collect(rootPath: string, options: CollectOptions): Promise<CollectResult> {\n const gitignoreMatcher = options.includeIgnored\n ? null\n : await loadRootGitignore(rootPath, options.signal);\n\n const entries: CollectedEntry[] = [];\n let scanned = 0;\n let totalEntries = 0;\n let totalFiles = 0;\n let totalDirectories = 0;\n\n for await (const entry of globEntries({\n cwd: rootPath,\n pattern: '**/*',\n excludePatterns: options.includeIgnored ? [] : DEFAULT_EXCLUDE_PATTERNS,\n includeHidden: options.includeHidden,\n baseNameMatch: false,\n // ListInputSchema.maxDepth is 1-based (1 = top-level only); the shared\n // globEntries primitive is now 0-based, so subtract one here. options.maxDepth\n // is guaranteed >= 1 by its PositiveInt schema, so this never underflows.\n maxDepth: options.maxDepth - 1,\n onlyFiles: false,\n })) {\n options.signal.throwIfAborted();\n scanned++;\n options.onProgress?.({ current: scanned });\n\n const entryType: EntryType = resolveEntryType(entry.dirent);\n const isDir = entryType === 'directory';\n const relPath = toPosixRelative(rootPath, entry.path);\n const name = basename(relPath);\n\n if (\n gitignoreMatcher &&\n isIgnoredByGitignore(gitignoreMatcher, rootPath, entry.path, {\n isDirectory: isDir,\n })\n ) {\n continue;\n }\n const accessible = await options.pathGuard.isEntryAccessible(entry.path, entryType, [rootPath]);\n if (!accessible) continue;\n\n totalEntries++;\n if (entryType === 'directory') {\n totalDirectories++;\n } else {\n totalFiles++;\n }\n\n const collectedEntry: CollectedEntry = {\n name,\n relativePath: relPath,\n type: entryType,\n };\n\n if (entries.length < options.entryCap) {\n entries.push(collectedEntry);\n }\n }\n\n options.signal.throwIfAborted();\n entries.sort(compareEntries);\n\n return {\n entries,\n totalEntries,\n totalFiles,\n totalDirectories,\n };\n}\n\nconst TEE = '├── ';\nconst ELBOW = '└── ';\nconst PIPE = '│ ';\nconst INDENT = ' ';\n\nfunction renderMarkdown(rootName: string, entries: readonly CollectedEntry[]): string {\n if (entries.length === 0) return rootName;\n\n // Group entries by parent path\n const childrenOf = new Map<string, CollectedEntry[]>();\n for (const entry of entries) {\n const slash = entry.relativePath.lastIndexOf('/');\n const parentKey = slash === -1 ? '' : entry.relativePath.slice(0, slash);\n if (!childrenOf.has(parentKey)) childrenOf.set(parentKey, []);\n const children = childrenOf.get(parentKey);\n if (children) children.push(entry);\n }\n\n const lines: string[] = [rootName];\n\n function renderChildren(parentKey: string, prefix: string): void {\n const children = childrenOf.get(parentKey);\n if (!children) return;\n\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (!child) continue;\n const isLast = i === children.length - 1;\n const connector = isLast ? ELBOW : TEE;\n lines.push(prefix + connector + child.name);\n\n const childKey = child.relativePath;\n const nextPrefix = prefix + (isLast ? INDENT : PIPE);\n renderChildren(childKey, nextPrefix);\n }\n }\n\n renderChildren('', '');\n return lines.join('\\n');\n}\n\nconst DEFAULT_LIST_DEPTH = 1;\nconst DEFAULT_LIST_ENTRIES = DEFAULT_TREE_ENTRIES;\n\nconst ListInputSchema = z.strictObject({\n path: OptionalPath.describe('Directory to list (default: first allowed root)'),\n maxDepth: PositiveInt.max(MAX_TREE_DEPTH)\n .default(DEFAULT_LIST_DEPTH)\n .describe(\n `Max directory depth to traverse (default: ${String(DEFAULT_LIST_DEPTH)} = top-level only; increase to recurse deeper)`,\n ),\n maxEntries: PositiveInt.max(MAX_LIST_ENTRIES)\n .default(DEFAULT_LIST_ENTRIES)\n .describe(\n `Page size (default: ${String(DEFAULT_LIST_ENTRIES)}). Continue with nextCursor; an incomplete first page also carries resourceUri for the whole list.`,\n ),\n includeHidden: includeHiddenField(),\n includeIgnored: includeIgnoredField(),\n cursor: CursorSchema,\n});\n\nconst ListOutputSchema = z.strictObject({\n path: z.string().optional().describe('Resolved absolute path of the listed directory'),\n entries: z\n .array(\n z.strictObject({\n name: z.string().describe('Entry basename'),\n relativePath: z.string().describe('POSIX path relative to the listed directory'),\n type: FileTypeEnum.describe('Entry type: file, directory, symlink, or other'),\n }),\n )\n .describe('Inline directory entries sorted directories-first then alphabetically by name'),\n // No `markdown` field: the ASCII tree is the call's text content already, and\n // carrying it here too doubled every list response for a string the client\n // has in hand. The stored full-tree resource still holds its own copy — that\n // one is a *different* (uncapped) tree and is never sent inline.\n entryCount: NonNegInt.describe('Number of entries included in this response'),\n totalEntries: NonNegInt.describe('Total entries found before the maxEntries cap was applied'),\n totalFiles: NonNegInt.describe('Total number of files found'),\n totalDirectories: NonNegInt.describe('Total number of directories found'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'URI to the full entry list in the resource store; first page only, whenever the response is ' +\n 'incomplete — more pages follow, or the hard cap cut the listing. The stored list is itself ' +\n 'bounded by that cap and marked truncated if exceeded.',\n ),\n nextCursor: NextCursorSchema,\n});\n\ninterface ListPageMetadata {\n readonly path: string;\n readonly totalEntries: number;\n readonly totalFiles: number;\n readonly totalDirectories: number;\n}\n\nfunction listQueryKey(args: z.infer<typeof ListInputSchema>, path: string): string {\n return JSON.stringify({\n method: 'list',\n path,\n maxDepth: args.maxDepth,\n includeHidden: args.includeHidden,\n includeIgnored: args.includeIgnored,\n });\n}\n\nfunction listOutput(\n entries: readonly CollectedEntry[],\n metadata: ListPageMetadata,\n nextCursor: string | undefined,\n resourceUri: string | undefined,\n): z.infer<typeof ListOutputSchema> {\n return {\n path: metadata.path,\n entries: [...entries],\n entryCount: entries.length,\n totalEntries: metadata.totalEntries,\n totalFiles: metadata.totalFiles,\n totalDirectories: metadata.totalDirectories,\n ...(resourceUri !== undefined ? { resourceUri } : {}),\n ...(nextCursor !== undefined ? { nextCursor } : {}),\n };\n}\n\nasync function handleList(\n args: z.infer<typeof ListInputSchema>,\n ctx: ToolCtx,\n): Promise<{\n structured: z.infer<typeof ListOutputSchema>;\n markdown: string;\n link?: ContentBlock;\n}> {\n const path = args.path;\n const resolvedPath = ctx.fs.pathGuard.resolvePathOrRoot(path);\n const queryKey = listQueryKey(args, resolvedPath);\n const { resourceStore } = ctx;\n\n const paged = await paginate<CollectedEntry, ListPageMetadata, JsonResourceResult>({\n store: ctx.pageStore,\n queryKey,\n cursor: args.cursor,\n pageSize: args.maxEntries,\n produce: async () => {\n const validDir = await ctx.fs.pathGuard.validateExistingDirectory(resolvedPath);\n const result = await collect(validDir, {\n maxDepth: args.maxDepth,\n includeHidden: args.includeHidden,\n includeIgnored: args.includeIgnored,\n signal: timedSignal(ctx.signal, DEFAULT_SEARCH_TIMEOUT_MS),\n pathGuard: ctx.fs.pathGuard,\n entryCap: MAX_LIST_ENTRIES,\n ...(ctx.onProgress ? { onProgress: ctx.onProgress } : {}),\n });\n return {\n items: result.entries,\n metadata: {\n path: validDir,\n totalEntries: result.totalEntries,\n totalFiles: result.totalFiles,\n totalDirectories: result.totalDirectories,\n },\n truncated: result.totalEntries > result.entries.length,\n };\n },\n externalize: resourceStore\n ? (entries, metadata) => {\n const name = basename(metadata.path);\n // The stored tree is the whole collected set — itself bounded by the\n // hard cap, and marked when the cap cut it.\n const fullOutput = {\n entries,\n markdown: renderMarkdown(name, entries),\n totalEntries: metadata.totalEntries,\n totalFiles: metadata.totalFiles,\n totalDirectories: metadata.totalDirectories,\n ...(metadata.totalEntries > entries.length ? { truncated: true } : {}),\n };\n return putJsonResource(resourceStore, `${name} tree`, fullOutput);\n }\n : undefined,\n });\n\n return {\n structured: listOutput(paged.page, paged.metadata, paged.nextCursor, paged.resource?.entry.uri),\n markdown: renderMarkdown(basename(paged.metadata.path), [...paged.page]),\n ...(paged.resource ? { link: paged.resource.link } : {}),\n };\n}\n\nexport const LIST = defineTool({\n name: 'list',\n title: 'List',\n description:\n 'List sorted directory entries and an ASCII tree. maxDepth=1 is top-level. ' +\n 'maxEntries sets page size; continue with nextCursor. An incomplete first page also carries resourceUri for the whole list.',\n input: ListInputSchema,\n output: ListOutputSchema,\n // Not published: every field is a plainly-named scalar (`entryCount`,\n // `totalFiles`, `nextCursor`) that one sample response teaches, and the\n // schema costs 1599 chars of every session start. Publishing is reserved for\n // the value-XOR-error union shape a sample cannot convey.\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_DIRECTORY,\n progress: (args) => ({\n label: 'List',\n subject: args.path ? basename(args.path) : '.',\n }),\n accessPaths: (args) => (args.path ? [args.path] : []),\n run: async (args, ctx) => {\n const { structured, markdown, link } = await handleList(args, ctx);\n // The tree is what the model reads; nextCursor and the full-list URI used\n // to reach it only through the structured half, which now ships as _meta.\n // Both ride the text so paging needs no second lookup.\n const trailer: string[] = [];\n if (structured.nextCursor !== undefined) {\n trailer.push(`nextCursor: ${structured.nextCursor}`);\n }\n if (structured.resourceUri !== undefined) {\n trailer.push(\n `${String(structured.entryCount)} of ${String(structured.totalEntries)} entries shown; full tree at ${structured.resourceUri}`,\n );\n }\n return {\n structured,\n text: trailer.length > 0 ? `${markdown}\\n\\n${trailer.join('\\n')}` : markdown,\n ...(link ? { resources: [link] } : {}),\n };\n },\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"move.d.ts","sourceRoot":"","sources":["../../src/tools/move.ts"],"names":[],"mappings":"AAsaA,eAAO,MAAM,IAAI,mCA8Cf,CAAC"}
1
+ {"version":3,"file":"move.d.ts","sourceRoot":"","sources":["../../src/tools/move.ts"],"names":[],"mappings":"AAsaA,eAAO,MAAM,IAAI,mCA4Cf,CAAC"}
@@ -7,7 +7,7 @@ import { destExists } from '../core/fs.js';
7
7
  import { readAcceptedChoice } from '../core/input-required.js';
8
8
  import { IS_CASE_INSENSITIVE_FS, isPathInsideDirectory, isSamePath } from '../core/path-utils.js';
9
9
  import { defaultFalseBoolean, pairFailureSchema, RequiredPath } from '../core/schema.js';
10
- import { pairFailure, runOverPairs } from './batch.js';
10
+ import { isTotalFailure, pairFailure, runOverPairs } from './batch.js';
11
11
  import { defineTool } from './define.js';
12
12
  const MoveItemSchema = z.strictObject({
13
13
  source: RequiredPath.describe('Path of the file or directory to move or copy'),
@@ -312,9 +312,12 @@ export const MOVE = defineTool({
312
312
  // verbatim so the executor short-circuits before building a CallToolResult.
313
313
  if (isInputRequiredResult(output))
314
314
  return output;
315
+ const failures = output.failures ?? [];
316
+ const skipped = output.skipped ?? [];
315
317
  return {
316
318
  structured: output,
317
- text: buildSummary(args.copy ? 'copy' : 'move', output.moves, output.failures ?? [], output.skipped ?? []),
319
+ text: buildSummary(args.copy ? 'copy' : 'move', output.moves, failures, skipped),
320
+ isError: isTotalFailure({ results: output.moves, skipped, failures }),
318
321
  };
319
322
  },
320
323
  });
@@ -1 +1 @@
1
- {"version":3,"file":"move.js","sourceRoot":"","sources":["../../src/tools/move.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAE5D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,WAAW,EACX,OAAO,EACP,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAClG,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEzF,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC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,CAAC,IAAI,EAAE,MAAM,IAAI,EAAE,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,WAAW,IAAI,EAAE,CAAC,EAAE;aAClF,CAAC;QACJ,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;IAClE,CAAC;IACD,gBAAgB,EAAE,SAAS,CAAC,OAAO;IACnC,WAAW,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC;IAC3E,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QACvB,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC3C,qEAAqE;QACrE,4EAA4E;QAC5E,IAAI,qBAAqB,CAAC,MAAM,CAAC;YAAE,OAAO,MAAM,CAAC;QACjD,OAAO;YACL,UAAU,EAAE,MAAM;YAClB,IAAI,EAAE,YAAY,CAChB,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAC3B,MAAM,CAAC,KAAK,EACZ,MAAM,CAAC,QAAQ,IAAI,EAAE,EACrB,MAAM,CAAC,OAAO,IAAI,EAAE,CACrB;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { InputRequiredResult } from '@modelcontextprotocol/server';\nimport { isInputRequiredResult } from '@modelcontextprotocol/server';\n\nimport { basename, dirname, resolve, sep } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n Problem,\n rethrowIfAborted,\n} from '../core/errors.js';\nimport { joinRoster, pathLabel } from '../core/fmt.js';\nimport { destExists } from '../core/fs.js';\nimport type { GuardedFileSystem } from '../core/fs.js';\nimport { readAcceptedChoice } from '../core/input-required.js';\nimport { IS_CASE_INSENSITIVE_FS, isPathInsideDirectory, isSamePath } from '../core/path-utils.js';\nimport { defaultFalseBoolean, pairFailureSchema, RequiredPath } from '../core/schema.js';\nimport type { PairExecResult, PairPlanResult } from './batch.js';\nimport { pairFailure, runOverPairs } from './batch.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst MoveItemSchema = z.strictObject({\n source: RequiredPath.describe('Path of the file or directory to move or copy'),\n destination: RequiredPath.describe('Destination path'),\n});\n\nconst MoveItemResultSchema = z.strictObject({\n from: z.string().describe('Resolved absolute source path'),\n to: z.string().describe('Resolved absolute destination path'),\n});\n\nconst MoveInputSchema = z.strictObject({\n moves: z.array(MoveItemSchema).min(1).max(100).describe('Operations to perform (max 100)'),\n copy: defaultFalseBoolean('Copy instead of move; sources are left in place'),\n overwrite: defaultFalseBoolean(\n 'Copy mode only: overwrite existing destinations without confirmation',\n ),\n});\n\nconst MoveFailureItemSchema = pairFailureSchema('moved', 'move');\n\ntype MoveFailureItem = z.infer<typeof MoveFailureItemSchema>;\n\nconst MoveOutputSchema = z.strictObject({\n moves: z.array(MoveItemResultSchema).describe('Successfully completed operations'),\n failures: z\n .array(MoveFailureItemSchema)\n .optional()\n .describe('Operations that failed with per-item error details'),\n skipped: z\n .array(z.string())\n .optional()\n .describe('Destinations skipped because the user chose Skip'),\n});\n\ntype MoveItemResult = z.infer<typeof MoveItemResultSchema>;\n\n/** A move pre-checked up to the point a confirmation decision is needed. */\ninterface MovePlan {\n pair: { source: string; destination: string };\n renamePath: string;\n validDest: string;\n isCaseOnlyRename: boolean;\n /** Whether the destination existed when planned (drives the TOCTOU guard). */\n destExistedOriginally: boolean;\n /** Destination exists and is not a self/case-only move → needs overwrite confirmation. */\n pending: boolean;\n}\n\n/**\n * Phase 1 (no mutation): validate source and destination, reject self-moves and\n * moves into a subdirectory of the source, and stat the destination to decide\n * whether this move needs an overwrite confirmation. No `mkdir` happens here —\n * the old flow created the destination's parent before asking, which mutated\n * the filesystem before a confirmation; that now waits for phase 2 (R14).\n */\nasync function planMove(\n move: { source: string; destination: string },\n fs: ToolCtx['fs'],\n): Promise<PairPlanResult<MovePlan>> {\n let renamePath: string;\n let realPath: string;\n try {\n ({ renamePath, realPath } = await validateMoveSource(move.source, fs));\n } catch (error) {\n return { status: 'fail', failure: pairFailure(move, error) };\n }\n\n let validDest: string;\n try {\n validDest = await fs.pathGuard.validatePathForWrite(move.destination);\n } catch (error) {\n return { status: 'fail', failure: pairFailure(move, error) };\n }\n\n // Comparisons run on the resolved source; only the fs call below uses\n // renamePath. validatePathForWrite resolves the destination through a\n // symlink too, so both sides of every check must be resolved to match.\n const resolvedSource = resolve(realPath);\n const resolvedDest = resolve(validDest);\n\n if (resolvedSource === resolvedDest) {\n // Self-move — silently skip.\n return { status: 'noop' };\n }\n\n const normalizedDest = IS_CASE_INSENSITIVE_FS ? resolvedDest.toLowerCase() : resolvedDest;\n const normalizedSource = IS_CASE_INSENSITIVE_FS\n ? (resolvedSource + sep).toLowerCase()\n : resolvedSource + sep;\n\n if (normalizedDest.startsWith(normalizedSource)) {\n return {\n status: 'fail',\n failure: pairFailure(\n move,\n new FsError(\n ErrorCode.INVALID_INPUT,\n 'Cannot move a directory into its own subdirectory',\n move.source,\n ),\n ),\n };\n }\n\n const isCaseOnlyRename = isSamePath(resolvedSource, resolvedDest);\n const destExistedOriginally = !isCaseOnlyRename && (await destExists(fs, validDest, 'move'));\n\n const pending = !isCaseOnlyRename && destExistedOriginally;\n return {\n status: 'plan',\n plan: { pair: move, renamePath, validDest, isCaseOnlyRename, destExistedOriginally, pending },\n };\n}\n\n/**\n * Phase 2 (mutation): confirm an overwrite if needed, create the destination's\n * parent, TOCTOU-check the destination, then rename (with cross-device fallback).\n * A declined/missing confirmation throws `CANCELLED`, collected as a per-move\n * failure by the caller. A destination that appeared between plan and rename\n * (created during the confirmation gap) also fails closed.\n */\nasync function executeMove(\n plan: MovePlan,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'inputResponses' | 'log'>,\n pendingSorted: readonly string[],\n): Promise<PairExecResult<MoveItemResult>> {\n if (plan.pending) {\n const key = `confirm_${pendingSorted.indexOf(plan.validDest)}`;\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: plan.pair.destination };\n }\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Move cancelled: overwrite of \"${plan.pair.destination}\" was declined or missing`,\n plan.pair.destination,\n );\n }\n }\n\n // TOCTOU check before any mutation: a destination that did not exist when\n // planned but exists now was created during the confirmation gap.\n if (!plan.isCaseOnlyRename) {\n const existsNow = await destExists(ctx.fs, plan.validDest, 'move');\n if (existsNow && !plan.destExistedOriginally) {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Move cancelled: destination \"${plan.pair.destination}\" was created during confirmation.`,\n plan.pair.destination,\n );\n }\n }\n\n await ctx.fs.mkdir(dirname(plan.validDest), { recursive: true });\n\n await performRenameWithFallback(plan.renamePath, plan.validDest, ctx.fs, plan.pair.source);\n ctx.log?.('info', `move: ${plan.pair.source} -> ${plan.pair.destination}`, 'move');\n return { value: { from: plan.renamePath, to: plan.validDest } };\n}\n\n/** A copy pre-checked up to the point a confirmation decision is needed. */\ninterface CopyPlan {\n pair: { source: string; destination: string };\n realSource: string;\n validDest: string;\n destExistedOriginally: boolean;\n pending: boolean;\n}\n\nasync function planCopy(\n copy: { source: string; destination: string },\n fs: ToolCtx['fs'],\n overwrite: boolean,\n): Promise<PairPlanResult<CopyPlan>> {\n let realSource: string;\n try {\n realSource = await fs.pathGuard.validateExistingPath(copy.source);\n } catch (error) {\n return { status: 'fail', failure: pairFailure(copy, error) };\n }\n\n let validDest: string;\n try {\n validDest = await fs.pathGuard.validatePathForWrite(copy.destination);\n } catch (error) {\n return { status: 'fail', failure: pairFailure(copy, error) };\n }\n\n if (isSamePath(realSource, validDest)) {\n // Self-copy — noop\n return { status: 'noop' };\n }\n\n if (isPathInsideDirectory(realSource, validDest)) {\n return {\n status: 'fail',\n failure: pairFailure(\n copy,\n new FsError(\n ErrorCode.INVALID_INPUT,\n 'Cannot copy a directory into its own subdirectory',\n copy.source,\n ),\n ),\n };\n }\n\n const destExistedOriginally = await destExists(fs, validDest, 'copy');\n\n const pending = destExistedOriginally && !overwrite;\n return {\n status: 'plan',\n plan: { pair: copy, realSource, validDest, destExistedOriginally, pending },\n };\n}\n\nasync function executeCopy(\n plan: CopyPlan,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'inputResponses'>,\n pendingSorted: readonly string[],\n overwrite: boolean,\n): Promise<PairExecResult<MoveItemResult>> {\n if (plan.pending && !overwrite) {\n const key = `confirm_${pendingSorted.indexOf(plan.validDest)}`;\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: plan.pair.destination };\n }\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Copy cancelled: overwrite of \"${plan.pair.destination}\" was declined or missing`,\n plan.pair.destination,\n );\n }\n }\n\n // TOCTOU check before any mutation: a destination that did not exist when\n // planned but exists now was created during the confirmation gap.\n if ((await destExists(ctx.fs, plan.validDest, 'copy')) && !plan.destExistedOriginally) {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Copy cancelled: destination \"${plan.pair.destination}\" was created during confirmation.`,\n plan.pair.destination,\n );\n }\n\n await ctx.fs.mkdir(dirname(plan.validDest), { recursive: true });\n\n await ctx.fs.cp(plan.realSource, plan.validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n force: true,\n });\n\n return { value: { from: plan.realSource, to: plan.validDest } };\n}\n\n/**\n * Two-phase move: pre-check every move (no mutation) to build the overwrite\n * pending set; if any move is pending and the round carries no verified\n * `requestState`, return `input_required` moving nothing (R14). On retry, R9\n * checks the state binds this move set, then each pending move proceeds only on\n * an accepted overwrite. Non-pending moves proceed alongside them.\n */\nasync function handleMove(\n args: z.infer<typeof MoveInputSchema>,\n ctx: ToolCtx,\n): Promise<z.infer<typeof MoveOutputSchema> | InputRequiredResult> {\n const outcome = args.copy\n ? await runOverPairs(args.moves, ctx, {\n op: 'copy',\n plan: (pair) => planCopy(pair, ctx.fs, args.overwrite),\n execute: (plan, pendingSorted) => executeCopy(plan, ctx, pendingSorted, args.overwrite),\n })\n : await runOverPairs(args.moves, ctx, {\n op: 'move',\n plan: (move) => planMove(move, ctx.fs),\n execute: (plan, pendingSorted) => executeMove(plan, ctx, pendingSorted),\n });\n if (isInputRequiredResult(outcome)) return outcome;\n\n const { results, skipped, failures } = outcome;\n\n return {\n moves: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n}\n\nfunction buildSummary(\n verb: 'move' | 'copy',\n results: readonly MoveItemResult[],\n failures: readonly MoveFailureItem[],\n skipped: readonly string[] = [],\n): string {\n const successCount = results.length;\n const failCount = failures.length;\n if (failCount === 0 && skipped.length === 0 && successCount === 1) {\n const result = results[0];\n if (result) {\n return `${verb}: ${pathLabel(result.from)} → ${pathLabel(result.to)}`;\n }\n }\n // Name each pair. \"move: 2 items\" left the caller to open structuredContent\n // to learn which two, and a partial failure was unreadable without it.\n // Skipped destinations are an outcome the user chose, not a failure — name\n // them, or an all-skipped call reads as \"copy: nothing\".\n const tokens = [\n ...results.map((r) => `${pathLabel(r.from)} → ${pathLabel(r.to)}`),\n ...skipped.map((dest) => `${pathLabel(dest)} SKIPPED`),\n ];\n const parts = [`${verb}: ${joinRoster(tokens) || 'nothing'}`];\n if (failCount > 0) parts.push(`${String(failCount)} failed`);\n return parts.join(' · ');\n}\n\ninterface MoveSource {\n /** Symlink preserved — the path actually handed to rename/cp/rm. */\n renamePath: string;\n /** Symlink resolved — the identity used for every same-target comparison. */\n realPath: string;\n}\n\n/**\n * A move needs two views of its source. Renaming must operate on the link\n * itself, or moving a symlink would rename the file it points at and leave the\n * link dangling. Every collision check must instead compare the resolved\n * target, or a link moved onto itself (or onto its own target) reads as a real\n * move and renames the link over that target, destroying it.\n */\nasync function validateMoveSource(source: string, fs: ToolCtx['fs']): Promise<MoveSource> {\n try {\n const realPath = await fs.pathGuard.validateExistingPath(source);\n const renamePath = await fs.pathGuard.validatePathForDelete(source);\n return { renamePath, realPath };\n } catch (error) {\n if (isFsError(error)) throw error;\n throw new FsError(ErrorCode.ACCESS_DENIED, `Move failed for ${source}`, source);\n }\n}\n\nasync function performRenameWithFallback(\n validSource: string,\n validDest: string,\n fsOps: Pick<GuardedFileSystem, 'rename' | 'cp' | 'rm'>,\n originalSource: string,\n): Promise<void> {\n try {\n await fsOps.rename(validSource, validDest);\n } catch (error: unknown) {\n rethrowIfAborted(error);\n\n if (!isNodeError(error) || error.code !== 'EXDEV') {\n throw error;\n }\n\n // EXDEV: cross-device rename. Copy then remove, preserving symlinks and\n // timestamps so link semantics survive the move.\n let copied = false;\n try {\n await fsOps.cp(validSource, validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n });\n copied = true;\n await fsOps.rm(validSource, { recursive: true, force: true });\n } catch (copyOrRemoveError) {\n rethrowIfAborted(copyOrRemoveError);\n if (copied) {\n // cp succeeded but rm failed: the destination already holds a complete\n // copy and the source remains. Surface the rm error as the cause so the\n // caller can recover (clean up the duplicate) instead of a silent generic\n // failure that hides the partial completion.\n const baseProblem = Problem.fromUnknown(\n copyOrRemoveError,\n ErrorCode.UNKNOWN,\n originalSource,\n );\n throw new FsError(\n baseProblem.code,\n `Cross-device move of ${originalSource}: copy succeeded but source removal failed (destination holds a copy): ${baseProblem.message}`,\n originalSource,\n undefined,\n copyOrRemoveError,\n );\n }\n throw copyOrRemoveError;\n }\n }\n}\n\nexport const MOVE = defineTool({\n name: 'move',\n title: 'Move or Copy Files',\n description:\n 'Move, rename, or copy files and directories to explicit destination paths (max 100 operations per call). ' +\n 'Pass moves: [{ source, destination }] — there is no single-pair form. ' +\n 'Parent directories are created automatically. Set copy=true to copy instead of move (sources are kept). ' +\n 'An existing destination prompts the user to confirm the overwrite, so the call returns without moving ' +\n 'anything until that confirmation comes back; copy=true with overwrite=true skips the prompt, move has no ' +\n 'such bypass. Self-moves are silently skipped.',\n input: MoveInputSchema,\n output: MoveOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n progress: (args) => {\n const label = args.copy ? 'Copy' : 'Move';\n if (args.moves.length === 1) {\n const move = args.moves[0];\n return {\n label,\n subject: `${basename(move?.source ?? '')} → ${basename(move?.destination ?? '')}`,\n };\n }\n return { label, subject: `${String(args.moves.length)} files` };\n },\n defaultErrorCode: ErrorCode.UNKNOWN,\n accessPaths: (args) => args.moves.flatMap((m) => [m.source, m.destination]),\n run: async (args, ctx) => {\n const output = await handleMove(args, ctx);\n // input_required is a return value, not a completed call: surface it\n // verbatim so the executor short-circuits before building a CallToolResult.\n if (isInputRequiredResult(output)) return output;\n return {\n structured: output,\n text: buildSummary(\n args.copy ? 'copy' : 'move',\n output.moves,\n output.failures ?? [],\n output.skipped ?? [],\n ),\n };\n },\n});\n"]}
1
+ {"version":3,"file":"move.js","sourceRoot":"","sources":["../../src/tools/move.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAE5D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,WAAW,EACX,OAAO,EACP,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,kBAAkB,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C,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC;YAChF,OAAO,EAAE,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;SACtE,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { InputRequiredResult } from '@modelcontextprotocol/server';\nimport { isInputRequiredResult } from '@modelcontextprotocol/server';\n\nimport { basename, dirname, resolve, sep } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n Problem,\n rethrowIfAborted,\n} from '../core/errors.js';\nimport { joinRoster, pathLabel } from '../core/fmt.js';\nimport { destExists } from '../core/fs.js';\nimport type { GuardedFileSystem } from '../core/fs.js';\nimport { readAcceptedChoice } from '../core/input-required.js';\nimport { IS_CASE_INSENSITIVE_FS, isPathInsideDirectory, isSamePath } from '../core/path-utils.js';\nimport { defaultFalseBoolean, pairFailureSchema, RequiredPath } from '../core/schema.js';\nimport type { PairExecResult, PairPlanResult } from './batch.js';\nimport { isTotalFailure, pairFailure, runOverPairs } from './batch.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst MoveItemSchema = z.strictObject({\n source: RequiredPath.describe('Path of the file or directory to move or copy'),\n destination: RequiredPath.describe('Destination path'),\n});\n\nconst MoveItemResultSchema = z.strictObject({\n from: z.string().describe('Resolved absolute source path'),\n to: z.string().describe('Resolved absolute destination path'),\n});\n\nconst MoveInputSchema = z.strictObject({\n moves: z.array(MoveItemSchema).min(1).max(100).describe('Operations to perform (max 100)'),\n copy: defaultFalseBoolean('Copy instead of move; sources are left in place'),\n overwrite: defaultFalseBoolean(\n 'Copy mode only: overwrite existing destinations without confirmation',\n ),\n});\n\nconst MoveFailureItemSchema = pairFailureSchema('moved', 'move');\n\ntype MoveFailureItem = z.infer<typeof MoveFailureItemSchema>;\n\nconst MoveOutputSchema = z.strictObject({\n moves: z.array(MoveItemResultSchema).describe('Successfully completed operations'),\n failures: z\n .array(MoveFailureItemSchema)\n .optional()\n .describe('Operations that failed with per-item error details'),\n skipped: z\n .array(z.string())\n .optional()\n .describe('Destinations skipped because the user chose Skip'),\n});\n\ntype MoveItemResult = z.infer<typeof MoveItemResultSchema>;\n\n/** A move pre-checked up to the point a confirmation decision is needed. */\ninterface MovePlan {\n pair: { source: string; destination: string };\n renamePath: string;\n validDest: string;\n isCaseOnlyRename: boolean;\n /** Whether the destination existed when planned (drives the TOCTOU guard). */\n destExistedOriginally: boolean;\n /** Destination exists and is not a self/case-only move → needs overwrite confirmation. */\n pending: boolean;\n}\n\n/**\n * Phase 1 (no mutation): validate source and destination, reject self-moves and\n * moves into a subdirectory of the source, and stat the destination to decide\n * whether this move needs an overwrite confirmation. No `mkdir` happens here —\n * the old flow created the destination's parent before asking, which mutated\n * the filesystem before a confirmation; that now waits for phase 2 (R14).\n */\nasync function planMove(\n move: { source: string; destination: string },\n fs: ToolCtx['fs'],\n): Promise<PairPlanResult<MovePlan>> {\n let renamePath: string;\n let realPath: string;\n try {\n ({ renamePath, realPath } = await validateMoveSource(move.source, fs));\n } catch (error) {\n return { status: 'fail', failure: pairFailure(move, error) };\n }\n\n let validDest: string;\n try {\n validDest = await fs.pathGuard.validatePathForWrite(move.destination);\n } catch (error) {\n return { status: 'fail', failure: pairFailure(move, error) };\n }\n\n // Comparisons run on the resolved source; only the fs call below uses\n // renamePath. validatePathForWrite resolves the destination through a\n // symlink too, so both sides of every check must be resolved to match.\n const resolvedSource = resolve(realPath);\n const resolvedDest = resolve(validDest);\n\n if (resolvedSource === resolvedDest) {\n // Self-move — silently skip.\n return { status: 'noop' };\n }\n\n const normalizedDest = IS_CASE_INSENSITIVE_FS ? resolvedDest.toLowerCase() : resolvedDest;\n const normalizedSource = IS_CASE_INSENSITIVE_FS\n ? (resolvedSource + sep).toLowerCase()\n : resolvedSource + sep;\n\n if (normalizedDest.startsWith(normalizedSource)) {\n return {\n status: 'fail',\n failure: pairFailure(\n move,\n new FsError(\n ErrorCode.INVALID_INPUT,\n 'Cannot move a directory into its own subdirectory',\n move.source,\n ),\n ),\n };\n }\n\n const isCaseOnlyRename = isSamePath(resolvedSource, resolvedDest);\n const destExistedOriginally = !isCaseOnlyRename && (await destExists(fs, validDest, 'move'));\n\n const pending = !isCaseOnlyRename && destExistedOriginally;\n return {\n status: 'plan',\n plan: { pair: move, renamePath, validDest, isCaseOnlyRename, destExistedOriginally, pending },\n };\n}\n\n/**\n * Phase 2 (mutation): confirm an overwrite if needed, create the destination's\n * parent, TOCTOU-check the destination, then rename (with cross-device fallback).\n * A declined/missing confirmation throws `CANCELLED`, collected as a per-move\n * failure by the caller. A destination that appeared between plan and rename\n * (created during the confirmation gap) also fails closed.\n */\nasync function executeMove(\n plan: MovePlan,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'inputResponses' | 'log'>,\n pendingSorted: readonly string[],\n): Promise<PairExecResult<MoveItemResult>> {\n if (plan.pending) {\n const key = `confirm_${pendingSorted.indexOf(plan.validDest)}`;\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: plan.pair.destination };\n }\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Move cancelled: overwrite of \"${plan.pair.destination}\" was declined or missing`,\n plan.pair.destination,\n );\n }\n }\n\n // TOCTOU check before any mutation: a destination that did not exist when\n // planned but exists now was created during the confirmation gap.\n if (!plan.isCaseOnlyRename) {\n const existsNow = await destExists(ctx.fs, plan.validDest, 'move');\n if (existsNow && !plan.destExistedOriginally) {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Move cancelled: destination \"${plan.pair.destination}\" was created during confirmation.`,\n plan.pair.destination,\n );\n }\n }\n\n await ctx.fs.mkdir(dirname(plan.validDest), { recursive: true });\n\n await performRenameWithFallback(plan.renamePath, plan.validDest, ctx.fs, plan.pair.source);\n ctx.log?.('info', `move: ${plan.pair.source} -> ${plan.pair.destination}`, 'move');\n return { value: { from: plan.renamePath, to: plan.validDest } };\n}\n\n/** A copy pre-checked up to the point a confirmation decision is needed. */\ninterface CopyPlan {\n pair: { source: string; destination: string };\n realSource: string;\n validDest: string;\n destExistedOriginally: boolean;\n pending: boolean;\n}\n\nasync function planCopy(\n copy: { source: string; destination: string },\n fs: ToolCtx['fs'],\n overwrite: boolean,\n): Promise<PairPlanResult<CopyPlan>> {\n let realSource: string;\n try {\n realSource = await fs.pathGuard.validateExistingPath(copy.source);\n } catch (error) {\n return { status: 'fail', failure: pairFailure(copy, error) };\n }\n\n let validDest: string;\n try {\n validDest = await fs.pathGuard.validatePathForWrite(copy.destination);\n } catch (error) {\n return { status: 'fail', failure: pairFailure(copy, error) };\n }\n\n if (isSamePath(realSource, validDest)) {\n // Self-copy — noop\n return { status: 'noop' };\n }\n\n if (isPathInsideDirectory(realSource, validDest)) {\n return {\n status: 'fail',\n failure: pairFailure(\n copy,\n new FsError(\n ErrorCode.INVALID_INPUT,\n 'Cannot copy a directory into its own subdirectory',\n copy.source,\n ),\n ),\n };\n }\n\n const destExistedOriginally = await destExists(fs, validDest, 'copy');\n\n const pending = destExistedOriginally && !overwrite;\n return {\n status: 'plan',\n plan: { pair: copy, realSource, validDest, destExistedOriginally, pending },\n };\n}\n\nasync function executeCopy(\n plan: CopyPlan,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'inputResponses'>,\n pendingSorted: readonly string[],\n overwrite: boolean,\n): Promise<PairExecResult<MoveItemResult>> {\n if (plan.pending && !overwrite) {\n const key = `confirm_${pendingSorted.indexOf(plan.validDest)}`;\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: plan.pair.destination };\n }\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Copy cancelled: overwrite of \"${plan.pair.destination}\" was declined or missing`,\n plan.pair.destination,\n );\n }\n }\n\n // TOCTOU check before any mutation: a destination that did not exist when\n // planned but exists now was created during the confirmation gap.\n if ((await destExists(ctx.fs, plan.validDest, 'copy')) && !plan.destExistedOriginally) {\n throw new FsError(\n ErrorCode.CANCELLED,\n `Copy cancelled: destination \"${plan.pair.destination}\" was created during confirmation.`,\n plan.pair.destination,\n );\n }\n\n await ctx.fs.mkdir(dirname(plan.validDest), { recursive: true });\n\n await ctx.fs.cp(plan.realSource, plan.validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n force: true,\n });\n\n return { value: { from: plan.realSource, to: plan.validDest } };\n}\n\n/**\n * Two-phase move: pre-check every move (no mutation) to build the overwrite\n * pending set; if any move is pending and the round carries no verified\n * `requestState`, return `input_required` moving nothing (R14). On retry, R9\n * checks the state binds this move set, then each pending move proceeds only on\n * an accepted overwrite. Non-pending moves proceed alongside them.\n */\nasync function handleMove(\n args: z.infer<typeof MoveInputSchema>,\n ctx: ToolCtx,\n): Promise<z.infer<typeof MoveOutputSchema> | InputRequiredResult> {\n const outcome = args.copy\n ? await runOverPairs(args.moves, ctx, {\n op: 'copy',\n plan: (pair) => planCopy(pair, ctx.fs, args.overwrite),\n execute: (plan, pendingSorted) => executeCopy(plan, ctx, pendingSorted, args.overwrite),\n })\n : await runOverPairs(args.moves, ctx, {\n op: 'move',\n plan: (move) => planMove(move, ctx.fs),\n execute: (plan, pendingSorted) => executeMove(plan, ctx, pendingSorted),\n });\n if (isInputRequiredResult(outcome)) return outcome;\n\n const { results, skipped, failures } = outcome;\n\n return {\n moves: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n}\n\nfunction buildSummary(\n verb: 'move' | 'copy',\n results: readonly MoveItemResult[],\n failures: readonly MoveFailureItem[],\n skipped: readonly string[] = [],\n): string {\n const successCount = results.length;\n const failCount = failures.length;\n if (failCount === 0 && skipped.length === 0 && successCount === 1) {\n const result = results[0];\n if (result) {\n return `${verb}: ${pathLabel(result.from)} → ${pathLabel(result.to)}`;\n }\n }\n // Name each pair. \"move: 2 items\" left the caller to open structuredContent\n // to learn which two, and a partial failure was unreadable without it.\n // Skipped destinations are an outcome the user chose, not a failure — name\n // them, or an all-skipped call reads as \"copy: nothing\".\n const tokens = [\n ...results.map((r) => `${pathLabel(r.from)} → ${pathLabel(r.to)}`),\n ...skipped.map((dest) => `${pathLabel(dest)} SKIPPED`),\n ];\n const parts = [`${verb}: ${joinRoster(tokens) || 'nothing'}`];\n if (failCount > 0) parts.push(`${String(failCount)} failed`);\n return parts.join(' · ');\n}\n\ninterface MoveSource {\n /** Symlink preserved — the path actually handed to rename/cp/rm. */\n renamePath: string;\n /** Symlink resolved — the identity used for every same-target comparison. */\n realPath: string;\n}\n\n/**\n * A move needs two views of its source. Renaming must operate on the link\n * itself, or moving a symlink would rename the file it points at and leave the\n * link dangling. Every collision check must instead compare the resolved\n * target, or a link moved onto itself (or onto its own target) reads as a real\n * move and renames the link over that target, destroying it.\n */\nasync function validateMoveSource(source: string, fs: ToolCtx['fs']): Promise<MoveSource> {\n try {\n const realPath = await fs.pathGuard.validateExistingPath(source);\n const renamePath = await fs.pathGuard.validatePathForDelete(source);\n return { renamePath, realPath };\n } catch (error) {\n if (isFsError(error)) throw error;\n throw new FsError(ErrorCode.ACCESS_DENIED, `Move failed for ${source}`, source);\n }\n}\n\nasync function performRenameWithFallback(\n validSource: string,\n validDest: string,\n fsOps: Pick<GuardedFileSystem, 'rename' | 'cp' | 'rm'>,\n originalSource: string,\n): Promise<void> {\n try {\n await fsOps.rename(validSource, validDest);\n } catch (error: unknown) {\n rethrowIfAborted(error);\n\n if (!isNodeError(error) || error.code !== 'EXDEV') {\n throw error;\n }\n\n // EXDEV: cross-device rename. Copy then remove, preserving symlinks and\n // timestamps so link semantics survive the move.\n let copied = false;\n try {\n await fsOps.cp(validSource, validDest, {\n recursive: true,\n verbatimSymlinks: true,\n preserveTimestamps: true,\n });\n copied = true;\n await fsOps.rm(validSource, { recursive: true, force: true });\n } catch (copyOrRemoveError) {\n rethrowIfAborted(copyOrRemoveError);\n if (copied) {\n // cp succeeded but rm failed: the destination already holds a complete\n // copy and the source remains. Surface the rm error as the cause so the\n // caller can recover (clean up the duplicate) instead of a silent generic\n // failure that hides the partial completion.\n const baseProblem = Problem.fromUnknown(\n copyOrRemoveError,\n ErrorCode.UNKNOWN,\n originalSource,\n );\n throw new FsError(\n baseProblem.code,\n `Cross-device move of ${originalSource}: copy succeeded but source removal failed (destination holds a copy): ${baseProblem.message}`,\n originalSource,\n undefined,\n copyOrRemoveError,\n );\n }\n throw copyOrRemoveError;\n }\n }\n}\n\nexport const MOVE = defineTool({\n name: 'move',\n title: 'Move or Copy Files',\n description:\n 'Move, rename, or copy files and directories to explicit destination paths (max 100 operations per call). ' +\n 'Pass moves: [{ source, destination }] — there is no single-pair form. ' +\n 'Parent directories are created automatically. Set copy=true to copy instead of move (sources are kept). ' +\n 'An existing destination prompts the user to confirm the overwrite, so the call returns without moving ' +\n 'anything until that confirmation comes back; copy=true with overwrite=true skips the prompt, move has no ' +\n 'such bypass. Self-moves are silently skipped.',\n input: MoveInputSchema,\n output: MoveOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n progress: (args) => {\n const label = args.copy ? 'Copy' : 'Move';\n if (args.moves.length === 1) {\n const move = args.moves[0];\n return {\n label,\n subject: `${basename(move?.source ?? '')} → ${basename(move?.destination ?? '')}`,\n };\n }\n return { label, subject: `${String(args.moves.length)} files` };\n },\n defaultErrorCode: ErrorCode.UNKNOWN,\n accessPaths: (args) => args.moves.flatMap((m) => [m.source, m.destination]),\n run: async (args, ctx) => {\n const output = await handleMove(args, ctx);\n // input_required is a return value, not a completed call: surface it\n // verbatim so the executor short-circuits before building a CallToolResult.\n if (isInputRequiredResult(output)) return output;\n const failures = output.failures ?? [];\n const skipped = output.skipped ?? [];\n return {\n structured: output,\n text: buildSummary(args.copy ? 'copy' : 'move', output.moves, failures, skipped),\n isError: isTotalFailure({ results: output.moves, skipped, failures }),\n };\n },\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAsZA,eAAO,MAAM,SAAS,mCAuKpB,CAAC"}
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAsZA,eAAO,MAAM,SAAS,mCAwKpB,CAAC"}
@@ -8,7 +8,7 @@ import { detectMimeFromContent, detectMimeType } from '../core/mime.js';
8
8
  import { readFileWithStats } from '../core/read.js';
9
9
  import { ContinuationSchema, createReadRangeFields, defaultFalseBoolean, FileKind, NonNegInt, OperationSummarySchema, PerFileErrorSchema, PositiveInt, Sha256Hex, singleOrBatchAccessPaths, singleOrBatchPathsInput, validateReadRange, } from '../core/schema.js';
10
10
  import { DEFAULT_CONTINUATION_CHUNK_SIZE, DEFAULT_SEARCH_TIMEOUT_MS, getDefaultReadManyMaxTotalSize, getMaxTextFileSize, PARALLEL_CONCURRENCY, } from '../core/util.js';
11
- import { runOverPaths } from './batch.js';
11
+ import { isTotalFailure, runOverPaths } from './batch.js';
12
12
  import { defineTool } from './define.js';
13
13
  const readRangeFields = createReadRangeFields({
14
14
  head: 'Return first N lines',
@@ -434,6 +434,7 @@ export const READ_FILE = defineTool({
434
434
  return {
435
435
  structured: { results: structuredResults, summary },
436
436
  text,
437
+ isError: isTotalFailure(summary),
437
438
  ...(resources.length > 0 ? { resources } : {}),
438
439
  };
439
440
  },