@j0hanz/filesystem-mcp 2.7.6 → 2.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.ts +1 -9
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/core/cursor.d.ts +8 -0
- package/dist/core/cursor.d.ts.map +1 -1
- package/dist/core/cursor.js +14 -0
- package/dist/core/cursor.js.map +1 -1
- package/dist/core/errors.d.ts +4 -3
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +5 -16
- package/dist/core/errors.js.map +1 -1
- package/dist/core/fs.d.ts +11 -11
- package/dist/core/fs.d.ts.map +1 -1
- package/dist/core/fs.js +172 -83
- package/dist/core/fs.js.map +1 -1
- package/dist/core/glob.d.ts +8 -0
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +192 -29
- package/dist/core/glob.js.map +1 -1
- package/dist/core/input-required.d.ts +19 -0
- package/dist/core/input-required.d.ts.map +1 -1
- package/dist/core/input-required.js +20 -2
- package/dist/core/input-required.js.map +1 -1
- package/dist/core/observability.d.ts +2 -0
- package/dist/core/observability.d.ts.map +1 -1
- package/dist/core/observability.js +7 -0
- package/dist/core/observability.js.map +1 -1
- package/dist/core/path-completer.d.ts.map +1 -1
- package/dist/core/path-completer.js +11 -30
- package/dist/core/path-completer.js.map +1 -1
- package/dist/core/path-utils.d.ts +9 -6
- package/dist/core/path-utils.d.ts.map +1 -1
- package/dist/core/path-utils.js +13 -19
- package/dist/core/path-utils.js.map +1 -1
- package/dist/core/path.d.ts +1 -20
- package/dist/core/path.d.ts.map +1 -1
- package/dist/core/path.js +17 -69
- package/dist/core/path.js.map +1 -1
- package/dist/core/read.d.ts +7 -3
- package/dist/core/read.d.ts.map +1 -1
- package/dist/core/read.js +32 -50
- package/dist/core/read.js.map +1 -1
- package/dist/core/schema.d.ts +6 -1
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +17 -3
- package/dist/core/schema.js.map +1 -1
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +104 -51
- package/dist/core/search.js.map +1 -1
- package/dist/core/sensitive.d.ts.map +1 -1
- package/dist/core/sensitive.js +7 -14
- package/dist/core/sensitive.js.map +1 -1
- package/dist/core/store.d.ts +36 -1
- package/dist/core/store.d.ts.map +1 -1
- package/dist/core/store.js +71 -6
- package/dist/core/store.js.map +1 -1
- package/dist/core/util.d.ts +40 -5
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +75 -5
- package/dist/core/util.js.map +1 -1
- package/dist/index.js +5 -16
- package/dist/index.js.map +1 -1
- package/dist/prompts.d.ts +1 -1
- package/dist/prompts.d.ts.map +1 -1
- package/dist/prompts.js +1 -1
- package/dist/prompts.js.map +1 -1
- package/dist/resources.d.ts +6 -3
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +46 -25
- package/dist/resources.js.map +1 -1
- package/dist/server.d.ts +9 -6
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +8 -9
- package/dist/server.js.map +1 -1
- package/dist/tools/create.d.ts.map +1 -1
- package/dist/tools/create.js +13 -25
- package/dist/tools/create.js.map +1 -1
- package/dist/tools/define.d.ts +8 -7
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +48 -16
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete.d.ts.map +1 -1
- package/dist/tools/delete.js +46 -27
- package/dist/tools/delete.js.map +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +24 -39
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/find-files.d.ts.map +1 -1
- package/dist/tools/find-files.js +45 -62
- package/dist/tools/find-files.js.map +1 -1
- package/dist/tools/index.d.ts +3 -12
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -10
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +81 -74
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/move.d.ts.map +1 -1
- package/dist/tools/move.js +17 -14
- package/dist/tools/move.js.map +1 -1
- package/dist/tools/patch.d.ts.map +1 -1
- package/dist/tools/patch.js +3 -6
- package/dist/tools/patch.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +31 -40
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-text.d.ts.map +1 -1
- package/dist/tools/replace-text.js +24 -33
- package/dist/tools/replace-text.js.map +1 -1
- package/dist/tools/search-text.d.ts.map +1 -1
- package/dist/tools/search-text.js +42 -69
- package/dist/tools/search-text.js.map +1 -1
- package/dist/transport/http-policy.d.ts +3 -2
- package/dist/transport/http-policy.d.ts.map +1 -1
- package/dist/transport/http-policy.js +3 -2
- package/dist/transport/http-policy.js.map +1 -1
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +2 -3
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/shared.d.ts +7 -5
- package/dist/transport/shared.d.ts.map +1 -1
- package/dist/transport/shared.js +8 -2
- package/dist/transport/shared.js.map +1 -1
- package/dist/transport/stdio.d.ts +4 -1
- package/dist/transport/stdio.d.ts.map +1 -1
- package/dist/transport/stdio.js +45 -12
- package/dist/transport/stdio.js.map +1 -1
- package/package.json +3 -2
package/dist/tools/create.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/tools/create.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,SAAS,EACT,yBAAyB,EACzB,OAAO,EAEP,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,o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E,CAAC;IACnD,CAAC;SAAM,CAAC;QACN,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE;YACpD,MAAM,EAAE,GAAG,CAAC,MAAM;SACnB,CAAC,CAAC;QACH,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QAC9B,MAAM,SAAS,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;QAC1E,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;QAC5C,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;QACzC,IAAI,GAAG,oBAAoB,CAAC;YAC1B,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,OAAO;YACP,YAAY,EAAE,QAAQ;SACvB,CAAC,CAAC;IACL,CAAC;IAED,MAAM,IAAI,GAAqB;QAC7B,IAAI,EAAE,SAAS;QACf,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,OAAO;QACP,QAAQ;KACT,CAAC;IAEF,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;AAClF,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename, dirname } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.ts';\nimport {\n ErrorCode,\n formatUnknownErrorMessage,\n FsError,\n type Problem,\n rethrowIfAborted,\n} from '../core/errors.ts';\nimport { buildWrittenFileMeta, writtenFileLinks, type WrittenFileMeta } from '../core/file-uri.ts';\nimport { countFileLines, destExists, type Stats } from '../core/fs.ts';\nimport {\n confirmKey,\n describeRefusal,\n pendingRoundTrip,\n readAcceptedChoice,\n} from '../core/input-required.ts';\nimport { detectMimeFromContent, type FileKind, MIME_SAMPLE_SIZE } from '../core/mime.ts';\nimport { isSamePath } from '../core/path-utils.ts';\nimport { RequiredPath } from '../core/schema.ts';\nimport { getMaxTextFileSize, PARALLEL_CONCURRENCY } from '../core/util.ts';\nimport { isTotalFailure, runOverPaths } from './batch.ts';\nimport { defineTool, type ToolCtx } from './define.ts';\n\nconst EPOCH = new Date(0);\n\nconst CreateFileItemSchema = z.strictObject({\n path: RequiredPath.describe('Absolute path where the file will be created'),\n content: z\n .string()\n .refine((val) => val.length <= getMaxTextFileSize(), {\n message: 'Content exceeds maximum allowed text file size',\n })\n .describe('Text content to write, verbatim.'),\n append: z\n .boolean()\n .optional()\n .describe(\n 'Append the content to the end of the file instead of overwriting; creates the file if it does not exist',\n ),\n overwrite: z\n .boolean()\n .optional()\n .describe(\n 'Replace an existing file without asking the user; without it an existing file prompts for confirmation',\n ),\n});\n\ntype CreateFileResult = Omit<WrittenFileMeta, 'resourceLink'> & {\n path: string;\n created: string;\n modified: string;\n};\n\nconst CreateInputSchema = z\n .strictObject({\n files: z\n .array(CreateFileItemSchema)\n .min(1)\n .max(100)\n .describe(\n 'List of files to create (max 100); each entry requires path and content; combined content is capped at the file-size limit',\n ),\n })\n .superRefine((value, ctx) => {\n // Entries write in parallel and each replaces its file whole, so two\n // entries for one path race: the last rename wins and the other's\n // content is lost while both report success. One entry per file.\n for (const [index, file] of value.files.entries()) {\n const first = value.files.findIndex((other) => isSamePath(other.path, file.path));\n if (first < index) {\n ctx.addIssue({\n code: 'custom',\n path: ['files', index, 'path'],\n message: `duplicate of files[${String(first)}].path; one entry per file`,\n input: value,\n });\n }\n }\n // One call's content is what one inbound message carries; the transports\n // size their message bound from this same limit (getMaxInboundMessageBytes),\n // so a batch that passes here always fits on the wire. Counted in the same\n // UTF-16 units as the per-file refine above.\n const total = value.files.reduce((sum, file) => sum + file.content.length, 0);\n const limit = getMaxTextFileSize();\n if (total > limit) {\n ctx.addIssue({\n code: 'custom',\n path: ['files'],\n message: `combined content is ${String(total)} characters; one create call carries at most ${String(limit)} (FS_MAX_FILE_SIZE). Split the batch.`,\n input: value,\n });\n }\n });\n\ninterface CreateFailureItem {\n path: string;\n error: Problem;\n}\n\ninterface CreateOutput {\n files: CreateFileResult[];\n failures?: CreateFailureItem[];\n skipped?: string[];\n}\n\nexport const CREATE = defineTool<typeof CreateInputSchema, CreateOutput>({\n name: 'create',\n title: 'Create Files',\n description:\n 'Write whole text files: create new ones, overwrite, or append. Missing parent directories are created. ' +\n 'edit or patch changes part of an existing file.',\n input: CreateInputSchema,\n readOnlyHint: false,\n accessPaths: (args) => args.files.map((f) => f.path),\n run: async (args, ctx) => {\n // Phase 1 (no mutation): which entries would replace a file that exists\n // right now? Those need the user's word before anything is written (R14).\n // append never destroys, and overwrite: true is that word given up front.\n // A path that fails validation here is left for runOverPaths to report.\n // A file that appears between rounds needs no re-stat before the write:\n // the retry re-plans, and the grown pending set fails the R9 check.\n const { results: planned } = await processInParallel(\n args.files,\n async (entry) => {\n if (entry.append || entry.overwrite) return undefined;\n try {\n const validPath = await ctx.fs.pathGuard.validatePathForWrite(entry.path);\n return (await destExists(ctx.fs, validPath, 'create')) ? validPath : undefined;\n } catch (error) {\n rethrowIfAborted(error);\n return undefined;\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n const pendingByPath = new Map<string, string>();\n for (const { index, value } of planned) {\n const requested = args.files[index]?.path;\n if (value && requested) pendingByPath.set(requested, value);\n }\n const pendingSorted = [...new Set(pendingByPath.values())].sort();\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required; a retry whose verified state does not\n // bind this overwrite set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip(ctx, {\n op: 'create',\n pending: pendingSorted,\n buildInputs: (paths) =>\n paths.map((target, i) => ({\n key: confirmKey(i),\n message: `\"${target}\" already exists. Overwrite it?`,\n choices: ['overwrite', 'skip'],\n })),\n });\n if (round !== undefined) return round;\n }\n\n const batch = await runOverPaths<\n z.infer<typeof CreateFileItemSchema>,\n { file: CreateFileResult; resourceLink?: ContentBlock } | { skipped: string }\n >(args.files, ctx, ErrorCode.UNKNOWN, async ({ path, content, append, overwrite }) => {\n const pendingPath = pendingByPath.get(path);\n if (pendingPath !== undefined) {\n const key = confirmKey(pendingSorted.indexOf(pendingPath));\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') return { skipped: path };\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `create cancelled: overwrite of \"${path}\" was ${describeRefusal(ctx, key)}`,\n path,\n );\n }\n }\n\n // Lock per resolved file so two entries naming one file (e.g. through a\n // symlinked parent) cannot clobber each other.\n return ctx.fs.lockForWrite(path, async (resolvedTarget) => {\n // The file may have appeared since the overwrite set was planned.\n if (\n !append &&\n !overwrite &&\n pendingPath === undefined &&\n (await destExists(ctx.fs, resolvedTarget, 'create'))\n ) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `create refused: \"${path}\" appeared after overwrite confirmation was checked`,\n path,\n );\n }\n return createOne(path, content, append, ctx);\n });\n });\n\n const results: CreateFileResult[] = [];\n const failures: CreateFailureItem[] = [];\n const skipped: string[] = [];\n const links: ContentBlock[] = [];\n for (const r of batch.results) {\n if ('error' in r) {\n failures.push({ path: r.path, error: r.error });\n continue;\n }\n if ('skipped' in r.value) {\n skipped.push(r.value.skipped);\n continue;\n }\n results.push(r.value.file);\n if (r.value.resourceLink) links.push(r.value.resourceLink);\n }\n\n const structured = {\n files: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n // No `text` on purpose. The one-line roster this used to build named the\n // paths and dropped every per-file size, line count and error the caller\n // asked `create` for. Supplying no text makes this a data tool, so\n // `define.ts` renders the JSON and keeps it in `structuredContent`.\n if (links.length > 0) {\n return { structured, resources: links, isError: isTotalFailure(batch.summary) };\n }\n\n return { structured, isError: isTotalFailure(batch.summary) };\n },\n progress: (args) => ({\n label: 'Create',\n subject:\n args.files.length === 1\n ? basename(args.files[0]?.path ?? '')\n : `${String(args.files.length)} files`,\n }),\n});\n\nasync function createOne(\n path: string,\n content: string,\n append: boolean | undefined,\n ctx: ToolCtx,\n): Promise<{ file: CreateFileResult; resourceLink?: ContentBlock }> {\n await ctx.fs.mkdir(dirname(path), { recursive: true });\n\n // Overwrite: file content == `content`, so content-derived meta is\n // exact and the atomic temp+rename write protects the existing mode.\n // Append: the resulting file is everything that was there plus\n // `content`, so size/created/modified come from a real post-append\n // stat, MIME from the resulting file's leading bytes, and the line\n // count streams the file — reading a multi-GB log back whole is the\n // round-trip append exists to avoid.\n let validPath: string;\n let meta: WrittenFileMeta;\n let created: string;\n let modified: string;\n if (append) {\n const appended = await ctx.fs.appendFile(path, content, {\n signal: ctx.signal,\n });\n validPath = appended.validPath;\n // The append is the commit point: the bytes are on disk, so\n // everything below is best-effort RESULT METADATA, not part of the\n // write. It runs unwired to ctx.signal, and a metadata failure\n // degrades the result instead of failing it — either would report\n // the append as failed and a client retry would append twice. The\n // stat covers the committed validPath, never the input path: a\n // symlink there could have been swapped between write and stat,\n // and the result must describe the file the bytes landed in.\n let stats: Stats | undefined;\n let mimeType: string;\n let kind: FileKind;\n let lineCount = 0;\n try {\n stats = (await ctx.fs.stat(appended.validPath)).stats;\n // Sniff the resulting file's leading bytes, not the appended\n // chunk: text appended to a binary file is still a binary file.\n const sample = await ctx.fs.readLeadingSample(appended.validPath, MIME_SAMPLE_SIZE);\n const mimeInfo = detectMimeFromContent(appended.validPath, sample);\n mimeType = mimeInfo.mimeType;\n kind = mimeInfo.kind;\n lineCount = await countFileLines(appended.validPath);\n } catch (error) {\n ctx.log(\n 'warning',\n `create append: result metadata degraded for ${appended.validPath}: ${formatUnknownErrorMessage(error)}`,\n 'create',\n );\n // A POSIX mode-0222 file appends fine but cannot be opened 'r';\n // fall back to the chunk for MIME (an approximation) and report\n // the line count as unknown-as-zero rather than fail the append.\n const mimeInfo = detectMimeFromContent(appended.validPath, content);\n mimeType = mimeInfo.mimeType;\n kind = mimeInfo.kind;\n }\n // A failed stat leaves the size unknown, so nothing is advertised.\n meta = {\n size: stats?.size ?? 0,\n lineCount,\n mimeType,\n kind,\n ...writtenFileLinks(\n appended.validPath,\n mimeType,\n stats?.size,\n false,\n stats?.mtime.toISOString(),\n ),\n };\n created = (stats?.birthtime ?? EPOCH).toISOString();\n modified = (stats?.mtime ?? EPOCH).toISOString();\n } else {\n const written = await ctx.fs.writeFile(path, content, {\n signal: ctx.signal,\n });\n validPath = written.validPath;\n const fileStats = (await ctx.fs.stat(path, { signal: ctx.signal })).stats;\n created = fileStats.birthtime.toISOString();\n modified = fileStats.mtime.toISOString();\n meta = buildWrittenFileMeta({\n validPath: written.validPath,\n content,\n lastModified: modified,\n });\n }\n\n const file: CreateFileResult = {\n path: validPath,\n size: meta.size,\n lineCount: meta.lineCount,\n mimeType: meta.mimeType,\n kind: meta.kind,\n resourceUri: meta.resourceUri,\n created,\n modified,\n };\n\n return meta.resourceLink ? { file, resourceLink: meta.resourceLink } : { file };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/tools/create.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,SAAS,EACT,yBAAyB,EACzB,OAAO,EAEP,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAw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E,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;QAC1E,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;QAC5C,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;QACzC,IAAI,GAAG,oBAAoB,CAAC;YAC1B,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,OAAO;YACP,YAAY,EAAE,QAAQ;SACvB,CAAC,CAAC;IACL,CAAC;IAED,MAAM,EAAE,YAAY,EAAE,GAAG,QAAQ,EAAE,GAAG,IAAI,CAAC;IAC3C,MAAM,IAAI,GAAqB,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IAEnF,OAAO,YAAY,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;AAC1D,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename, dirname } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.ts';\nimport {\n ErrorCode,\n formatUnknownErrorMessage,\n FsError,\n type Problem,\n rethrowIfAborted,\n} from '../core/errors.ts';\nimport { buildWrittenFileMeta, writtenFileLinks, type WrittenFileMeta } from '../core/file-uri.ts';\nimport { destExists, type Stats } from '../core/fs.ts';\nimport { confirmKey, pendingRoundTrip, readPendingVerdict } from '../core/input-required.ts';\nimport { detectMimeFromContent, type FileKind } from '../core/mime.ts';\nimport { isSamePath } from '../core/path-utils.ts';\nimport { RequiredPath } from '../core/schema.ts';\nimport { getMaxTextFileSize, PARALLEL_CONCURRENCY } from '../core/util.ts';\nimport { isTotalFailure, runOverPaths } from './batch.ts';\nimport { defineTool, type ToolCtx } from './define.ts';\n\nconst EPOCH = new Date(0);\n\nconst CreateFileItemSchema = z.strictObject({\n path: RequiredPath.describe('Absolute path where the file will be created'),\n content: z\n .string()\n .refine((val) => val.length <= getMaxTextFileSize(), {\n message: 'Content exceeds maximum allowed text file size',\n })\n .describe('Text content to write, verbatim.'),\n append: z\n .boolean()\n .optional()\n .describe(\n 'Append the content to the end of the file instead of overwriting; creates the file if it does not exist',\n ),\n overwrite: z\n .boolean()\n .optional()\n .describe(\n 'Replace an existing file without asking the user; without it an existing file prompts for confirmation',\n ),\n});\n\ntype CreateFileResult = Omit<WrittenFileMeta, 'resourceLink'> & {\n path: string;\n created: string;\n modified: string;\n};\n\nconst CreateInputSchema = z\n .strictObject({\n files: z\n .array(CreateFileItemSchema)\n .min(1)\n .max(100)\n .describe(\n 'List of files to create (max 100); each entry requires path and content; combined content is capped at the file-size limit',\n ),\n })\n .superRefine((value, ctx) => {\n // Entries write in parallel and each replaces its file whole, so two\n // entries for one path race: the last rename wins and the other's\n // content is lost while both report success. One entry per file.\n for (const [index, file] of value.files.entries()) {\n const first = value.files.findIndex((other) => isSamePath(other.path, file.path));\n if (first < index) {\n ctx.addIssue({\n code: 'custom',\n path: ['files', index, 'path'],\n message: `duplicate of files[${String(first)}].path; one entry per file`,\n input: value,\n });\n }\n }\n // One call's content is what one inbound message carries; the transports\n // size their message bound from this same limit (getMaxInboundMessageBytes),\n // so a batch that passes here always fits on the wire. Counted in the same\n // UTF-16 units as the per-file refine above.\n const total = value.files.reduce((sum, file) => sum + file.content.length, 0);\n const limit = getMaxTextFileSize();\n if (total > limit) {\n ctx.addIssue({\n code: 'custom',\n path: ['files'],\n message: `combined content is ${String(total)} characters; one create call carries at most ${String(limit)} (FS_MAX_FILE_SIZE). Split the batch.`,\n input: value,\n });\n }\n });\n\ninterface CreateFailureItem {\n path: string;\n error: Problem;\n}\n\ninterface CreateOutput {\n files: CreateFileResult[];\n failures?: CreateFailureItem[];\n skipped?: string[];\n}\n\nexport const CREATE = defineTool<typeof CreateInputSchema, CreateOutput>({\n name: 'create',\n title: 'Create Files',\n description:\n 'Write whole text files: create new ones, overwrite, or append. Missing parent directories are created. ' +\n 'edit or patch changes part of an existing file.',\n input: CreateInputSchema,\n readOnlyHint: false,\n accessPaths: (args) => args.files.map((f) => f.path),\n run: async (args, ctx) => {\n // Phase 1 (no mutation): which entries would replace a file that exists\n // right now? Those need the user's word before anything is written (R14).\n // append never destroys, and overwrite: true is that word given up front.\n // A path that fails validation here is left for runOverPaths to report.\n // A file that appears between rounds needs no re-stat before the write:\n // the retry re-plans, and the grown pending set fails the R9 check.\n const { results: planned } = await processInParallel(\n args.files,\n async (entry) => {\n if (entry.append || entry.overwrite) return undefined;\n try {\n const validPath = await ctx.fs.pathGuard.validatePathForWrite(entry.path);\n return (await destExists(ctx.fs, validPath, 'create')) ? validPath : undefined;\n } catch (error) {\n rethrowIfAborted(error);\n return undefined;\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n const pendingByPath = new Map<string, string>();\n for (const { index, value } of planned) {\n const requested = args.files[index]?.path;\n if (value && requested) pendingByPath.set(requested, value);\n }\n const pendingSorted = [...new Set(pendingByPath.values())].sort();\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required; a retry whose verified state does not\n // bind this overwrite set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip(ctx, {\n op: 'create',\n pending: pendingSorted,\n buildInputs: (paths) =>\n paths.map((target, i) => ({\n key: confirmKey(i),\n message: `\"${target}\" already exists. Overwrite it?`,\n choices: ['overwrite', 'skip'],\n })),\n });\n if (round !== undefined) return round;\n }\n\n const batch = await runOverPaths<\n z.infer<typeof CreateFileItemSchema>,\n { file: CreateFileResult; resourceLink?: ContentBlock } | { skipped: string }\n >(args.files, ctx, ErrorCode.UNKNOWN, async ({ path, content, append, overwrite }) => {\n const pendingPath = pendingByPath.get(path);\n if (pendingPath !== undefined) {\n const verdict = readPendingVerdict(ctx, pendingSorted, pendingPath, 'overwrite');\n if (verdict === 'skipped') return { skipped: path };\n if (verdict !== 'accepted') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `create cancelled: overwrite of \"${path}\" was ${verdict.refused}`,\n path,\n );\n }\n }\n\n // Lock per resolved file so two entries naming one file (e.g. through a\n // symlinked parent) cannot clobber each other.\n return ctx.fs.lockForWrite(path, async (resolvedTarget) => {\n // The file may have appeared since the overwrite set was planned.\n if (\n !append &&\n !overwrite &&\n pendingPath === undefined &&\n (await destExists(ctx.fs, resolvedTarget, 'create'))\n ) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `create refused: \"${path}\" appeared after overwrite confirmation was checked`,\n path,\n );\n }\n return createOne(path, content, append, ctx);\n });\n });\n\n const results: CreateFileResult[] = [];\n const failures: CreateFailureItem[] = [];\n const skipped: string[] = [];\n const links: ContentBlock[] = [];\n for (const r of batch.results) {\n if ('error' in r) {\n failures.push({ path: r.path, error: r.error });\n continue;\n }\n if ('skipped' in r.value) {\n skipped.push(r.value.skipped);\n continue;\n }\n results.push(r.value.file);\n if (r.value.resourceLink) links.push(r.value.resourceLink);\n }\n\n const structured = {\n files: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n // No `text` on purpose. The one-line roster this used to build named the\n // paths and dropped every per-file size, line count and error the caller\n // asked `create` for. Supplying no text makes this a data tool, so\n // `define.ts` renders the JSON and keeps it in `structuredContent`.\n return { structured, resources: links, isError: isTotalFailure(batch.summary) };\n },\n progress: (args) => ({\n label: 'Create',\n subject:\n args.files.length === 1\n ? basename(args.files[0]?.path ?? '')\n : `${String(args.files.length)} files`,\n }),\n});\n\nasync function createOne(\n path: string,\n content: string,\n append: boolean | undefined,\n ctx: ToolCtx,\n): Promise<{ file: CreateFileResult; resourceLink?: ContentBlock }> {\n await ctx.fs.mkdir(dirname(path), { recursive: true });\n\n // Overwrite: file content == `content`, so content-derived meta is\n // exact and the atomic temp+rename write protects the existing mode.\n // Append: the resulting file is everything that was there plus\n // `content`, so size/created/modified come from a real post-append\n // stat, MIME from the resulting file's leading bytes, and the line\n // count streams the file — reading a multi-GB log back whole is the\n // round-trip append exists to avoid.\n let validPath: string;\n let meta: WrittenFileMeta;\n let created: string;\n let modified: string;\n if (append) {\n const appended = await ctx.fs.appendFile(path, content, {\n signal: ctx.signal,\n });\n validPath = appended.validPath;\n // The append is the commit point: the bytes are on disk, so\n // everything below is best-effort RESULT METADATA, not part of the\n // write. It runs unwired to ctx.signal, and a metadata failure\n // degrades the result instead of failing it — either would report\n // the append as failed and a client retry would append twice. The\n // stat covers the committed validPath, never the input path: a\n // symlink there could have been swapped between write and stat,\n // and the result must describe the file the bytes landed in.\n let stats: Stats | undefined;\n let mimeType: string;\n let kind: FileKind;\n let lineCount = 0;\n try {\n stats = (await ctx.fs.stat(appended.validPath)).stats;\n // Sniff the resulting file's leading bytes, not the appended\n // chunk: text appended to a binary file is still a binary file.\n const sample = await ctx.fs.readLeadingSample(appended.validPath);\n const mimeInfo = detectMimeFromContent(appended.validPath, sample);\n mimeType = mimeInfo.mimeType;\n kind = mimeInfo.kind;\n lineCount = await ctx.fs.countFileLines(appended.validPath);\n } catch (error) {\n ctx.log(\n 'warning',\n `create append: result metadata degraded for ${appended.validPath}: ${formatUnknownErrorMessage(error)}`,\n 'create',\n );\n // A POSIX mode-0222 file appends fine but cannot be opened 'r';\n // fall back to the chunk for MIME (an approximation) and report\n // the line count as unknown-as-zero rather than fail the append.\n const mimeInfo = detectMimeFromContent(appended.validPath, content);\n mimeType = mimeInfo.mimeType;\n kind = mimeInfo.kind;\n }\n // A failed stat leaves the size unknown, so nothing is advertised.\n meta = {\n size: stats?.size ?? 0,\n lineCount,\n mimeType,\n kind,\n ...writtenFileLinks(\n appended.validPath,\n mimeType,\n stats?.size,\n false,\n stats?.mtime.toISOString(),\n ),\n };\n created = (stats?.birthtime ?? EPOCH).toISOString();\n modified = (stats?.mtime ?? EPOCH).toISOString();\n } else {\n const written = await ctx.fs.writeFile(path, content, {\n signal: ctx.signal,\n });\n validPath = written.validPath;\n const fileStats = (await ctx.fs.stat(path, { signal: ctx.signal })).stats;\n created = fileStats.birthtime.toISOString();\n modified = fileStats.mtime.toISOString();\n meta = buildWrittenFileMeta({\n validPath: written.validPath,\n content,\n lastModified: modified,\n });\n }\n\n const { resourceLink, ...fileMeta } = meta;\n const file: CreateFileResult = { path: validPath, ...fileMeta, created, modified };\n\n return resourceLink ? { file, resourceLink } : { file };\n}\n"]}
|
package/dist/tools/define.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ClientCapabilities, ContentBlock, InputRequiredResult, McpServer,
|
|
1
|
+
import type { ClientCapabilities, ContentBlock, InputRequiredResult, McpServer, RegisteredTool, RequestId, RequestStateAccessor, ServerContext } from '@modelcontextprotocol/server';
|
|
2
2
|
import type * as z from 'zod/v4';
|
|
3
3
|
import { ErrorCode } from '../core/errors.ts';
|
|
4
4
|
import type { ProgressCtx } from '../core/fmt.ts';
|
|
@@ -8,17 +8,13 @@ import type { PathGuard } from '../core/path.ts';
|
|
|
8
8
|
import type { PageSnapshotStore, ResourceStore } from '../core/store.ts';
|
|
9
9
|
export interface ToolCtx {
|
|
10
10
|
readonly signal: AbortSignal;
|
|
11
|
-
readonly _meta?: RequestMeta | undefined;
|
|
12
11
|
/** The JSON-RPC id of the `tools/call` this context serves; prefixes every log line. */
|
|
13
12
|
readonly requestId: RequestId;
|
|
14
|
-
/** W3C trace context the client put in `_meta`, when it did; rides the log prefix. */
|
|
15
|
-
readonly traceparent?: string | undefined;
|
|
16
13
|
readonly fs: GuardedFileSystem;
|
|
17
14
|
readonly pageStore: PageSnapshotStore;
|
|
18
15
|
readonly resourceStore: ResourceStore;
|
|
19
16
|
/** Emits a log line to stderr via `Logger.emit`, gated by `FS_LOG_LEVEL`. */
|
|
20
17
|
readonly log: (level: LoggingLevel, data: unknown, logger?: string) => void;
|
|
21
|
-
readonly sendNotification: (notification: Notification) => Promise<void>;
|
|
22
18
|
readonly onProgress: (params: {
|
|
23
19
|
current: number;
|
|
24
20
|
total?: number;
|
|
@@ -59,10 +55,10 @@ export interface ToolCtx {
|
|
|
59
55
|
readonly clientCapabilities?: ClientCapabilities | undefined;
|
|
60
56
|
/** The SDK request context this call runs under; `pendingRoundTrip` binds minted state to it. */
|
|
61
57
|
readonly serverCtx: ServerContext;
|
|
62
|
-
/** `stdio` alone has a 10 MiB frame limit;
|
|
58
|
+
/** `stdio` alone has a 10 MiB frame limit; `http` on HTTP, unset on the in-memory test pair. */
|
|
63
59
|
readonly transport?: 'stdio' | 'http' | undefined;
|
|
64
60
|
}
|
|
65
|
-
interface ToolDeps {
|
|
61
|
+
export interface ToolDeps {
|
|
66
62
|
readonly server: McpServer;
|
|
67
63
|
readonly pathGuard: PathGuard;
|
|
68
64
|
readonly pageStore: PageSnapshotStore;
|
|
@@ -102,6 +98,11 @@ export interface ToolDef<I extends z.ZodType, O extends object> {
|
|
|
102
98
|
*/
|
|
103
99
|
readonly accessPaths?: (args: z.infer<I>) => readonly string[];
|
|
104
100
|
readonly run: (args: z.infer<I>, ctx: ToolCtx) => Promise<RunResult<O> | InputRequiredResult>;
|
|
101
|
+
/**
|
|
102
|
+
* What the stdio size refusal tells the caller to do instead, for a tool
|
|
103
|
+
* that knows better than the generic advice (see `refuseOversized`).
|
|
104
|
+
*/
|
|
105
|
+
readonly oversizeRemedy?: (result: RunResult<O>) => string;
|
|
105
106
|
}
|
|
106
107
|
export interface DefinedTool {
|
|
107
108
|
readonly name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.d.ts","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,SAAS,
|
|
1
|
+
{"version":3,"file":"define.d.ts","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,SAAS,EAET,cAAc,EACd,SAAS,EACT,oBAAoB,EACp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ErrorCode, formatUnknownErrorMessage, Problem } from "../core/errors.js";
|
|
2
|
+
import { ErrorCode, formatUnknownErrorMessage, FsError, Problem } from "../core/errors.js";
|
|
3
3
|
import { plainMessage } from "../core/fmt.js";
|
|
4
4
|
import { GuardedFileSystem } from "../core/fs.js";
|
|
5
5
|
import { confirmKey, pendingRoundTrip, readAcceptedConfirm, readAcceptedMultiChoice, } from "../core/input-required.js";
|
|
6
6
|
import { Logger, sanitizeLogField } from "../core/observability.js";
|
|
7
7
|
import { isSamePath } from "../core/path-utils.js";
|
|
8
8
|
import { withSplitArgsRecovery } from "../core/schema.js";
|
|
9
|
+
import { jsonBytesOver, MAX_OUTBOUND_RESULT_BYTES } from "../core/util.js";
|
|
9
10
|
import { ProgressSession } from "./progress.js";
|
|
10
11
|
function toToolCtx(ctx, deps) {
|
|
11
12
|
// Envelope first, accessor second — the two eras carry this differently.
|
|
@@ -33,15 +34,10 @@ function toToolCtx(ctx, deps) {
|
|
|
33
34
|
(deps.era === 'legacy' ? {} : undefined);
|
|
34
35
|
return {
|
|
35
36
|
signal: ctx.mcpReq.signal,
|
|
36
|
-
...(ctx.mcpReq._meta ? { _meta: ctx.mcpReq._meta } : {}),
|
|
37
37
|
requestId: ctx.mcpReq.id,
|
|
38
|
-
...(typeof ctx.mcpReq._meta?.[TRACEPARENT_META_KEY] === 'string'
|
|
39
|
-
? { traceparent: ctx.mcpReq._meta[TRACEPARENT_META_KEY] }
|
|
40
|
-
: {}),
|
|
41
38
|
fs: new GuardedFileSystem(deps.pathGuard),
|
|
42
39
|
pageStore: deps.pageStore,
|
|
43
40
|
resourceStore: deps.resourceStore,
|
|
44
|
-
sendNotification: async (notification) => ctx.mcpReq.notify(notification),
|
|
45
41
|
inputResponses: ctx.mcpReq.inputResponses,
|
|
46
42
|
droppedInputResponseKeys: ctx.mcpReq.droppedInputResponseKeys,
|
|
47
43
|
requestState: ctx.mcpReq.requestState,
|
|
@@ -85,14 +81,21 @@ class ToolExecutor {
|
|
|
85
81
|
? AbortSignal.any([ctx.signal, AbortSignal.timeout(def.timeoutMs)])
|
|
86
82
|
: ctx.signal;
|
|
87
83
|
this.#progressCtx = def.progress ? def.progress(parsedArgs) : { label: def.title };
|
|
88
|
-
const
|
|
84
|
+
const { mcpReq } = ctx.serverCtx;
|
|
85
|
+
const token = mcpReq._meta?.progressToken;
|
|
86
|
+
const notify = async (notification) => mcpReq.notify(notification);
|
|
89
87
|
this.#progressSession = new ProgressSession({
|
|
90
88
|
label: this.#progressCtx.label,
|
|
91
|
-
...(token !== undefined ? { sink: { toolName, token, notify
|
|
89
|
+
...(token !== undefined ? { sink: { toolName, token, notify } } : {}),
|
|
92
90
|
});
|
|
91
|
+
const traceparent = mcpReq._meta?.[TRACEPARENT_META_KEY];
|
|
93
92
|
this.toolCtx = {
|
|
94
93
|
...ctx,
|
|
95
94
|
signal: this.signal,
|
|
95
|
+
// Per-call views, so a response refused after `run` can take back the
|
|
96
|
+
// cached result and page snapshot behind a link or cursor it never sent.
|
|
97
|
+
pageStore: ctx.pageStore.forCall(),
|
|
98
|
+
resourceStore: ctx.resourceStore.forCall(),
|
|
96
99
|
log: (level, data, logger) => {
|
|
97
100
|
const msg = typeof data === 'string' ? data : String(data);
|
|
98
101
|
// `[req <id>]` first so one grep finds every line of one call; the
|
|
@@ -102,7 +105,7 @@ class ToolExecutor {
|
|
|
102
105
|
// The message is flattened too (uncapped): it can carry a resolved
|
|
103
106
|
// path or OS error text, and input schemas reject CR/LF but not the
|
|
104
107
|
// Unicode line separators.
|
|
105
|
-
const trace =
|
|
108
|
+
const trace = typeof traceparent === 'string' ? ` ${sanitizeLogField(traceparent)}` : '';
|
|
106
109
|
const prefix = logger ? `[${logger}] ` : '';
|
|
107
110
|
const text = sanitizeLogField(msg, Infinity);
|
|
108
111
|
Logger.emit(level, `[req ${sanitizeLogField(String(ctx.requestId))}${trace}] ${prefix}${text}`);
|
|
@@ -120,17 +123,15 @@ class ToolExecutor {
|
|
|
120
123
|
};
|
|
121
124
|
this.#progressSession.set({ ...p, message: plainMessage('tick', tickCtx) });
|
|
122
125
|
}
|
|
123
|
-
|
|
126
|
+
completeProgress(result) {
|
|
124
127
|
const doneCtx = this.def.progressDone
|
|
125
128
|
? { ...this.#progressCtx, ...this.def.progressDone(this.parsedArgs, result) }
|
|
126
129
|
: this.#progressCtx;
|
|
127
130
|
this.#progressSession.complete(plainMessage('done', doneCtx));
|
|
128
|
-
await this.#progressSession.flush();
|
|
129
131
|
}
|
|
130
|
-
|
|
132
|
+
failProgress(error) {
|
|
131
133
|
const errMsg = formatUnknownErrorMessage(error);
|
|
132
134
|
this.#progressSession.fail(plainMessage('fail', { ...this.#progressCtx, error: errMsg }));
|
|
133
|
-
await this.#progressSession.flush();
|
|
134
135
|
const errorText = Problem.toText(error, this.def.defaultErrorCode ?? ErrorCode.UNKNOWN);
|
|
135
136
|
return {
|
|
136
137
|
content: [{ type: 'text', text: errorText }],
|
|
@@ -206,6 +207,35 @@ class ToolExecutor {
|
|
|
206
207
|
}
|
|
207
208
|
return undefined;
|
|
208
209
|
}
|
|
210
|
+
/**
|
|
211
|
+
* stdio's SDK reader drops the connection on a message past 10 MiB, so a
|
|
212
|
+
* response that would overflow it becomes TOO_LARGE instead. Only a call
|
|
213
|
+
* that changed nothing can be refused after `run` — a read-only tool, or a
|
|
214
|
+
* dry run (every tool with `dryRun` writes nothing under it); a mutation may
|
|
215
|
+
* already have committed. The whole encoded response counts, duplicated
|
|
216
|
+
* metadata and escaping included; the ceiling leaves room for the envelope.
|
|
217
|
+
*/
|
|
218
|
+
refuseOversized(result, response) {
|
|
219
|
+
if (this.toolCtx.transport !== 'stdio')
|
|
220
|
+
return;
|
|
221
|
+
const dryRun = this.parsedArgs.dryRun === true;
|
|
222
|
+
if (!this.def.readOnlyHint && !dryRun)
|
|
223
|
+
return;
|
|
224
|
+
const encodedBytes = jsonBytesOver(response, MAX_OUTBOUND_RESULT_BYTES);
|
|
225
|
+
if (encodedBytes === undefined)
|
|
226
|
+
return;
|
|
227
|
+
// The client never receives the link or cursor these back, so they would
|
|
228
|
+
// only push live entries out of the stores' caps.
|
|
229
|
+
this.toolCtx.resourceStore.discard();
|
|
230
|
+
this.toolCtx.pageStore.discard();
|
|
231
|
+
const remedy = this.def.oversizeRemedy?.(result) ??
|
|
232
|
+
(dryRun
|
|
233
|
+
? 'Nothing was written. Preview fewer files or a smaller file per call, or connect over HTTP.'
|
|
234
|
+
: 'Reduce the requested output or connect over HTTP.');
|
|
235
|
+
// The remedy stands in for TOO_LARGE's default head/tail advice, which
|
|
236
|
+
// fits neither media nor a dry run.
|
|
237
|
+
throw new FsError(ErrorCode.TOO_LARGE, `${this.def.name} result too large to return (${String(encodedBytes)} bytes once JSON-encoded, over the ${String(MAX_OUTBOUND_RESULT_BYTES)}-byte stdio message limit).`, undefined, undefined, remedy);
|
|
238
|
+
}
|
|
209
239
|
async execute() {
|
|
210
240
|
try {
|
|
211
241
|
// Access-grant pre-check before any filesystem touch (R7/R8/R9). A
|
|
@@ -224,11 +254,13 @@ class ToolExecutor {
|
|
|
224
254
|
if (isInputRequiredResult(result)) {
|
|
225
255
|
return result;
|
|
226
256
|
}
|
|
227
|
-
|
|
228
|
-
|
|
257
|
+
const response = buildSuccessResponse(result);
|
|
258
|
+
this.refuseOversized(result, response);
|
|
259
|
+
this.completeProgress(result.structured);
|
|
260
|
+
return response;
|
|
229
261
|
}
|
|
230
262
|
catch (error) {
|
|
231
|
-
return
|
|
263
|
+
return this.failProgress(error);
|
|
232
264
|
}
|
|
233
265
|
finally {
|
|
234
266
|
await this.#progressSession.flush();
|
package/dist/tools/define.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAeA,OAAO,EACL,4BAA4B,EAC5B,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,8BAA8B,CAAC;AAItC,OAAO,EAAE,SAAS,EAAE,yBAAyB,EAAE,OAAO,E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Y,EAAE,GAAG,CAAC,YAAY;QAE9B,QAAQ,CAAC,IAAc;YACrB,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE,CAC1E,IAAI,YAAY,CAAO,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,OAAO,EAAE,CAC5E,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CallToolResult,\n ClientCapabilities,\n ContentBlock,\n InputRequiredResult,\n McpServer,\n Notification,\n RegisteredTool,\n RequestId,\n RequestMeta,\n RequestStateAccessor,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server';\nimport {\n CLIENT_CAPABILITIES_META_KEY,\n isInputRequiredResult,\n TRACEPARENT_META_KEY,\n} from '@modelcontextprotocol/server';\n\nimport type * as z from 'zod/v4';\n\nimport { ErrorCode, formatUnknownErrorMessage, Problem } from '../core/errors.ts';\nimport type { ProgressCtx } from '../core/fmt.ts';\nimport { plainMessage } from '../core/fmt.ts';\nimport { GuardedFileSystem } from '../core/fs.ts';\nimport {\n confirmKey,\n pendingRoundTrip,\n readAcceptedConfirm,\n readAcceptedMultiChoice,\n} from '../core/input-required.ts';\nimport { Logger, sanitizeLogField } from '../core/observability.ts';\nimport type { LoggingLevel } from '../core/observability.ts';\nimport { isSamePath } from '../core/path-utils.ts';\nimport type { PathGuard } from '../core/path.ts';\nimport { withSplitArgsRecovery } from '../core/schema.ts';\nimport type { PageSnapshotStore, ResourceStore } from '../core/store.ts';\nimport { ProgressSession } from './progress.ts';\n\nexport interface ToolCtx {\n readonly signal: AbortSignal;\n readonly _meta?: RequestMeta | undefined;\n /** The JSON-RPC id of the `tools/call` this context serves; prefixes every log line. */\n readonly requestId: RequestId;\n /** W3C trace context the client put in `_meta`, when it did; rides the log prefix. */\n readonly traceparent?: string | undefined;\n readonly fs: GuardedFileSystem;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore;\n /** Emits a log line to stderr via `Logger.emit`, gated by `FS_LOG_LEVEL`. */\n readonly log: (level: LoggingLevel, data: unknown, logger?: string) => void;\n readonly sendNotification: (notification: Notification) => Promise<void>;\n readonly onProgress: (params: { current: number; total?: number }) => void;\n /**\n * Multi-round-trip `inputResponses` carried by a retried `tools/call`\n * (protocol revision 2026-07-28); `undefined` on the first round. Bare,\n * unvalidated client values — handlers read them through\n * `readAcceptedConfirm`.\n */\n readonly inputResponses?: Record<string, unknown> | undefined;\n /**\n * Keys of `inputResponses` entries the SDK dropped on this round because\n * they were not bare results (the `{ method, result }` wrapper some hosts\n * send). `pendingRoundTrip` re-issues a confirmation whose key is listed\n * here once; `describeRefusal` names the cause after that.\n */\n readonly droppedInputResponseKeys?: readonly string[] | undefined;\n /**\n * Reads the verified multi-round-trip `requestState` for the current round:\n * the decoded `PendingState` the `requestStateCodec` verified, or `undefined`\n * when the round carried no state (the first round). `undefined` when no\n * live request context is available.\n */\n readonly requestState?: RequestStateAccessor | undefined;\n /**\n * What the connected client declared it can do, or `undefined` when this\n * connection cannot say. Read by the `input_required` flows: an embedded\n * elicitation sent to a client that never declared `elicitation` is rejected\n * by the SDK with `-32021` before it reaches the wire, so the handlers check\n * first and answer with an actionable tool error instead.\n *\n * Two sources, because the eras differ: a legacy connection negotiated them\n * at `initialize` (`Server.getClientCapabilities()`), a modern one carries\n * them per request in the `_meta` envelope and never runs `initialize` at\n * all. `undefined` means \"cannot tell\" — never \"no capabilities\".\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n /** The SDK request context this call runs under; `pendingRoundTrip` binds minted state to it. */\n readonly serverCtx: ServerContext;\n /** `stdio` alone has a 10 MiB frame limit; unset on HTTP and the in-memory test pair. */\n readonly transport?: 'stdio' | 'http' | undefined;\n}\n\ninterface ToolDeps {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore;\n readonly era?: 'legacy' | 'modern';\n readonly transport?: 'stdio' | 'http';\n}\n\ninterface RunResult<T> {\n readonly structured: T;\n readonly text?: string;\n readonly resources?: ContentBlock[];\n /**\n * The call as a whole failed. Batch tools set it from `isTotalFailure` in\n * `batch.ts` — every requested item failed — so the executor never has to\n * know a tool's output shape. Absent or `false` means the call did work.\n */\n readonly isError?: boolean;\n}\n\nexport interface ToolDef<I extends z.ZodType, O extends object> {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly input: I;\n /** Required: drives both the --read-only gate and published annotations. */\n readonly readOnlyHint: boolean;\n readonly timeoutMs?: number;\n readonly progress?: (args: z.infer<I>) => ProgressCtx;\n readonly progressDone?: (args: z.infer<I>, result: O) => Partial<ProgressCtx>;\n readonly defaultErrorCode?: ErrorCode;\n /**\n * The filesystem paths this tool will operate on, extracted from its parsed\n * args. The executor runs an access-grant pre-check over these BEFORE `run`\n * (R7): any path outside the granted roots yields an `input_required`\n * round-trip requesting a grant, and nothing is touched until the client\n * retries with an accepted grant (R8). Omit for tools that do not operate on\n * caller-supplied filesystem paths.\n */\n readonly accessPaths?: (args: z.infer<I>) => readonly string[];\n readonly run: (args: z.infer<I>, ctx: ToolCtx) => Promise<RunResult<O> | InputRequiredResult>;\n}\n\nexport interface DefinedTool {\n readonly name: string;\n readonly readOnlyHint: boolean;\n\n register(deps: ToolDeps): RegisteredTool;\n}\n\nfunction toToolCtx(\n ctx: ServerContext,\n deps: Pick<\n ToolDeps,\n 'pathGuard' | 'pageStore' | 'resourceStore' | 'server' | 'era' | 'transport'\n >,\n): Omit<ToolCtx, 'log' | 'onProgress'> {\n // Envelope first, accessor second — the two eras carry this differently.\n // A modern request states the capabilities in its own `_meta` envelope; a\n // legacy connection fixed them at `initialize` and has no envelope at all.\n // The deprecated accessor still answers for both today (the SDK backfills it\n // per request from the validated envelope on modern instances), but reading\n // the envelope directly is the supported path, so it leads: when the accessor\n // goes, legacy degrades to \"cannot tell\", which fails open to the behavior\n // that predates this check.\n //\n // The cast is the SDK's shipped `RequestMetaEnvelope` declaration collapsing\n // to `{}` — the reserved keys survive at runtime but not in the .d.ts, so the\n // key constant cannot index the declared type.\n const envelope = ctx.mcpReq.envelope as Record<string, unknown> | undefined;\n const clientCapabilities =\n (envelope?.[CLIENT_CAPABILITIES_META_KEY] as ClientCapabilities | undefined) ??\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the only source of client capabilities on a legacy connection, where no envelope exists.\n deps.server.server.getClientCapabilities() ??\n // A legacy instance that never saw `initialize` is the HTTP leg's\n // per-request serving (`createMcpHandler` with `legacy: 'stateless'`):\n // there is no return path for a server-to-client request, so read the\n // client as having declared nothing. The `input_required` flows then\n // answer with their named workaround instead of the SDK's generic refusal.\n // sunset(SEP-2577): removal trigger in docs/adr/002-legacy-protocol-paths-sunset.md.\n (deps.era === 'legacy' ? {} : undefined);\n\n return {\n signal: ctx.mcpReq.signal,\n ...(ctx.mcpReq._meta ? { _meta: ctx.mcpReq._meta } : {}),\n requestId: ctx.mcpReq.id,\n ...(typeof ctx.mcpReq._meta?.[TRACEPARENT_META_KEY] === 'string'\n ? { traceparent: ctx.mcpReq._meta[TRACEPARENT_META_KEY] }\n : {}),\n fs: new GuardedFileSystem(deps.pathGuard),\n pageStore: deps.pageStore,\n resourceStore: deps.resourceStore,\n sendNotification: async (notification) => ctx.mcpReq.notify(notification),\n inputResponses: ctx.mcpReq.inputResponses,\n droppedInputResponseKeys: ctx.mcpReq.droppedInputResponseKeys,\n requestState: ctx.mcpReq.requestState,\n serverCtx: ctx,\n ...(clientCapabilities ? { clientCapabilities } : {}),\n ...(deps.transport ? { transport: deps.transport } : {}),\n };\n}\n\n/**\n * Claude Code — and any client that treats `structuredContent` as the canonical\n * model view — discards the `text` blocks when `structuredContent` is present,\n * showing the model `JSON.stringify(structuredContent)` instead. A tool that\n * authored a text result (list's ASCII tree, read's file) meant that text for\n * the model, so it ships its metadata under `_meta`, which no client renders in\n * place of the content. Tools with no `text` keep `structuredContent`: the JSON\n * *is* their model-facing view.\n */\nfunction buildSuccessResponse<O extends object>(result: RunResult<O>): CallToolResult {\n const hasText = result.text !== undefined;\n const text = result.text ?? JSON.stringify(result.structured);\n const content: ContentBlock[] = [{ type: 'text' as const, text }, ...(result.resources ?? [])];\n return {\n content,\n ...(hasText // Result interfaces have named fields; the SDK metadata requires an index signature.\n ? { _meta: result.structured as Record<string, unknown> }\n : { structuredContent: result.structured }),\n ...(result.isError ? { isError: true } : {}),\n };\n}\n\nclass ToolExecutor<I extends z.ZodType, O extends object> {\n readonly signal: AbortSignal;\n private readonly def: ToolDef<I, O>;\n private readonly parsedArgs: z.infer<I>;\n private readonly toolCtx: ToolCtx;\n\n readonly #progressCtx: ProgressCtx;\n readonly #progressSession: ProgressSession;\n\n constructor(\n toolName: string,\n ctx: Omit<ToolCtx, 'log' | 'onProgress'>,\n def: ToolDef<I, O>,\n parsedArgs: z.infer<I>,\n ) {\n this.def = def;\n this.parsedArgs = parsedArgs;\n this.signal = def.timeoutMs\n ? AbortSignal.any([ctx.signal, AbortSignal.timeout(def.timeoutMs)])\n : ctx.signal;\n this.#progressCtx = def.progress ? def.progress(parsedArgs) : { label: def.title };\n const token = ctx._meta?.progressToken;\n this.#progressSession = new ProgressSession({\n label: this.#progressCtx.label,\n ...(token !== undefined ? { sink: { toolName, token, notify: ctx.sendNotification } } : {}),\n });\n this.toolCtx = {\n ...ctx,\n signal: this.signal,\n log: (level: LoggingLevel, data: unknown, logger?: string) => {\n const msg = typeof data === 'string' ? data : String(data);\n // `[req <id>]` first so one grep finds every line of one call; the\n // traceparent rides along only when the client sent one. Both are\n // client-supplied, so they pass through `sanitizeLogField`: a control\n // character in a JSON-RPC id or a traceparent would forge log lines.\n // The message is flattened too (uncapped): it can carry a resolved\n // path or OS error text, and input schemas reject CR/LF but not the\n // Unicode line separators.\n const trace = ctx.traceparent ? ` ${sanitizeLogField(ctx.traceparent)}` : '';\n const prefix = logger ? `[${logger}] ` : '';\n const text = sanitizeLogField(msg, Infinity);\n Logger.emit(\n level,\n `[req ${sanitizeLogField(String(ctx.requestId))}${trace}] ${prefix}${text}`,\n );\n },\n onProgress: (p) => {\n this.#tick(p);\n },\n };\n }\n\n #tick(p: { current: number; total?: number }): void {\n const tickCtx: ProgressCtx = {\n ...this.#progressCtx,\n current: p.current,\n ...(p.total !== undefined ? { total: p.total } : {}),\n };\n this.#progressSession.set({ ...p, message: plainMessage('tick', tickCtx) });\n }\n\n private async completeProgress(result: O): Promise<void> {\n const doneCtx: ProgressCtx = this.def.progressDone\n ? { ...this.#progressCtx, ...this.def.progressDone(this.parsedArgs, result) }\n : this.#progressCtx;\n this.#progressSession.complete(plainMessage('done', doneCtx));\n await this.#progressSession.flush();\n }\n\n private async failProgress(error: unknown): Promise<{ isError: true; content: ContentBlock[] }> {\n const errMsg = formatUnknownErrorMessage(error);\n this.#progressSession.fail(plainMessage('fail', { ...this.#progressCtx, error: errMsg }));\n await this.#progressSession.flush();\n const errorText = Problem.toText(error, this.def.defaultErrorCode ?? ErrorCode.UNKNOWN);\n return {\n content: [{ type: 'text' as const, text: errorText }],\n isError: true,\n };\n }\n\n /**\n * Access-grant pre-check (R7/R8/R9). Before `run` touches the filesystem,\n * ask PathGuard which of the tool's declared paths are out-of-root and\n * grantable. If any are and this round carries no verified `requestState`,\n * return `input_required` (nothing is read or written — R7). On retry, the\n * verified state must bind this grant set (R9); apply each accepted grant for\n * the session (R8) and proceed. A declined or ungrantable path is left for\n * `validateAccess` to fail closed during the operation. Returns `undefined`\n * when no round-trip is needed and any applicable grants have been applied.\n */\n private async precheckGrant(): Promise<InputRequiredResult | undefined> {\n const extract = this.def.accessPaths;\n if (!extract) return undefined;\n const paths = extract(this.parsedArgs);\n if (paths.length === 0) return undefined;\n const grantDirs = await this.toolCtx.fs.pathGuard.precheckAccess(paths);\n if (grantDirs.length === 0) return undefined;\n\n // One grant dir: a single boolean confirm. Multiple: one multi-select\n // elicitation so the client picks the subset to allow in one round-trip\n // (N dirs → 1 round-trip, not N). `pendingRoundTrip` still binds\n // `paths: grantDirs` sorted, so R9 path-binding is unaffected.\n const multi = grantDirs.length > 1;\n const round = await pendingRoundTrip(this.toolCtx, {\n op: 'grant',\n pending: grantDirs,\n buildInputs: (dirs) =>\n multi\n ? [\n {\n key: 'grant',\n message: 'Grant filesystem access to these directories? Select the ones to allow.',\n choices: dirs,\n multi: true,\n },\n ]\n : dirs.map((dir, i) => ({\n key: confirmKey(i),\n message: `Grant filesystem access to \"${dir}\"?`,\n })),\n });\n if (round !== undefined) return round;\n // Apply accepted grants for the session (R8). Declined/missing dirs are\n // skipped here; their paths fail with ACCESS_DENIED during the operation.\n //\n // No list-changed notification follows: a grant widens the allowed roots,\n // and no resource list reads them. The instructions resource has a fixed\n // URI, the result template lists the ResourceStore, and the file template\n // lists nothing at all (see resources.ts). Notifying here only bought the\n // client a round trip to re-fetch a list that could not have changed.\n //\n // `readAcceptedMultiChoice` does NOT validate against the offered choices\n // (attacker-controlled inputResponses on re-entry). Only grant dirs that\n // were actually offered by precheckAccess — a value outside grantDirs is\n // ignored and fails closed in validateAccess. The single-select path reads\n // `confirmKey(i)` for `grantDirs[i]`, so the isSamePath filter is a no-op\n // there; it only bites for the multi-select array.\n const accepted = multi\n ? (readAcceptedMultiChoice(this.toolCtx.inputResponses, 'grant') ?? [])\n : grantDirs.filter((_dir, i) =>\n readAcceptedConfirm(this.toolCtx.inputResponses, confirmKey(i)),\n );\n for (const dir of accepted) {\n if (!grantDirs.some((g) => isSamePath(g, dir))) continue;\n await this.toolCtx.fs.pathGuard.applyGrant(dir);\n }\n return undefined;\n }\n\n async execute(): Promise<CallToolResult | InputRequiredResult> {\n try {\n // Access-grant pre-check before any filesystem touch (R7/R8/R9). A\n // grant input_required short-circuits here (progress paused, not\n // finished); an R9 mismatch throws, which this catch surfaces as an\n // isError tool result like every other handler failure — not a raw\n // JSON-RPC error (GRANT-1 impact #2).\n const grantRequired = await this.precheckGrant();\n if (grantRequired !== undefined) return grantRequired;\n const result = await this.def.run(this.parsedArgs, this.toolCtx);\n // input_required is a return value, not a completed call: the client\n // retries the same tools/call carrying inputResponses, and this\n // handler re-enters from the top. Skip the progress \"done\" close and\n // return it verbatim — progress is paused, not finished.\n if (isInputRequiredResult(result)) {\n return result;\n }\n await this.completeProgress(result.structured);\n return buildSuccessResponse(result);\n } catch (error) {\n return await this.failProgress(error);\n } finally {\n await this.#progressSession.flush();\n }\n }\n}\n\nexport function defineTool<I extends z.ZodType, O extends object>(def: ToolDef<I, O>): DefinedTool {\n // Nothing here depends on `deps`, so it is built once per tool definition\n // rather than once per `register` — the HTTP leg registers every tool afresh\n // on each request.\n // Filesystem tools are closed-world; only mutating tools are destructive.\n const publishedAnnotations: ToolAnnotations = {\n readOnlyHint: def.readOnlyHint,\n openWorldHint: false,\n ...(def.readOnlyHint ? {} : { destructiveHint: true }),\n };\n\n const toolDefShape = {\n title: def.title,\n description: def.description,\n // The Zod schema goes in behind `withSplitArgsRecovery` only: the SDK\n // validates with it and publishes its own draft-2020-12 conversion in\n // `tools/list`, which the preprocess step leaves unchanged. The cast only\n // names the in/out types a generic `ZodType` cannot surface through\n // `~standard`.\n inputSchema: withSplitArgsRecovery(def.input) as unknown as StandardSchemaWithJSON<\n z.input<I>,\n z.output<I>\n >,\n // No `outputSchema`, ever. Publishing one obliges the result to carry\n // `structuredContent` (clients enforce it), and every tool that authors its\n // own text ships its metadata under `_meta` instead — see\n // `buildSuccessResponse`. The two cannot both hold, and the text is what\n // the model reads. `TOOL-SURFACE-001` pins this for the whole surface.\n // Result shapes are checked by TypeScript, not unused runtime schemas.\n annotations: publishedAnnotations,\n };\n\n return {\n name: def.name,\n readOnlyHint: def.readOnlyHint,\n\n register(deps: ToolDeps): RegisteredTool {\n return deps.server.registerTool(def.name, toolDefShape, async (args, ctx) =>\n new ToolExecutor<I, O>(def.name, toToolCtx(ct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AE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE,CAC1E,IAAI,YAAY,CAAO,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,OAAO,EAAE,CAC5E,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CallToolResult,\n ClientCapabilities,\n ContentBlock,\n InputRequiredResult,\n McpServer,\n Notification,\n RegisteredTool,\n RequestId,\n RequestStateAccessor,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server';\nimport {\n CLIENT_CAPABILITIES_META_KEY,\n isInputRequiredResult,\n TRACEPARENT_META_KEY,\n} from '@modelcontextprotocol/server';\n\nimport type * as z from 'zod/v4';\n\nimport { ErrorCode, formatUnknownErrorMessage, FsError, Problem } from '../core/errors.ts';\nimport type { ProgressCtx } from '../core/fmt.ts';\nimport { plainMessage } from '../core/fmt.ts';\nimport { GuardedFileSystem } from '../core/fs.ts';\nimport {\n confirmKey,\n pendingRoundTrip,\n readAcceptedConfirm,\n readAcceptedMultiChoice,\n} from '../core/input-required.ts';\nimport { Logger, sanitizeLogField } from '../core/observability.ts';\nimport type { LoggingLevel } from '../core/observability.ts';\nimport { isSamePath } from '../core/path-utils.ts';\nimport type { PathGuard } from '../core/path.ts';\nimport { withSplitArgsRecovery } from '../core/schema.ts';\nimport type { PageSnapshotStore, ResourceStore } from '../core/store.ts';\nimport { jsonBytesOver, MAX_OUTBOUND_RESULT_BYTES } from '../core/util.ts';\nimport { ProgressSession } from './progress.ts';\n\nexport interface ToolCtx {\n readonly signal: AbortSignal;\n /** The JSON-RPC id of the `tools/call` this context serves; prefixes every log line. */\n readonly requestId: RequestId;\n readonly fs: GuardedFileSystem;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore;\n /** Emits a log line to stderr via `Logger.emit`, gated by `FS_LOG_LEVEL`. */\n readonly log: (level: LoggingLevel, data: unknown, logger?: string) => void;\n readonly onProgress: (params: { current: number; total?: number }) => void;\n /**\n * Multi-round-trip `inputResponses` carried by a retried `tools/call`\n * (protocol revision 2026-07-28); `undefined` on the first round. Bare,\n * unvalidated client values — handlers read them through\n * `readAcceptedConfirm`.\n */\n readonly inputResponses?: Record<string, unknown> | undefined;\n /**\n * Keys of `inputResponses` entries the SDK dropped on this round because\n * they were not bare results (the `{ method, result }` wrapper some hosts\n * send). `pendingRoundTrip` re-issues a confirmation whose key is listed\n * here once; `describeRefusal` names the cause after that.\n */\n readonly droppedInputResponseKeys?: readonly string[] | undefined;\n /**\n * Reads the verified multi-round-trip `requestState` for the current round:\n * the decoded `PendingState` the `requestStateCodec` verified, or `undefined`\n * when the round carried no state (the first round). `undefined` when no\n * live request context is available.\n */\n readonly requestState?: RequestStateAccessor | undefined;\n /**\n * What the connected client declared it can do, or `undefined` when this\n * connection cannot say. Read by the `input_required` flows: an embedded\n * elicitation sent to a client that never declared `elicitation` is rejected\n * by the SDK with `-32021` before it reaches the wire, so the handlers check\n * first and answer with an actionable tool error instead.\n *\n * Two sources, because the eras differ: a legacy connection negotiated them\n * at `initialize` (`Server.getClientCapabilities()`), a modern one carries\n * them per request in the `_meta` envelope and never runs `initialize` at\n * all. `undefined` means \"cannot tell\" — never \"no capabilities\".\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n /** The SDK request context this call runs under; `pendingRoundTrip` binds minted state to it. */\n readonly serverCtx: ServerContext;\n /** `stdio` alone has a 10 MiB frame limit; `http` on HTTP, unset on the in-memory test pair. */\n readonly transport?: 'stdio' | 'http' | undefined;\n}\n\nexport interface ToolDeps {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore;\n readonly era?: 'legacy' | 'modern';\n readonly transport?: 'stdio' | 'http';\n}\n\ninterface RunResult<T> {\n readonly structured: T;\n readonly text?: string;\n readonly resources?: ContentBlock[];\n /**\n * The call as a whole failed. Batch tools set it from `isTotalFailure` in\n * `batch.ts` — every requested item failed — so the executor never has to\n * know a tool's output shape. Absent or `false` means the call did work.\n */\n readonly isError?: boolean;\n}\n\nexport interface ToolDef<I extends z.ZodType, O extends object> {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly input: I;\n /** Required: drives both the --read-only gate and published annotations. */\n readonly readOnlyHint: boolean;\n readonly timeoutMs?: number;\n readonly progress?: (args: z.infer<I>) => ProgressCtx;\n readonly progressDone?: (args: z.infer<I>, result: O) => Partial<ProgressCtx>;\n readonly defaultErrorCode?: ErrorCode;\n /**\n * The filesystem paths this tool will operate on, extracted from its parsed\n * args. The executor runs an access-grant pre-check over these BEFORE `run`\n * (R7): any path outside the granted roots yields an `input_required`\n * round-trip requesting a grant, and nothing is touched until the client\n * retries with an accepted grant (R8). Omit for tools that do not operate on\n * caller-supplied filesystem paths.\n */\n readonly accessPaths?: (args: z.infer<I>) => readonly string[];\n readonly run: (args: z.infer<I>, ctx: ToolCtx) => Promise<RunResult<O> | InputRequiredResult>;\n /**\n * What the stdio size refusal tells the caller to do instead, for a tool\n * that knows better than the generic advice (see `refuseOversized`).\n */\n readonly oversizeRemedy?: (result: RunResult<O>) => string;\n}\n\nexport interface DefinedTool {\n readonly name: string;\n readonly readOnlyHint: boolean;\n\n register(deps: ToolDeps): RegisteredTool;\n}\n\nfunction toToolCtx(ctx: ServerContext, deps: ToolDeps): Omit<ToolCtx, 'log' | 'onProgress'> {\n // Envelope first, accessor second — the two eras carry this differently.\n // A modern request states the capabilities in its own `_meta` envelope; a\n // legacy connection fixed them at `initialize` and has no envelope at all.\n // The deprecated accessor still answers for both today (the SDK backfills it\n // per request from the validated envelope on modern instances), but reading\n // the envelope directly is the supported path, so it leads: when the accessor\n // goes, legacy degrades to \"cannot tell\", which fails open to the behavior\n // that predates this check.\n //\n // The cast is the SDK's shipped `RequestMetaEnvelope` declaration collapsing\n // to `{}` — the reserved keys survive at runtime but not in the .d.ts, so the\n // key constant cannot index the declared type.\n const envelope = ctx.mcpReq.envelope as Record<string, unknown> | undefined;\n const clientCapabilities =\n (envelope?.[CLIENT_CAPABILITIES_META_KEY] as ClientCapabilities | undefined) ??\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the only source of client capabilities on a legacy connection, where no envelope exists.\n deps.server.server.getClientCapabilities() ??\n // A legacy instance that never saw `initialize` is the HTTP leg's\n // per-request serving (`createMcpHandler` with `legacy: 'stateless'`):\n // there is no return path for a server-to-client request, so read the\n // client as having declared nothing. The `input_required` flows then\n // answer with their named workaround instead of the SDK's generic refusal.\n // sunset(SEP-2577): removal trigger in docs/adr/002-legacy-protocol-paths-sunset.md.\n (deps.era === 'legacy' ? {} : undefined);\n\n return {\n signal: ctx.mcpReq.signal,\n requestId: ctx.mcpReq.id,\n fs: new GuardedFileSystem(deps.pathGuard),\n pageStore: deps.pageStore,\n resourceStore: deps.resourceStore,\n inputResponses: ctx.mcpReq.inputResponses,\n droppedInputResponseKeys: ctx.mcpReq.droppedInputResponseKeys,\n requestState: ctx.mcpReq.requestState,\n serverCtx: ctx,\n ...(clientCapabilities ? { clientCapabilities } : {}),\n ...(deps.transport ? { transport: deps.transport } : {}),\n };\n}\n\n/**\n * Claude Code — and any client that treats `structuredContent` as the canonical\n * model view — discards the `text` blocks when `structuredContent` is present,\n * showing the model `JSON.stringify(structuredContent)` instead. A tool that\n * authored a text result (list's ASCII tree, read's file) meant that text for\n * the model, so it ships its metadata under `_meta`, which no client renders in\n * place of the content. Tools with no `text` keep `structuredContent`: the JSON\n * *is* their model-facing view.\n */\nfunction buildSuccessResponse<O extends object>(result: RunResult<O>): CallToolResult {\n const hasText = result.text !== undefined;\n const text = result.text ?? JSON.stringify(result.structured);\n const content: ContentBlock[] = [{ type: 'text' as const, text }, ...(result.resources ?? [])];\n return {\n content,\n ...(hasText // Result interfaces have named fields; the SDK metadata requires an index signature.\n ? { _meta: result.structured as Record<string, unknown> }\n : { structuredContent: result.structured }),\n ...(result.isError ? { isError: true } : {}),\n };\n}\n\nclass ToolExecutor<I extends z.ZodType, O extends object> {\n readonly signal: AbortSignal;\n private readonly def: ToolDef<I, O>;\n private readonly parsedArgs: z.infer<I>;\n private readonly toolCtx: ToolCtx;\n\n readonly #progressCtx: ProgressCtx;\n readonly #progressSession: ProgressSession;\n\n constructor(\n toolName: string,\n ctx: Omit<ToolCtx, 'log' | 'onProgress'>,\n def: ToolDef<I, O>,\n parsedArgs: z.infer<I>,\n ) {\n this.def = def;\n this.parsedArgs = parsedArgs;\n this.signal = def.timeoutMs\n ? AbortSignal.any([ctx.signal, AbortSignal.timeout(def.timeoutMs)])\n : ctx.signal;\n this.#progressCtx = def.progress ? def.progress(parsedArgs) : { label: def.title };\n const { mcpReq } = ctx.serverCtx;\n const token = mcpReq._meta?.progressToken;\n const notify = async (notification: Notification): Promise<void> => mcpReq.notify(notification);\n this.#progressSession = new ProgressSession({\n label: this.#progressCtx.label,\n ...(token !== undefined ? { sink: { toolName, token, notify } } : {}),\n });\n const traceparent = mcpReq._meta?.[TRACEPARENT_META_KEY];\n this.toolCtx = {\n ...ctx,\n signal: this.signal,\n // Per-call views, so a response refused after `run` can take back the\n // cached result and page snapshot behind a link or cursor it never sent.\n pageStore: ctx.pageStore.forCall(),\n resourceStore: ctx.resourceStore.forCall(),\n log: (level: LoggingLevel, data: unknown, logger?: string) => {\n const msg = typeof data === 'string' ? data : String(data);\n // `[req <id>]` first so one grep finds every line of one call; the\n // traceparent rides along only when the client sent one. Both are\n // client-supplied, so they pass through `sanitizeLogField`: a control\n // character in a JSON-RPC id or a traceparent would forge log lines.\n // The message is flattened too (uncapped): it can carry a resolved\n // path or OS error text, and input schemas reject CR/LF but not the\n // Unicode line separators.\n const trace = typeof traceparent === 'string' ? ` ${sanitizeLogField(traceparent)}` : '';\n const prefix = logger ? `[${logger}] ` : '';\n const text = sanitizeLogField(msg, Infinity);\n Logger.emit(\n level,\n `[req ${sanitizeLogField(String(ctx.requestId))}${trace}] ${prefix}${text}`,\n );\n },\n onProgress: (p) => {\n this.#tick(p);\n },\n };\n }\n\n #tick(p: { current: number; total?: number }): void {\n const tickCtx: ProgressCtx = {\n ...this.#progressCtx,\n current: p.current,\n ...(p.total !== undefined ? { total: p.total } : {}),\n };\n this.#progressSession.set({ ...p, message: plainMessage('tick', tickCtx) });\n }\n\n private completeProgress(result: O): void {\n const doneCtx: ProgressCtx = this.def.progressDone\n ? { ...this.#progressCtx, ...this.def.progressDone(this.parsedArgs, result) }\n : this.#progressCtx;\n this.#progressSession.complete(plainMessage('done', doneCtx));\n }\n\n private failProgress(error: unknown): { isError: true; content: ContentBlock[] } {\n const errMsg = formatUnknownErrorMessage(error);\n this.#progressSession.fail(plainMessage('fail', { ...this.#progressCtx, error: errMsg }));\n const errorText = Problem.toText(error, this.def.defaultErrorCode ?? ErrorCode.UNKNOWN);\n return {\n content: [{ type: 'text' as const, text: errorText }],\n isError: true,\n };\n }\n\n /**\n * Access-grant pre-check (R7/R8/R9). Before `run` touches the filesystem,\n * ask PathGuard which of the tool's declared paths are out-of-root and\n * grantable. If any are and this round carries no verified `requestState`,\n * return `input_required` (nothing is read or written — R7). On retry, the\n * verified state must bind this grant set (R9); apply each accepted grant for\n * the session (R8) and proceed. A declined or ungrantable path is left for\n * `validateAccess` to fail closed during the operation. Returns `undefined`\n * when no round-trip is needed and any applicable grants have been applied.\n */\n private async precheckGrant(): Promise<InputRequiredResult | undefined> {\n const extract = this.def.accessPaths;\n if (!extract) return undefined;\n const paths = extract(this.parsedArgs);\n if (paths.length === 0) return undefined;\n const grantDirs = await this.toolCtx.fs.pathGuard.precheckAccess(paths);\n if (grantDirs.length === 0) return undefined;\n\n // One grant dir: a single boolean confirm. Multiple: one multi-select\n // elicitation so the client picks the subset to allow in one round-trip\n // (N dirs → 1 round-trip, not N). `pendingRoundTrip` still binds\n // `paths: grantDirs` sorted, so R9 path-binding is unaffected.\n const multi = grantDirs.length > 1;\n const round = await pendingRoundTrip(this.toolCtx, {\n op: 'grant',\n pending: grantDirs,\n buildInputs: (dirs) =>\n multi\n ? [\n {\n key: 'grant',\n message: 'Grant filesystem access to these directories? Select the ones to allow.',\n choices: dirs,\n multi: true,\n },\n ]\n : dirs.map((dir, i) => ({\n key: confirmKey(i),\n message: `Grant filesystem access to \"${dir}\"?`,\n })),\n });\n if (round !== undefined) return round;\n // Apply accepted grants for the session (R8). Declined/missing dirs are\n // skipped here; their paths fail with ACCESS_DENIED during the operation.\n //\n // No list-changed notification follows: a grant widens the allowed roots,\n // and no resource list reads them. The instructions resource has a fixed\n // URI, the result template lists the ResourceStore, and the file template\n // lists nothing at all (see resources.ts). Notifying here only bought the\n // client a round trip to re-fetch a list that could not have changed.\n //\n // `readAcceptedMultiChoice` does NOT validate against the offered choices\n // (attacker-controlled inputResponses on re-entry). Only grant dirs that\n // were actually offered by precheckAccess — a value outside grantDirs is\n // ignored and fails closed in validateAccess. The single-select path reads\n // `confirmKey(i)` for `grantDirs[i]`, so the isSamePath filter is a no-op\n // there; it only bites for the multi-select array.\n const accepted = multi\n ? (readAcceptedMultiChoice(this.toolCtx.inputResponses, 'grant') ?? [])\n : grantDirs.filter((_dir, i) =>\n readAcceptedConfirm(this.toolCtx.inputResponses, confirmKey(i)),\n );\n for (const dir of accepted) {\n if (!grantDirs.some((g) => isSamePath(g, dir))) continue;\n await this.toolCtx.fs.pathGuard.applyGrant(dir);\n }\n return undefined;\n }\n\n /**\n * stdio's SDK reader drops the connection on a message past 10 MiB, so a\n * response that would overflow it becomes TOO_LARGE instead. Only a call\n * that changed nothing can be refused after `run` — a read-only tool, or a\n * dry run (every tool with `dryRun` writes nothing under it); a mutation may\n * already have committed. The whole encoded response counts, duplicated\n * metadata and escaping included; the ceiling leaves room for the envelope.\n */\n private refuseOversized(result: RunResult<O>, response: CallToolResult): void {\n if (this.toolCtx.transport !== 'stdio') return;\n const dryRun = (this.parsedArgs as { dryRun?: unknown }).dryRun === true;\n if (!this.def.readOnlyHint && !dryRun) return;\n const encodedBytes = jsonBytesOver(response, MAX_OUTBOUND_RESULT_BYTES);\n if (encodedBytes === undefined) return;\n // The client never receives the link or cursor these back, so they would\n // only push live entries out of the stores' caps.\n this.toolCtx.resourceStore.discard();\n this.toolCtx.pageStore.discard();\n const remedy =\n this.def.oversizeRemedy?.(result) ??\n (dryRun\n ? 'Nothing was written. Preview fewer files or a smaller file per call, or connect over HTTP.'\n : 'Reduce the requested output or connect over HTTP.');\n // The remedy stands in for TOO_LARGE's default head/tail advice, which\n // fits neither media nor a dry run.\n throw new FsError(\n ErrorCode.TOO_LARGE,\n `${this.def.name} result too large to return (${String(encodedBytes)} bytes once JSON-encoded, over the ${String(MAX_OUTBOUND_RESULT_BYTES)}-byte stdio message limit).`,\n undefined,\n undefined,\n remedy,\n );\n }\n\n async execute(): Promise<CallToolResult | InputRequiredResult> {\n try {\n // Access-grant pre-check before any filesystem touch (R7/R8/R9). A\n // grant input_required short-circuits here (progress paused, not\n // finished); an R9 mismatch throws, which this catch surfaces as an\n // isError tool result like every other handler failure — not a raw\n // JSON-RPC error (GRANT-1 impact #2).\n const grantRequired = await this.precheckGrant();\n if (grantRequired !== undefined) return grantRequired;\n const result = await this.def.run(this.parsedArgs, this.toolCtx);\n // input_required is a return value, not a completed call: the client\n // retries the same tools/call carrying inputResponses, and this\n // handler re-enters from the top. Skip the progress \"done\" close and\n // return it verbatim — progress is paused, not finished.\n if (isInputRequiredResult(result)) {\n return result;\n }\n const response = buildSuccessResponse(result);\n this.refuseOversized(result, response);\n this.completeProgress(result.structured);\n return response;\n } catch (error) {\n return this.failProgress(error);\n } finally {\n await this.#progressSession.flush();\n }\n }\n}\n\nexport function defineTool<I extends z.ZodType, O extends object>(def: ToolDef<I, O>): DefinedTool {\n // Nothing here depends on `deps`, so it is built once per tool definition\n // rather than once per `register` — the HTTP leg registers every tool afresh\n // on each request.\n // Filesystem tools are closed-world; only mutating tools are destructive.\n const publishedAnnotations: ToolAnnotations = {\n readOnlyHint: def.readOnlyHint,\n openWorldHint: false,\n ...(def.readOnlyHint ? {} : { destructiveHint: true }),\n };\n\n const toolDefShape = {\n title: def.title,\n description: def.description,\n // The Zod schema goes in behind `withSplitArgsRecovery` only: the SDK\n // validates with it and publishes its own draft-2020-12 conversion in\n // `tools/list`, which the preprocess step leaves unchanged. The cast only\n // names the in/out types a generic `ZodType` cannot surface through\n // `~standard`.\n inputSchema: withSplitArgsRecovery(def.input) as unknown as StandardSchemaWithJSON<\n z.input<I>,\n z.output<I>\n >,\n // No `outputSchema`, ever. Publishing one obliges the result to carry\n // `structuredContent` (clients enforce it), and every tool that authors its\n // own text ships its metadata under `_meta` instead — see\n // `buildSuccessResponse`. The two cannot both hold, and the text is what\n // the model reads. `TOOL-SURFACE-001` pins this for the whole surface.\n // Result shapes are checked by TypeScript, not unused runtime schemas.\n annotations: publishedAnnotations,\n };\n\n return {\n name: def.name,\n readOnlyHint: def.readOnlyHint,\n\n register(deps: ToolDeps): RegisteredTool {\n return deps.server.registerTool(def.name, toolDefShape, async (args, ctx) =>\n new ToolExecutor<I, O>(def.name, toToolCtx(ctx, deps), def, args).execute(),\n );\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delete.d.ts","sourceRoot":"","sources":["../../src/tools/delete.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"delete.d.ts","sourceRoot":"","sources":["../../src/tools/delete.ts"],"names":[],"mappings":"AAiYA,eAAO,MAAM,MAAM,mCA4CjB,CAAC"}
|
package/dist/tools/delete.js
CHANGED
|
@@ -4,7 +4,7 @@ import * as z from 'zod/v4';
|
|
|
4
4
|
import { processInParallel } from "../core/concurrency.js";
|
|
5
5
|
import { ErrorCode, FsError, isFsError, isNodeError, isNotFoundErrno, Problem, } from "../core/errors.js";
|
|
6
6
|
import { joinRoster, pathLabel } from "../core/fmt.js";
|
|
7
|
-
import { confirmKey,
|
|
7
|
+
import { confirmKey, pendingRoundTrip, readPendingVerdict, } from "../core/input-required.js";
|
|
8
8
|
import { resolveEntryType } from "../core/path-utils.js";
|
|
9
9
|
import { defaultFalseBoolean, RequiredPath } from "../core/schema.js";
|
|
10
10
|
import { PARALLEL_CONCURRENCY } from "../core/util.js";
|
|
@@ -91,20 +91,13 @@ async function planPath(inputPath, args, fs) {
|
|
|
91
91
|
return { status: 'fail', failure: toDeleteFailure(inputPath, error) };
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
if (isDirectory && !args.recursive) {
|
|
99
|
-
await fsOps.rmdir(validPath);
|
|
100
|
-
}
|
|
101
|
-
else {
|
|
102
|
-
await fsOps.rm(validPath, {
|
|
103
|
-
recursive: args.recursive,
|
|
104
|
-
force: args.ignoreIfNotExists,
|
|
105
|
-
});
|
|
106
|
-
}
|
|
94
|
+
return {
|
|
95
|
+
status: 'plan',
|
|
96
|
+
plan: { inputPath, validPath, itemType, firstStats, pending: hasChildren },
|
|
97
|
+
};
|
|
107
98
|
}
|
|
99
|
+
/** Same filesystem object. birthtimeMs joins dev/ino, which read 0 on some non-POSIX drivers. */
|
|
100
|
+
const sameIdentity = (a, b) => a.dev === b.dev && a.ino === b.ino && a.birthtimeMs === b.birthtimeMs;
|
|
108
101
|
/**
|
|
109
102
|
* Phase 2 (mutation): TOCTOU re-stat against the plan's first stat, then
|
|
110
103
|
* delete. A type or identity change across the confirmation gap fails closed
|
|
@@ -127,9 +120,7 @@ async function finalizeDeletion(plan, args, ctx) {
|
|
|
127
120
|
// the type but changes dev/ino/birthtimeMs. birthtimeMs is the primary
|
|
128
121
|
// cross-platform signal — dev/ino can read 0 on some non-POSIX drivers — so
|
|
129
122
|
// combine all three rather than trusting dev/ino alone.
|
|
130
|
-
const identityChanged = plan.firstStats.stats
|
|
131
|
-
plan.firstStats.stats.ino !== currentStats.stats.ino ||
|
|
132
|
-
plan.firstStats.stats.birthtimeMs !== currentStats.stats.birthtimeMs;
|
|
123
|
+
const identityChanged = !sameIdentity(plan.firstStats.stats, currentStats.stats);
|
|
133
124
|
if (plan.itemType !== 'other' && (currentItemType !== plan.itemType || identityChanged)) {
|
|
134
125
|
return {
|
|
135
126
|
failure: {
|
|
@@ -139,7 +130,10 @@ async function finalizeDeletion(plan, args, ctx) {
|
|
|
139
130
|
};
|
|
140
131
|
}
|
|
141
132
|
try {
|
|
142
|
-
|
|
133
|
+
if (currentStats.stats.isDirectory() && !args.recursive)
|
|
134
|
+
await ctx.fs.rmdir(plan.validPath);
|
|
135
|
+
else
|
|
136
|
+
await ctx.fs.rm(plan.validPath, { recursive: args.recursive, force: args.ignoreIfNotExists });
|
|
143
137
|
}
|
|
144
138
|
catch (error) {
|
|
145
139
|
return { failure: toDeleteFailure(plan.inputPath, error) };
|
|
@@ -153,18 +147,28 @@ async function finalizeDeletion(plan, args, ctx) {
|
|
|
153
147
|
* `CANCELLED` for that path (R3 proceed, R4/R5 cancelled). A non-pending path
|
|
154
148
|
* deletes directly (R14: non-pending items proceed alongside accepted ones).
|
|
155
149
|
*/
|
|
156
|
-
async function executePlan(plan, args, ctx, pendingSorted) {
|
|
150
|
+
async function executePlan(plan, args, ctx, pendingSorted, confirmationState) {
|
|
157
151
|
if (plan.pending) {
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
if (choice === 'skip') {
|
|
152
|
+
const verdict = readPendingVerdict(ctx, pendingSorted, plan.validPath, 'delete');
|
|
153
|
+
if (verdict === 'skipped') {
|
|
161
154
|
return { skipped: true, path: plan.validPath };
|
|
162
155
|
}
|
|
163
|
-
if (
|
|
156
|
+
if (verdict !== 'accepted') {
|
|
157
|
+
return {
|
|
158
|
+
failure: {
|
|
159
|
+
path: plan.validPath,
|
|
160
|
+
error: Problem.cancelled(`Delete cancelled: confirmation was ${verdict.refused}`, {
|
|
161
|
+
path: plan.validPath,
|
|
162
|
+
}),
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
const identity = confirmationState?.deleteIdentities?.find((entry) => entry.path === plan.validPath);
|
|
167
|
+
if (identity?.itemType !== plan.itemType || !sameIdentity(identity, plan.firstStats.stats)) {
|
|
164
168
|
return {
|
|
165
169
|
failure: {
|
|
166
170
|
path: plan.validPath,
|
|
167
|
-
error: Problem.
|
|
171
|
+
error: Problem.invalidInput('Delete failed: item identity changed or is missing from the confirmation.', { path: plan.validPath }),
|
|
168
172
|
},
|
|
169
173
|
};
|
|
170
174
|
}
|
|
@@ -179,13 +183,19 @@ async function handleDelete(args, ctx) {
|
|
|
179
183
|
const planned = await processInParallel(paths, (inputPath) => planPath(inputPath, args, ctx.fs), PARALLEL_CONCURRENCY, ctx.signal);
|
|
180
184
|
const out = new Array(paths.length).fill(undefined);
|
|
181
185
|
const plans = [];
|
|
186
|
+
const confirmationState = ctx.requestState?.();
|
|
187
|
+
const previouslyPendingPaths = new Set(confirmationState?.op === 'delete' ? confirmationState.paths : []);
|
|
182
188
|
for (const { index, value: r } of planned.results) {
|
|
183
189
|
if (r.status === 'fail')
|
|
184
190
|
out[index] = { path: r.failure.path, error: r.failure.error };
|
|
185
191
|
else if (r.status === 'noop')
|
|
186
192
|
out[index] = { path: r.deleted, value: { deleted: true } };
|
|
187
|
-
else
|
|
193
|
+
else {
|
|
194
|
+
// Emptying a directory while its prompt is open must not discard the
|
|
195
|
+
// answer. Keep that path pending so the verified retry still honors skip.
|
|
196
|
+
r.plan.pending ||= previouslyPendingPaths.has(r.plan.validPath);
|
|
188
197
|
plans.push({ plan: r.plan, index });
|
|
198
|
+
}
|
|
189
199
|
}
|
|
190
200
|
for (const { index, error } of planned.errors) {
|
|
191
201
|
out[index] = {
|
|
@@ -201,13 +211,22 @@ async function handleDelete(args, ctx) {
|
|
|
201
211
|
const pendingSorted = [
|
|
202
212
|
...new Set(plans.filter((p) => p.plan.pending).map((p) => p.plan.validPath)),
|
|
203
213
|
].sort();
|
|
204
|
-
|
|
214
|
+
// With no actionable plans, preserve per-path NOT_FOUND / ignoreIfNotExists
|
|
215
|
+
// results. Otherwise even an empty pending set must be checked before an
|
|
216
|
+
// unrelated non-pending batch entry can mutate.
|
|
217
|
+
if (pendingSorted.length > 0 || (confirmationState?.op === 'delete' && plans.length > 0)) {
|
|
205
218
|
// Round 1 returns input_required (atomic — R14: nothing deleted yet, not
|
|
206
219
|
// even the non-pending items in the same call); a retry whose verified
|
|
207
220
|
// state does not bind this pending set throws (R9) via `pendingRoundTrip`.
|
|
208
221
|
const round = await pendingRoundTrip(ctx, {
|
|
209
222
|
op: 'delete',
|
|
210
223
|
pending: pendingSorted,
|
|
224
|
+
deleteIdentities: plans
|
|
225
|
+
.filter(({ plan }) => plan.pending)
|
|
226
|
+
.map(({ plan }) => {
|
|
227
|
+
const { dev, ino, birthtimeMs } = plan.firstStats.stats;
|
|
228
|
+
return { path: plan.validPath, itemType: plan.itemType, dev, ino, birthtimeMs };
|
|
229
|
+
}),
|
|
211
230
|
buildInputs: (ps) => ps.map((p, i) => ({
|
|
212
231
|
key: confirmKey(i),
|
|
213
232
|
message: `Permanently delete "${p}" and all its contents? This cannot be undone.`,
|
|
@@ -218,7 +237,7 @@ async function handleDelete(args, ctx) {
|
|
|
218
237
|
return round;
|
|
219
238
|
}
|
|
220
239
|
// Phase 2 (mutation): execute deletions for every planned path.
|
|
221
|
-
const executed = await processInParallel(plans, ({ plan }) => executePlan(plan, args, ctx, pendingSorted), PARALLEL_CONCURRENCY, ctx.signal);
|
|
240
|
+
const executed = await processInParallel(plans, ({ plan }) => executePlan(plan, args, ctx, pendingSorted, confirmationState), PARALLEL_CONCURRENCY, ctx.signal);
|
|
222
241
|
for (const { index, value: r } of executed.results) {
|
|
223
242
|
const slot = plans[index]?.index;
|
|
224
243
|
if (slot === undefined)
|