@j0hanz/filesystem-mcp 2.0.0 → 2.1.0
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/core/config.d.ts +7 -0
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/config.js +7 -0
- package/dist/core/config.js.map +1 -1
- package/dist/core/fmt.d.ts +0 -1
- package/dist/core/fmt.d.ts.map +1 -1
- package/dist/core/fmt.js +0 -16
- package/dist/core/fmt.js.map +1 -1
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +4 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/util.d.ts +0 -2
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +1 -2
- package/dist/core/util.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/instructions.d.ts +0 -1
- package/dist/instructions.d.ts.map +1 -1
- package/dist/instructions.js +2 -3
- package/dist/instructions.js.map +1 -1
- package/dist/tools/create.d.ts.map +1 -1
- package/dist/tools/create.js +6 -24
- package/dist/tools/create.js.map +1 -1
- package/dist/tools/define.d.ts +0 -8
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +24 -14
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete-file.d.ts.map +1 -1
- package/dist/tools/delete-file.js +0 -3
- package/dist/tools/delete-file.js.map +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +0 -2
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +11 -1
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +32 -5
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-in-files.d.ts.map +1 -1
- package/dist/tools/replace-in-files.js +0 -3
- package/dist/tools/replace-in-files.js.map +1 -1
- package/dist/tools/roots.d.ts.map +1 -1
- package/dist/tools/roots.js +21 -5
- package/dist/tools/roots.js.map +1 -1
- package/dist/tools/stat.d.ts.map +1 -1
- package/dist/tools/stat.js +4 -17
- package/dist/tools/stat.js.map +1 -1
- package/package.json +1 -1
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,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EACL,QAAQ,EACR,WAAW,EACX,SAAS,EACT,iBAAiB,EACjB,YAAY,GACb,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,oBAAoB,GAAG,CAAC,CAAC,YAAY,CAAC;IAC1C,IAAI,EAAE,YAAY,CAAC,QAAQ,CAAC,8CAA8C,CAAC;IAC3E,OAAO,EAAE,CAAC;SACP,MAAM,EAAE;SACR,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,IAAI,kBAAkB,EAAE,EAAE;QACnD,OAAO,EAAE,gDAAgD;KAC1D,CAAC;SACD,QAAQ,CAAC,kCAAkC,CAAC;CAChD,CAAC,CAAC;AAEH,MAAM,sBA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E,CAAC;QACzD,CAAC;QAED,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IACvC,CAAC;IACD,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACnB,KAAK,EAAE,QAAQ;QACf,OAAO,EACL,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YACrB,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,IAAI,EAAE,CAAC;YACrC,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ;KAC3C,CAAC;IACF,gBAAgB,EAAE,SAAS,CAAC,OAAO;CACpC,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename, dirname } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode } from '../core/errors.js';\nimport { buildFileResourceLink, buildFileResourceUri } from '../core/file-uri.js';\nimport { formatBytes, joinRoster } from '../core/fmt.js';\nimport { detectMimeFromContent } from '../core/mime.js';\nimport { countLines } from '../core/read.js';\nimport {\n FileKind,\n IsoDateTime,\n NonNegInt,\n PathFailureSchema,\n RequiredPath,\n} from '../core/schema.js';\nimport { getMaxTextFileSize } from '../core/util.js';\nimport { runOverPaths } from './batch.js';\nimport { defineTool } from './define.js';\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});\n\nconst CreateFileResultSchema = z.strictObject({\n path: z.string().describe('Resolved absolute path of the created file'),\n size: NonNegInt.describe('File size in bytes after writing'),\n lineCount: NonNegInt.describe('Number of lines in the written file'),\n mimeType: z.string().describe('Detected MIME type of the file'),\n kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .describe('Resource URI pointing to the created file content in the resource store'),\n created: IsoDateTime.describe('File creation timestamp (ISO 8601 UTC)'),\n modified: IsoDateTime.describe('File last-modification timestamp (ISO 8601 UTC)'),\n});\n\nconst CreateInputSchema = z.strictObject({\n files: z\n .array(CreateFileItemSchema)\n .min(1)\n .max(100)\n .describe('List of files to create (max 100); each entry requires path and content'),\n});\n\ntype CreateFailureItem = z.infer<typeof PathFailureSchema>;\n\nconst CreateOutputSchema = z.strictObject({\n files: z.array(CreateFileResultSchema).describe('Successfully created files'),\n failures: z\n .array(PathFailureSchema)\n .optional()\n .describe('Files that failed to create with per-file error details'),\n});\n\ntype CreateFileResult = z.infer<typeof CreateFileResultSchema>;\n\nfunction buildSummary(results: readonly CreateFileResult[], failCount: number): string {\n if (results.length === 1 && failCount === 0) {\n const result = results[0];\n if (result) {\n return [\n `create: ${basename(result.path)}`,\n formatBytes(result.size),\n `${String(result.lineCount)} lines`,\n ].join(' \\u00b7 ');\n }\n }\n // Name what was written. \"create: 3 files\" made the caller open\n // structuredContent to learn which three \\u2014 every other write tool answers\n // with its roster.\n const names = joinRoster(results.map((r) => basename(r.path)));\n const parts = [`create: ${names || 'nothing'}`];\n if (failCount > 0) parts.push(`${String(failCount)} failed`);\n return parts.join(' \\u00b7 ');\n}\n\nexport const CREATE = defineTool({\n name: 'create',\n title: 'Create Files',\n description:\n 'Create one or more files (max 100), writing or overwriting content and creating parent directories as needed. ' +\n 'Pass files: [{ path, content }] — there is no single-path form. ' +\n 'Silently overwrites existing files — read first if you need to preserve existing content.',\n input: CreateInputSchema,\n output: CreateOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n accessPaths: (args) => args.files.map((f) => f.path),\n run: async (args, ctx) => {\n const batch = await runOverPaths<\n { content: string },\n { file: CreateFileResult; resourceLink?: ContentBlock }\n >(\n { files: args.files },\n ctx,\n async ({ path, override }) => {\n const content = override?.content ?? '';\n\n await ctx.fs.mkdir(dirname(path), { recursive: true });\n\n const { validPath } = await ctx.fs.writeFile(path, content, {\n encoding: 'utf-8',\n signal: ctx.signal,\n });\n\n const { stats: fileStats } = await ctx.fs.stat(path, { signal: ctx.signal });\n const bytesWritten = Buffer.byteLength(content, 'utf-8');\n const lineCount = countLines(content);\n const mimeInfo = detectMimeFromContent(validPath, content);\n\n const resourceUri = buildFileResourceUri(validPath);\n const file: CreateFileResult = {\n path: validPath,\n size: bytesWritten,\n lineCount,\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n resourceUri,\n created: fileStats.birthtime.toISOString(),\n modified: fileStats.mtime.toISOString(),\n };\n\n return ctx.resourceStore\n ? {\n file,\n resourceLink: buildFileResourceLink(validPath, mimeInfo.mimeType, bytesWritten),\n }\n : { file };\n },\n { defaultErrorCode: ErrorCode.UNKNOWN },\n );\n\n const results: CreateFileResult[] = [];\n const failures: CreateFailureItem[] = [];\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 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 };\n const summary = buildSummary(results, failures.length);\n\n if (links.length > 0) {\n return { structured, text: summary, resources: links };\n }\n\n return { structured, text: 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 defaultErrorCode: ErrorCode.UNKNOWN,\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,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,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I,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YACrB,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,IAAI,EAAE,CAAC;YACrC,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ;KAC3C,CAAC;IACF,gBAAgB,EAAE,SAAS,CAAC,OAAO;CACpC,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename, dirname } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode } from '../core/errors.js';\nimport { buildFileResourceLink, buildFileResourceUri } from '../core/file-uri.js';\nimport { detectMimeFromContent } from '../core/mime.js';\nimport { countLines } from '../core/read.js';\nimport {\n FileKind,\n IsoDateTime,\n NonNegInt,\n PathFailureSchema,\n RequiredPath,\n} from '../core/schema.js';\nimport { getMaxTextFileSize } from '../core/util.js';\nimport { runOverPaths } from './batch.js';\nimport { defineTool } from './define.js';\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});\n\nconst CreateFileResultSchema = z.strictObject({\n path: z.string().describe('Resolved absolute path of the created file'),\n size: NonNegInt.describe('File size in bytes after writing'),\n lineCount: NonNegInt.describe('Number of lines in the written file'),\n mimeType: z.string().describe('Detected MIME type of the file'),\n kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .describe('Resource URI pointing to the created file content in the resource store'),\n created: IsoDateTime.describe('File creation timestamp (ISO 8601 UTC)'),\n modified: IsoDateTime.describe('File last-modification timestamp (ISO 8601 UTC)'),\n});\n\nconst CreateInputSchema = z.strictObject({\n files: z\n .array(CreateFileItemSchema)\n .min(1)\n .max(100)\n .describe('List of files to create (max 100); each entry requires path and content'),\n});\n\ntype CreateFailureItem = z.infer<typeof PathFailureSchema>;\n\nconst CreateOutputSchema = z.strictObject({\n files: z.array(CreateFileResultSchema).describe('Successfully created files'),\n failures: z\n .array(PathFailureSchema)\n .optional()\n .describe('Files that failed to create with per-file error details'),\n});\n\ntype CreateFileResult = z.infer<typeof CreateFileResultSchema>;\n\nexport const CREATE = defineTool({\n name: 'create',\n title: 'Create Files',\n description:\n 'Create one or more files (max 100), writing or overwriting content and creating parent directories as needed. ' +\n 'Pass files: [{ path, content }] — there is no single-path form. ' +\n 'Silently overwrites existing files — read first if you need to preserve existing content.',\n input: CreateInputSchema,\n output: CreateOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n accessPaths: (args) => args.files.map((f) => f.path),\n run: async (args, ctx) => {\n const batch = await runOverPaths<\n { content: string },\n { file: CreateFileResult; resourceLink?: ContentBlock }\n >(\n { files: args.files },\n ctx,\n async ({ path, override }) => {\n const content = override?.content ?? '';\n\n await ctx.fs.mkdir(dirname(path), { recursive: true });\n\n const { validPath } = await ctx.fs.writeFile(path, content, {\n encoding: 'utf-8',\n signal: ctx.signal,\n });\n\n const { stats: fileStats } = await ctx.fs.stat(path, { signal: ctx.signal });\n const bytesWritten = Buffer.byteLength(content, 'utf-8');\n const lineCount = countLines(content);\n const mimeInfo = detectMimeFromContent(validPath, content);\n\n const resourceUri = buildFileResourceUri(validPath);\n const file: CreateFileResult = {\n path: validPath,\n size: bytesWritten,\n lineCount,\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n resourceUri,\n created: fileStats.birthtime.toISOString(),\n modified: fileStats.mtime.toISOString(),\n };\n\n return ctx.resourceStore\n ? {\n file,\n resourceLink: buildFileResourceLink(validPath, mimeInfo.mimeType, bytesWritten),\n }\n : { file };\n },\n { defaultErrorCode: ErrorCode.UNKNOWN },\n );\n\n const results: CreateFileResult[] = [];\n const failures: CreateFailureItem[] = [];\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 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 };\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 };\n }\n\n return { structured };\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 defaultErrorCode: ErrorCode.UNKNOWN,\n});\n"]}
|
package/dist/tools/define.d.ts
CHANGED
|
@@ -90,14 +90,6 @@ export interface ToolDef<I extends z.ZodType, O extends z.ZodType> {
|
|
|
90
90
|
* caller-supplied filesystem paths.
|
|
91
91
|
*/
|
|
92
92
|
readonly accessPaths?: (args: z.infer<I>) => readonly string[];
|
|
93
|
-
/**
|
|
94
|
-
* Publish `output` as the tool's wire `outputSchema`. Off by default: the
|
|
95
|
-
* spec makes the field optional and it costs more than every other part of
|
|
96
|
-
* a tool entry combined. Turn it on only where the shape is not inferable —
|
|
97
|
-
* a discriminated per-path union, or a field that appears under one flag and
|
|
98
|
-
* not another. The Zod object still validates every result either way.
|
|
99
|
-
*/
|
|
100
|
-
readonly publishOutputSchema?: boolean;
|
|
101
93
|
readonly run: (args: z.infer<I>, ctx: ToolCtx) => Promise<RunResult<z.infer<O>> | InputRequiredResult>;
|
|
102
94
|
}
|
|
103
95
|
export interface DefinedTool {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.d.ts","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,QAAQ,EAER,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EAInB,SAAS,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AC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,SAAS,MAAM,EAAE,CAAC;IAC/D,QAAQ,CAAC,GAAG,EAAE,CACZ,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAChB,GAAG,EAAE,OAAO,KACT,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAAC,CAAC;CAC3D;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,EAAE,mBAAmB,CAAC;IAE1C,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,cAAc,CAAC;CAC1C;AAuYD,wBAAgB,UAAU,CAAC,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC,OAAO,EACjE,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,GACjB,WAAW,CA4Cb"}
|
package/dist/tools/define.js
CHANGED
|
@@ -94,17 +94,28 @@ function isTotalBatchFailure(structured) {
|
|
|
94
94
|
return len(result.files) + len(result.moves) + len(result.skipped) === 0;
|
|
95
95
|
}
|
|
96
96
|
/**
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
97
|
+
* Claude Code — and any client that treats `structuredContent` as the canonical
|
|
98
|
+
* model view — discards the `text` blocks when `structuredContent` is present,
|
|
99
|
+
* showing the model `JSON.stringify(structuredContent)` instead. A tool that
|
|
100
|
+
* authored a text result (list's ASCII tree, read's file) meant that text for
|
|
101
|
+
* the model, so it ships its metadata under `_meta`, which no client renders in
|
|
102
|
+
* place of the content. Tools with no `text` keep `structuredContent`: the JSON
|
|
103
|
+
* *is* their model-facing view.
|
|
101
104
|
*/
|
|
102
105
|
function buildSuccessResponse(result) {
|
|
106
|
+
const hasText = result.text !== undefined;
|
|
103
107
|
const text = result.text ?? JSON.stringify(result.structured);
|
|
104
108
|
const content = [{ type: 'text', text }, ...(result.resources ?? [])];
|
|
105
109
|
return {
|
|
106
110
|
content,
|
|
107
|
-
|
|
111
|
+
...(hasText
|
|
112
|
+
? // Safe because every `ToolDef.output` is a Zod object schema, so
|
|
113
|
+
// `structured` is always a plain object. Constraining `O` to prove it
|
|
114
|
+
// is not worth the cost: the bound has to thread through five generic
|
|
115
|
+
// sites and still loses to `exactOptionalPropertyTypes` variance on
|
|
116
|
+
// `RunResult`'s optional fields.
|
|
117
|
+
{ _meta: result.structured }
|
|
118
|
+
: { structuredContent: result.structured }),
|
|
108
119
|
...(isTotalBatchFailure(result.structured) ? { isError: true } : {}),
|
|
109
120
|
};
|
|
110
121
|
}
|
|
@@ -352,7 +363,6 @@ function toDraft202012(schema, io) {
|
|
|
352
363
|
}
|
|
353
364
|
export function defineTool(def) {
|
|
354
365
|
const inputJsonSchema = toDraft202012(def.input, 'input');
|
|
355
|
-
const outputJsonSchema = toDraft202012(def.output, 'output');
|
|
356
366
|
// Nothing here depends on `deps`, so it is built once per tool definition
|
|
357
367
|
// rather than once per `register` — the HTTP leg registers every tool afresh
|
|
358
368
|
// on each request.
|
|
@@ -372,14 +382,14 @@ export function defineTool(def) {
|
|
|
372
382
|
title: def.title,
|
|
373
383
|
description: def.description,
|
|
374
384
|
inputSchema: fromJsonSchema(inputJsonSchema, zodJsonSchemaValidator(def.input)),
|
|
375
|
-
//
|
|
376
|
-
//
|
|
377
|
-
//
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
385
|
+
// No `outputSchema`, ever. Publishing one obliges the result to carry
|
|
386
|
+
// `structuredContent` (clients enforce it), and every tool that authors its
|
|
387
|
+
// own text ships its metadata under `_meta` instead — see
|
|
388
|
+
// `buildSuccessResponse`. The two cannot both hold, and the text is what
|
|
389
|
+
// the model reads. `TOOL-SURFACE-001` pins this for the whole surface.
|
|
390
|
+
//
|
|
391
|
+
// `def.output` stays: it types `RunResult<z.infer<O>>`, which is what makes
|
|
392
|
+
// a tool returning the wrong shape a compile error.
|
|
383
393
|
annotations: publishedAnnotations,
|
|
384
394
|
};
|
|
385
395
|
const tool = {
|
package/dist/tools/define.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAiBA,OAAO,EACL,4BAA4B,EAC5B,cAAc,EACd,qBAAqB,GACtB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,yBAAyB,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAElF,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAGlD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAInD,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAyGjE,SAAS,SAAS,CAChB,GAA8B,EAC9B,IAA4E;IAE5E,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;QAC5C,OAAO;YACL,MAAM;YACN,EAAE,EAAE,IAAI,iBAAiB,CAAC,IAAI,CAAC,SAAS,CAAC;YACzC,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC;IACJ,CAAC;IACD,yEAAyE;IACzE,0EAA0E;IAC1E,2EA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a,eAAe,EAAE,sBAAsB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC3F,4EAA4E;QAC5E,2EAA2E;QAC3E,wDAAwD;QACxD,GAAG,CAAC,GAAG,CAAC,mBAAmB;YACzB,CAAC,CAAC;gBACE,YAAY,EAAE,cAAc,CAC1B,gBAAgB,EAChB,sBAAsB,CAAC,GAAG,CAAC,MAAM,CAAC,CACnC;aACF;YACH,CAAC,CAAC,EAAE,CAAC;QACP,WAAW,EAAE,oBAAoB;KAClC,CAAC;IAEF,MAAM,IAAI,GAAgB;QACxB,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,WAAW,EAAE,GAAG,CAAC,WAAW;QAE5B,QAAQ,CAAC,IAAc;YACrB,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,EAAE,YAAY,EAAE,uBAAuB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9F,CAAC;KACF,CAAC;IAEF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n AuthInfo,\n CallToolResult,\n ClientCapabilities,\n ContentBlock,\n InputRequiredResult,\n JsonSchemaType,\n JsonSchemaValidator,\n jsonSchemaValidator,\n McpServer,\n Notification,\n RegisteredTool,\n RequestMeta,\n RequestStateAccessor,\n ServerContext,\n ToolAnnotations,\n} from '@modelcontextprotocol/server';\nimport {\n CLIENT_CAPABILITIES_META_KEY,\n fromJsonSchema,\n isInputRequiredResult,\n} from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, formatUnknownErrorMessage, Problem } from '../core/errors.js';\nimport type { ProgressCtx } from '../core/fmt.js';\nimport { plainMessage } from '../core/fmt.js';\nimport { GuardedFileSystem } from '../core/fs.js';\nimport {\n confirmInput,\n multiSelectInput,\n pendingRoundTrip,\n readAcceptedConfirm,\n readAcceptedMultiChoice,\n} from '../core/input-required.js';\nimport { Logger } from '../core/observability.js';\nimport type { LoggingLevel } from '../core/observability.js';\nimport type { PageSnapshotStore } from '../core/page-store.js';\nimport { isSamePath } from '../core/path-utils.js';\nimport type { PathGuard } from '../core/path.js';\nimport type { ResourceStore } from '../core/store.js';\nimport type { ProgressSink } from './progress.js';\nimport { McpProgressSink, ProgressSession } from './progress.js';\n\nexport interface ToolCtx {\n readonly signal: AbortSignal;\n readonly sessionId?: string;\n readonly authInfo?: AuthInfo;\n readonly _meta?: RequestMeta | undefined;\n readonly fs: GuardedFileSystem;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore | undefined;\n /** Emits a log line to stderr via `Logger.emit`, gated by `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 * 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 readonly server?: McpServer;\n}\n\ninterface ToolDeps {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore | undefined;\n}\n\ninterface RunResult<T> {\n readonly structured: T;\n readonly text?: string;\n readonly resources?: ContentBlock[];\n}\n\n/**\n * `ToolAnnotations` with `readOnlyHint` required. It is optional in the SDK, but\n * MUTATING_TOOL_NAMES derives the `--read-only` gate from it, so a tool that\n * forgets it must be a compile error rather than a silent reclassification.\n */\ntype DeclaredAnnotations = ToolAnnotations & { readonly readOnlyHint: boolean };\n\nexport interface ToolDef<I extends z.ZodType, O extends z.ZodType> {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly input: I;\n readonly output: O;\n readonly annotations: DeclaredAnnotations;\n readonly timeoutMs?: number;\n readonly progress?: (args: z.infer<I>) => ProgressCtx;\n readonly progressDone?: (args: z.infer<I>, result: z.infer<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 /**\n * Publish `output` as the tool's wire `outputSchema`. Off by default: the\n * spec makes the field optional and it costs more than every other part of\n * a tool entry combined. Turn it on only where the shape is not inferable —\n * a discriminated per-path union, or a field that appears under one flag and\n * not another. The Zod object still validates every result either way.\n */\n readonly publishOutputSchema?: boolean;\n readonly run: (\n args: z.infer<I>,\n ctx: ToolCtx,\n ) => Promise<RunResult<z.infer<O>> | InputRequiredResult>;\n}\n\nexport interface DefinedTool {\n readonly name: string;\n readonly annotations: DeclaredAnnotations;\n\n register(deps: ToolDeps): RegisteredTool;\n}\n\nfunction toToolCtx(\n ctx: ServerContext | undefined,\n deps: Pick<ToolDeps, 'pathGuard' | 'pageStore' | 'resourceStore' | 'server'>,\n): ToolCtx {\n if (!ctx) {\n const signal = new AbortController().signal;\n return {\n signal,\n fs: new GuardedFileSystem(deps.pathGuard),\n pageStore: deps.pageStore,\n resourceStore: deps.resourceStore,\n server: deps.server,\n };\n }\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\n return {\n signal: ctx.mcpReq.signal,\n ...(ctx.sessionId ? { sessionId: ctx.sessionId } : {}),\n ...(ctx.http?.authInfo ? { authInfo: ctx.http.authInfo } : {}),\n ...(ctx.mcpReq._meta ? { _meta: ctx.mcpReq._meta } : {}),\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 requestState: ctx.mcpReq.requestState,\n ...(clientCapabilities ? { clientCapabilities } : {}),\n server: deps.server,\n };\n}\n\nfunction resolveProgressCtx<I extends z.ZodType, O extends z.ZodType>(\n def: ToolDef<I, O>,\n args: z.infer<I>,\n): ProgressCtx {\n if (!def.progress) return { label: def.title };\n try {\n return def.progress(args);\n } catch (err: unknown) {\n Logger.warn(`resolveProgressCtx: ${def.name}.progress threw: ${String(err)}`);\n return { label: def.title };\n }\n}\n\nfunction composeSignal(base: AbortSignal, timeoutMs?: number): AbortSignal {\n if (!timeoutMs) return base;\n return AbortSignal.any([base, AbortSignal.timeout(timeoutMs)]);\n}\n\n/**\n * A batch result where every path failed. The call produced no work at all, so\n * it is a failed call — `isError` must say so. Partial failure is deliberately\n * NOT an error: the per-path entries carry which paths failed and the succeeded\n * ones really were done.\n *\n * Two result shapes reach here. Most batch tools carry a `summary`. `create` and\n * `move` do not: they publish `{files|moves, failures, skipped}` (see\n * create.ts's CreateOutputSchema and move.ts's MoveOutputSchema), so a\n * summary-only check reported a fully-denied write as a successful call. Both\n * shapes are handled here rather than by growing the two output schemas, which\n * are the client-facing contract.\n */\nfunction isTotalBatchFailure(structured: unknown): boolean {\n if (typeof structured !== 'object' || structured === null) return false;\n const result = structured as {\n summary?: { total?: number; failed?: number };\n failures?: unknown;\n files?: unknown;\n moves?: unknown;\n skipped?: unknown;\n };\n\n const { summary } = result;\n if (typeof summary?.total === 'number') {\n return summary.total > 0 && summary.failed === summary.total;\n }\n\n const len = (value: unknown): number => (Array.isArray(value) ? value.length : 0);\n if (len(result.failures) === 0) return false;\n // A skipped entry is work the caller asked to skip, not work that failed —\n // a self-move that was silently dropped means the call did something.\n return len(result.files) + len(result.moves) + len(result.skipped) === 0;\n}\n\n/**\n * The spec asks a structured result to *also* carry the JSON as a text block,\n * for clients that read only `content`. Where a tool supplies its own `text`\n * (list's ASCII tree, read's file) that serves such a client better, so it\n * wins; tools with no `text` still fall back to the JSON.\n */\nfunction buildSuccessResponse<O>(result: RunResult<O>): CallToolResult {\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 structuredContent: result.structured,\n ...(isTotalBatchFailure(result.structured) ? { isError: true } : {}),\n };\n}\n\nclass ToolExecutor<I extends z.ZodType, O extends z.ZodType> {\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 #progressClosed = false;\n readonly #progressCtx: ProgressCtx;\n readonly #mcpSink?: McpProgressSink;\n readonly #progressSession: ProgressSession;\n\n constructor(toolName: string, ctx: ToolCtx, def: ToolDef<I, O>, parsedArgs: z.infer<I>) {\n this.def = def;\n this.parsedArgs = parsedArgs;\n this.signal = composeSignal(ctx.signal, def.timeoutMs);\n this.#progressCtx = resolveProgressCtx(def, parsedArgs);\n const sinks: ProgressSink[] = [];\n if (ctx._meta?.progressToken !== undefined && ctx.sendNotification !== undefined) {\n this.#mcpSink = new McpProgressSink(toolName, ctx._meta.progressToken, ctx.sendNotification);\n sinks.push(this.#mcpSink);\n }\n const isTest = process.env['NODE_ENV'] === 'test' || process.execArgv.includes('--test');\n this.#progressSession = new ProgressSession({\n label: this.#progressCtx.label,\n sinks,\n ...(isTest ? { rateLimitMs: 0 } : {}),\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 const prefix = logger ? `[${logger}] ` : '';\n Logger.emit(level, `${prefix}${msg}`);\n },\n onProgress: (p) => {\n this.#tick(p);\n },\n };\n }\n\n #tick(p: { current: number; total?: number }): void {\n if (this.#progressClosed) return;\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 async #closeWithDone(message: string): Promise<void> {\n this.#progressClosed = true;\n this.#progressSession.complete(message);\n if (this.#mcpSink) await this.#mcpSink.flush();\n }\n\n async #closeWithFail(error: unknown, message: string): Promise<void> {\n this.#progressClosed = true;\n this.#progressSession.fail(error, message);\n if (this.#mcpSink) await this.#mcpSink.flush();\n }\n\n async #flushProgress(): Promise<void> {\n if (this.#mcpSink) await this.#mcpSink.flush();\n }\n\n private async completeProgress(result: z.infer<O>): Promise<void> {\n const doneCtx: ProgressCtx = this.def.progressDone\n ? { ...this.#progressCtx, ...this.def.progressDone(this.parsedArgs, result) }\n : this.#progressCtx;\n await this.#closeWithDone(plainMessage('done', doneCtx));\n }\n\n private async failProgress(error: unknown): Promise<{ isError: true; content: ContentBlock[] }> {\n const errMsg = formatUnknownErrorMessage(error);\n const message = plainMessage('fail', { ...this.#progressCtx, error: errMsg });\n await this.#closeWithFail(error, message);\n const { text: errorText } = Problem.toText(\n error,\n this.def.defaultErrorCode ?? ErrorCode.UNKNOWN,\n );\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({\n op: 'grant',\n pending: grantDirs,\n requestState: this.toolCtx.requestState,\n clientCapabilities: this.toolCtx.clientCapabilities,\n buildInputs: (dirs) =>\n multi\n ? [\n multiSelectInput(\n 'grant',\n 'Grant filesystem access to these directories? Select the ones to allow.',\n dirs.map((d) => ({ value: d, title: d })),\n ),\n ]\n : dirs.map((dir, i) =>\n confirmInput(`confirm_${i}`, `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 // `confirm_${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, `confirm_${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 const runTool = async (): 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.#flushProgress();\n }\n };\n\n return runTool();\n }\n}\n\nfunction createServerToolHandler<I extends z.ZodType, O extends z.ZodType>(\n def: ToolDef<I, O>,\n deps: ToolDeps,\n): (args: z.infer<I>, ctx: ServerContext) => Promise<CallToolResult | InputRequiredResult> {\n return async (args, ctx) =>\n new ToolExecutor<I, O>(def.name, toToolCtx(ctx, deps), def, args).execute();\n}\n\n/**\n * Validate with Zod while publishing the precomputed JSON Schema: clients get\n * draft-2020-12, handlers get Zod's coercions, defaults and error messages.\n *\n * Each validator instance is built for exactly one schema and handed straight\n * to `fromJsonSchema(thatSchema, ...)`, which calls `getValidator` once with\n * the same schema — so the argument is redundant here and deliberately ignored.\n * Reusing one instance across schemas would silently validate against `schema`.\n */\nfunction zodJsonSchemaValidator(schema: z.ZodType): jsonSchemaValidator {\n return {\n getValidator<U>(): JsonSchemaValidator<U> {\n return (input: unknown) => {\n const result = schema.safeParse(input);\n if (result.success) {\n return {\n valid: true as const,\n data: result.data as U,\n errorMessage: undefined,\n };\n }\n return {\n valid: false as const,\n data: undefined,\n errorMessage: z.prettifyError(result.error),\n };\n };\n },\n };\n}\n\n/**\n * Generate the wire copy of a schema for `tools/list`. The Zod schema keeps\n * every constraint for runtime validation; the `override` pass only trims what\n * the wire copy costs every client at session start:\n *\n * - `$schema` and `title` carry no information the host uses.\n * - `maximum: Number.MAX_SAFE_INTEGER` is zod's int() artifact, not a bound.\n * - `examples` is dropped in both directions: on output it describes a field the\n * server itself fills in, and on input every description that carried one\n * already spells the same example out inline, so the keyword paid twice.\n *\n * Output `description`s are NOT dropped. They were, and the result was a wire\n * contract the model had to guess at: `delete` returns `path` XOR `paths`,\n * `edit.diff` appears only under dryRun, `read.value` has no required field at\n * all. None of that is inferable from types alone.\n *\n * No shared subschema carries a `.meta({ id })`, so zod inlines every one of\n * them and the emitted document has no `$defs`/`$ref` to dereference.\n */\nfunction toDraft202012(schema: z.ZodType, io: 'input' | 'output'): JsonSchemaType {\n const generated = z.toJSONSchema(schema, {\n target: 'draft-2020-12',\n io,\n override: ({ jsonSchema }) => {\n const node = jsonSchema as Record<string, unknown>;\n delete node['title'];\n if (node['maximum'] === Number.MAX_SAFE_INTEGER) delete node['maximum'];\n delete node['examples'];\n },\n }) as Record<string, unknown>;\n delete generated['$schema'];\n return generated;\n}\n\nexport function defineTool<I extends z.ZodType, O extends z.ZodType>(\n def: ToolDef<I, O>,\n): DefinedTool {\n const inputJsonSchema = toDraft202012(def.input, 'input');\n const outputJsonSchema = toDraft202012(def.output, 'output');\n\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 // Published annotations are derived, not passed through. `readOnlyHint` is\n // load-bearing (MUTATING_TOOL_NAMES derives the --read-only gate from it) and\n // `openWorldHint: false` is a real claim for a filesystem server. The other\n // two describe behavior a read-only tool cannot have, and restate the default\n // for a mutating one — 29 tokens per tool for nothing a client acts on.\n const publishedAnnotations: ToolAnnotations = {\n readOnlyHint: def.annotations.readOnlyHint,\n openWorldHint: def.annotations.openWorldHint ?? false,\n ...(def.annotations.readOnlyHint\n ? {}\n : { destructiveHint: def.annotations.destructiveHint ?? true }),\n };\n\n const toolDefShape = {\n title: def.title,\n description: def.description,\n inputSchema: fromJsonSchema<z.infer<I>>(inputJsonSchema, zodJsonSchemaValidator(def.input)),\n // The validator is built either way — results are still checked against the\n // Zod object — but the schema reaches the wire only where the shape is not\n // inferable from the description plus the text content.\n ...(def.publishOutputSchema\n ? {\n outputSchema: fromJsonSchema<z.infer<O>>(\n outputJsonSchema,\n zodJsonSchemaValidator(def.output),\n ),\n }\n : {}),\n annotations: publishedAnnotations,\n };\n\n const tool: DefinedTool = {\n name: def.name,\n annotations: def.annotations,\n\n register(deps: ToolDeps): RegisteredTool {\n return deps.server.registerTool(def.name, toolDefShape, createServerToolHandler(def, deps));\n },\n };\n\n return tool;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAiBA,OAAO,EACL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AA0D;QAC1D,yEAAyE;QACzE,uEAAuE;QACvE,EAAE;QACF,4EAA4E;QAC5E,oDAAoD;QACpD,WAAW,EAAE,oBAAoB;KAClC,CAAC;IAEF,MAAM,IAAI,GAAgB;QACxB,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,WAAW,EAAE,GAAG,CAAC,WAAW;QAE5B,QAAQ,CAAC,IAAc;YACrB,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,EAAE,YAAY,EAAE,uBAAuB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9F,CAAC;KACF,CAAC;IAEF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n AuthInfo,\n CallToolResult,\n ClientCapabilities,\n ContentBlock,\n InputRequiredResult,\n JsonSchemaType,\n JsonSchemaValidator,\n jsonSchemaValidator,\n McpServer,\n Notification,\n RegisteredTool,\n RequestMeta,\n RequestStateAccessor,\n ServerContext,\n ToolAnnotations,\n} from '@modelcontextprotocol/server';\nimport {\n CLIENT_CAPABILITIES_META_KEY,\n fromJsonSchema,\n isInputRequiredResult,\n} from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, formatUnknownErrorMessage, Problem } from '../core/errors.js';\nimport type { ProgressCtx } from '../core/fmt.js';\nimport { plainMessage } from '../core/fmt.js';\nimport { GuardedFileSystem } from '../core/fs.js';\nimport {\n confirmInput,\n multiSelectInput,\n pendingRoundTrip,\n readAcceptedConfirm,\n readAcceptedMultiChoice,\n} from '../core/input-required.js';\nimport { Logger } from '../core/observability.js';\nimport type { LoggingLevel } from '../core/observability.js';\nimport type { PageSnapshotStore } from '../core/page-store.js';\nimport { isSamePath } from '../core/path-utils.js';\nimport type { PathGuard } from '../core/path.js';\nimport type { ResourceStore } from '../core/store.js';\nimport type { ProgressSink } from './progress.js';\nimport { McpProgressSink, ProgressSession } from './progress.js';\n\nexport interface ToolCtx {\n readonly signal: AbortSignal;\n readonly sessionId?: string;\n readonly authInfo?: AuthInfo;\n readonly _meta?: RequestMeta | undefined;\n readonly fs: GuardedFileSystem;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore | undefined;\n /** Emits a log line to stderr via `Logger.emit`, gated by `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 * 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 readonly server?: McpServer;\n}\n\ninterface ToolDeps {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly pageStore: PageSnapshotStore;\n readonly resourceStore: ResourceStore | undefined;\n}\n\ninterface RunResult<T> {\n readonly structured: T;\n readonly text?: string;\n readonly resources?: ContentBlock[];\n}\n\n/**\n * `ToolAnnotations` with `readOnlyHint` required. It is optional in the SDK, but\n * MUTATING_TOOL_NAMES derives the `--read-only` gate from it, so a tool that\n * forgets it must be a compile error rather than a silent reclassification.\n */\ntype DeclaredAnnotations = ToolAnnotations & { readonly readOnlyHint: boolean };\n\nexport interface ToolDef<I extends z.ZodType, O extends z.ZodType> {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly input: I;\n readonly output: O;\n readonly annotations: DeclaredAnnotations;\n readonly timeoutMs?: number;\n readonly progress?: (args: z.infer<I>) => ProgressCtx;\n readonly progressDone?: (args: z.infer<I>, result: z.infer<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: (\n args: z.infer<I>,\n ctx: ToolCtx,\n ) => Promise<RunResult<z.infer<O>> | InputRequiredResult>;\n}\n\nexport interface DefinedTool {\n readonly name: string;\n readonly annotations: DeclaredAnnotations;\n\n register(deps: ToolDeps): RegisteredTool;\n}\n\nfunction toToolCtx(\n ctx: ServerContext | undefined,\n deps: Pick<ToolDeps, 'pathGuard' | 'pageStore' | 'resourceStore' | 'server'>,\n): ToolCtx {\n if (!ctx) {\n const signal = new AbortController().signal;\n return {\n signal,\n fs: new GuardedFileSystem(deps.pathGuard),\n pageStore: deps.pageStore,\n resourceStore: deps.resourceStore,\n server: deps.server,\n };\n }\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\n return {\n signal: ctx.mcpReq.signal,\n ...(ctx.sessionId ? { sessionId: ctx.sessionId } : {}),\n ...(ctx.http?.authInfo ? { authInfo: ctx.http.authInfo } : {}),\n ...(ctx.mcpReq._meta ? { _meta: ctx.mcpReq._meta } : {}),\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 requestState: ctx.mcpReq.requestState,\n ...(clientCapabilities ? { clientCapabilities } : {}),\n server: deps.server,\n };\n}\n\nfunction resolveProgressCtx<I extends z.ZodType, O extends z.ZodType>(\n def: ToolDef<I, O>,\n args: z.infer<I>,\n): ProgressCtx {\n if (!def.progress) return { label: def.title };\n try {\n return def.progress(args);\n } catch (err: unknown) {\n Logger.warn(`resolveProgressCtx: ${def.name}.progress threw: ${String(err)}`);\n return { label: def.title };\n }\n}\n\nfunction composeSignal(base: AbortSignal, timeoutMs?: number): AbortSignal {\n if (!timeoutMs) return base;\n return AbortSignal.any([base, AbortSignal.timeout(timeoutMs)]);\n}\n\n/**\n * A batch result where every path failed. The call produced no work at all, so\n * it is a failed call — `isError` must say so. Partial failure is deliberately\n * NOT an error: the per-path entries carry which paths failed and the succeeded\n * ones really were done.\n *\n * Two result shapes reach here. Most batch tools carry a `summary`. `create` and\n * `move` do not: they publish `{files|moves, failures, skipped}` (see\n * create.ts's CreateOutputSchema and move.ts's MoveOutputSchema), so a\n * summary-only check reported a fully-denied write as a successful call. Both\n * shapes are handled here rather than by growing the two output schemas, which\n * are the client-facing contract.\n */\nfunction isTotalBatchFailure(structured: unknown): boolean {\n if (typeof structured !== 'object' || structured === null) return false;\n const result = structured as {\n summary?: { total?: number; failed?: number };\n failures?: unknown;\n files?: unknown;\n moves?: unknown;\n skipped?: unknown;\n };\n\n const { summary } = result;\n if (typeof summary?.total === 'number') {\n return summary.total > 0 && summary.failed === summary.total;\n }\n\n const len = (value: unknown): number => (Array.isArray(value) ? value.length : 0);\n if (len(result.failures) === 0) return false;\n // A skipped entry is work the caller asked to skip, not work that failed —\n // a self-move that was silently dropped means the call did something.\n return len(result.files) + len(result.moves) + len(result.skipped) === 0;\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>(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\n ? // Safe because every `ToolDef.output` is a Zod object schema, so\n // `structured` is always a plain object. Constraining `O` to prove it\n // is not worth the cost: the bound has to thread through five generic\n // sites and still loses to `exactOptionalPropertyTypes` variance on\n // `RunResult`'s optional fields.\n { _meta: result.structured as Record<string, unknown> }\n : { structuredContent: result.structured }),\n ...(isTotalBatchFailure(result.structured) ? { isError: true } : {}),\n };\n}\n\nclass ToolExecutor<I extends z.ZodType, O extends z.ZodType> {\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 #progressClosed = false;\n readonly #progressCtx: ProgressCtx;\n readonly #mcpSink?: McpProgressSink;\n readonly #progressSession: ProgressSession;\n\n constructor(toolName: string, ctx: ToolCtx, def: ToolDef<I, O>, parsedArgs: z.infer<I>) {\n this.def = def;\n this.parsedArgs = parsedArgs;\n this.signal = composeSignal(ctx.signal, def.timeoutMs);\n this.#progressCtx = resolveProgressCtx(def, parsedArgs);\n const sinks: ProgressSink[] = [];\n if (ctx._meta?.progressToken !== undefined && ctx.sendNotification !== undefined) {\n this.#mcpSink = new McpProgressSink(toolName, ctx._meta.progressToken, ctx.sendNotification);\n sinks.push(this.#mcpSink);\n }\n const isTest = process.env['NODE_ENV'] === 'test' || process.execArgv.includes('--test');\n this.#progressSession = new ProgressSession({\n label: this.#progressCtx.label,\n sinks,\n ...(isTest ? { rateLimitMs: 0 } : {}),\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 const prefix = logger ? `[${logger}] ` : '';\n Logger.emit(level, `${prefix}${msg}`);\n },\n onProgress: (p) => {\n this.#tick(p);\n },\n };\n }\n\n #tick(p: { current: number; total?: number }): void {\n if (this.#progressClosed) return;\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 async #closeWithDone(message: string): Promise<void> {\n this.#progressClosed = true;\n this.#progressSession.complete(message);\n if (this.#mcpSink) await this.#mcpSink.flush();\n }\n\n async #closeWithFail(error: unknown, message: string): Promise<void> {\n this.#progressClosed = true;\n this.#progressSession.fail(error, message);\n if (this.#mcpSink) await this.#mcpSink.flush();\n }\n\n async #flushProgress(): Promise<void> {\n if (this.#mcpSink) await this.#mcpSink.flush();\n }\n\n private async completeProgress(result: z.infer<O>): Promise<void> {\n const doneCtx: ProgressCtx = this.def.progressDone\n ? { ...this.#progressCtx, ...this.def.progressDone(this.parsedArgs, result) }\n : this.#progressCtx;\n await this.#closeWithDone(plainMessage('done', doneCtx));\n }\n\n private async failProgress(error: unknown): Promise<{ isError: true; content: ContentBlock[] }> {\n const errMsg = formatUnknownErrorMessage(error);\n const message = plainMessage('fail', { ...this.#progressCtx, error: errMsg });\n await this.#closeWithFail(error, message);\n const { text: errorText } = Problem.toText(\n error,\n this.def.defaultErrorCode ?? ErrorCode.UNKNOWN,\n );\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({\n op: 'grant',\n pending: grantDirs,\n requestState: this.toolCtx.requestState,\n clientCapabilities: this.toolCtx.clientCapabilities,\n buildInputs: (dirs) =>\n multi\n ? [\n multiSelectInput(\n 'grant',\n 'Grant filesystem access to these directories? Select the ones to allow.',\n dirs.map((d) => ({ value: d, title: d })),\n ),\n ]\n : dirs.map((dir, i) =>\n confirmInput(`confirm_${i}`, `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 // `confirm_${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, `confirm_${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 const runTool = async (): 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.#flushProgress();\n }\n };\n\n return runTool();\n }\n}\n\nfunction createServerToolHandler<I extends z.ZodType, O extends z.ZodType>(\n def: ToolDef<I, O>,\n deps: ToolDeps,\n): (args: z.infer<I>, ctx: ServerContext) => Promise<CallToolResult | InputRequiredResult> {\n return async (args, ctx) =>\n new ToolExecutor<I, O>(def.name, toToolCtx(ctx, deps), def, args).execute();\n}\n\n/**\n * Validate with Zod while publishing the precomputed JSON Schema: clients get\n * draft-2020-12, handlers get Zod's coercions, defaults and error messages.\n *\n * Each validator instance is built for exactly one schema and handed straight\n * to `fromJsonSchema(thatSchema, ...)`, which calls `getValidator` once with\n * the same schema — so the argument is redundant here and deliberately ignored.\n * Reusing one instance across schemas would silently validate against `schema`.\n */\nfunction zodJsonSchemaValidator(schema: z.ZodType): jsonSchemaValidator {\n return {\n getValidator<U>(): JsonSchemaValidator<U> {\n return (input: unknown) => {\n const result = schema.safeParse(input);\n if (result.success) {\n return {\n valid: true as const,\n data: result.data as U,\n errorMessage: undefined,\n };\n }\n return {\n valid: false as const,\n data: undefined,\n errorMessage: z.prettifyError(result.error),\n };\n };\n },\n };\n}\n\n/**\n * Generate the wire copy of a schema for `tools/list`. The Zod schema keeps\n * every constraint for runtime validation; the `override` pass only trims what\n * the wire copy costs every client at session start:\n *\n * - `$schema` and `title` carry no information the host uses.\n * - `maximum: Number.MAX_SAFE_INTEGER` is zod's int() artifact, not a bound.\n * - `examples` is dropped in both directions: on output it describes a field the\n * server itself fills in, and on input every description that carried one\n * already spells the same example out inline, so the keyword paid twice.\n *\n * Output `description`s are NOT dropped. They were, and the result was a wire\n * contract the model had to guess at: `delete` returns `path` XOR `paths`,\n * `edit.diff` appears only under dryRun, `read.value` has no required field at\n * all. None of that is inferable from types alone.\n *\n * No shared subschema carries a `.meta({ id })`, so zod inlines every one of\n * them and the emitted document has no `$defs`/`$ref` to dereference.\n */\nfunction toDraft202012(schema: z.ZodType, io: 'input' | 'output'): JsonSchemaType {\n const generated = z.toJSONSchema(schema, {\n target: 'draft-2020-12',\n io,\n override: ({ jsonSchema }) => {\n const node = jsonSchema as Record<string, unknown>;\n delete node['title'];\n if (node['maximum'] === Number.MAX_SAFE_INTEGER) delete node['maximum'];\n delete node['examples'];\n },\n }) as Record<string, unknown>;\n delete generated['$schema'];\n return generated;\n}\n\nexport function defineTool<I extends z.ZodType, O extends z.ZodType>(\n def: ToolDef<I, O>,\n): DefinedTool {\n const inputJsonSchema = toDraft202012(def.input, 'input');\n\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 // Published annotations are derived, not passed through. `readOnlyHint` is\n // load-bearing (MUTATING_TOOL_NAMES derives the --read-only gate from it) and\n // `openWorldHint: false` is a real claim for a filesystem server. The other\n // two describe behavior a read-only tool cannot have, and restate the default\n // for a mutating one — 29 tokens per tool for nothing a client acts on.\n const publishedAnnotations: ToolAnnotations = {\n readOnlyHint: def.annotations.readOnlyHint,\n openWorldHint: def.annotations.openWorldHint ?? false,\n ...(def.annotations.readOnlyHint\n ? {}\n : { destructiveHint: def.annotations.destructiveHint ?? true }),\n };\n\n const toolDefShape = {\n title: def.title,\n description: def.description,\n inputSchema: fromJsonSchema<z.infer<I>>(inputJsonSchema, zodJsonSchemaValidator(def.input)),\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 //\n // `def.output` stays: it types `RunResult<z.infer<O>>`, which is what makes\n // a tool returning the wrong shape a compile error.\n annotations: publishedAnnotations,\n };\n\n const tool: DefinedTool = {\n name: def.name,\n annotations: def.annotations,\n\n register(deps: ToolDeps): RegisteredTool {\n return deps.server.registerTool(def.name, toolDefShape, createServerToolHandler(def, deps));\n },\n };\n\n return tool;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delete-file.d.ts","sourceRoot":"","sources":["../../src/tools/delete-file.ts"],"names":[],"mappings":"AAwZA,eAAO,MAAM,WAAW,
|
|
1
|
+
{"version":3,"file":"delete-file.d.ts","sourceRoot":"","sources":["../../src/tools/delete-file.ts"],"names":[],"mappings":"AAwZA,eAAO,MAAM,WAAW,mCAsDtB,CAAC"}
|
|
@@ -294,9 +294,6 @@ export const DELETE_FILE = defineTool({
|
|
|
294
294
|
'Workspace root directories cannot be deleted.',
|
|
295
295
|
input: DeleteInputSchema,
|
|
296
296
|
output: DeleteOutputSchema,
|
|
297
|
-
// results[].value XOR results[].error, and `deleted: false` means the user
|
|
298
|
-
// chose Skip rather than a failure — not inferable from the description.
|
|
299
|
-
publishOutputSchema: true,
|
|
300
297
|
annotations: {
|
|
301
298
|
readOnlyHint: false,
|
|
302
299
|
idempotentHint: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delete-file.js","sourceRoot":"","sources":["../../src/tools/delete-file.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,WAAW,EACX,eAAe,EACf,OAAO,GACR,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC9F,OAAO,EACL,mBAAmB,EACnB,sBAAsB,EACtB,kBAAkB,EAClB,YAAY,GACb,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,iBAAiB,G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SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAChC,IAAI,CAAC,CAAC,KAAK;gBAAE,OAAO,GAAG,KAAK,SAAS,CAAC;YACtC,OAAO,CAAC,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,UAAU,CAAC;QACvD,CAAC,CAAC,CAAC;QACH,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACnF,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW,UAAU,CAAC,MAAM,CAAC,GAAG,KAAK,EAAE,EAAE,CAAC;IACvE,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { InputRequiredResult } from '@modelcontextprotocol/server';\nimport { isInputRequiredResult } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.js';\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n isNotFoundErrno,\n Problem,\n} from '../core/errors.js';\nimport { joinRoster, pathLabel } from '../core/fmt.js';\nimport type { FileType, GuardedFileSystem } from '../core/fs.js';\nimport { getFileType } from '../core/fs.js';\nimport { choiceInput, pendingRoundTrip, readAcceptedChoice } from '../core/input-required.js';\nimport {\n defaultFalseBoolean,\n OperationSummarySchema,\n PerFileErrorSchema,\n RequiredPath,\n} from '../core/schema.js';\nimport { PARALLEL_CONCURRENCY } from '../core/util.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst DeleteInputSchema = z.strictObject({\n paths: z\n .array(RequiredPath)\n .min(1)\n .max(1000)\n .describe('Paths to delete (max 1000); accepts files, directories, or symlinks'),\n recursive: defaultFalseBoolean(\n 'Delete directory contents recursively (required for non-empty directories)',\n ),\n ignoreIfNotExists: defaultFalseBoolean(\n 'Silently succeed if a path does not exist instead of returning an error',\n ),\n});\n\nconst DeletePerPathValueSchema = z.strictObject({\n deleted: z.boolean().describe('True when the path was removed; false when the user chose Skip'),\n});\n\nconst DeletePerPathSchema = z.strictObject({\n path: z.string().describe('Requested path'),\n value: DeletePerPathValueSchema.optional().describe('Delete outcome; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\n// One envelope for every batch tool: `read` and `stat` already answer with\n// `{ results, summary }`, so `delete` does too. The old shape switched between\n// `{ ok, path }` and `{ ok: false, failures }` depending on the outcome, which\n// left a caller parsing two schemas for one tool and never named the paths in a\n// multi-delete's text.\nconst DeleteOutputSchema = z.strictObject({\n results: z\n .array(DeletePerPathSchema)\n .describe('Per-path results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype DeleteInput = z.infer<typeof DeleteInputSchema>;\ntype DeleteOutput = z.infer<typeof DeleteOutputSchema>;\ntype DeletePerPathResult = z.infer<typeof DeletePerPathSchema>;\n\n// Internal types for error handling\ninterface DeletedItem {\n path: string;\n}\ninterface DeleteFailure {\n path: string;\n error: {\n code: string;\n message: string;\n path?: string;\n suggestion?: string;\n };\n}\n\nconst ERR_NOT_EMPTY = new Error('Directory not empty. Set recursive: true.');\n\nfunction toDeleteFailure(path: string, error: unknown): DeleteFailure {\n // A missing path reached here as the raw errno text (\"ENOENT: no such file or\n // directory, lstat 'c:\\...'\"), while `stat` reported the same condition as\n // \"Path not found\". One condition, one message — and the syscall name stays\n // off the wire.\n if (isNotFoundErrno(error)) {\n return {\n path,\n error: Problem.toPerFileError(\n new FsError(ErrorCode.NOT_FOUND, 'Path not found', path),\n ErrorCode.NOT_FOUND,\n path,\n ),\n };\n }\n if (\n isNodeError(error) &&\n (error.code === 'ENOTEMPTY' || error.code === 'EISDIR' || error.code === 'EEXIST')\n ) {\n return {\n path,\n error: Problem.toPerFileError(ERR_NOT_EMPTY, ErrorCode.INVALID_INPUT, path),\n };\n }\n return { path, error: Problem.toPerFileError(error, ErrorCode.UNKNOWN, path) };\n}\n\ntype LstatResult = Awaited<ReturnType<GuardedFileSystem['lstat']>>;\ntype ItemType = FileType;\n\n/** A path's pre-checked plan: validated, statted, and flagged if it needs confirmation. */\ninterface DeletePlan {\n inputPath: string;\n validPath: string;\n itemType: ItemType;\n firstStats: LstatResult;\n /** Recursive + non-empty directory: needs a round-trip confirmation. */\n pending: boolean;\n}\n\ntype PlanResult =\n | { status: 'fail'; failure: DeleteFailure }\n | { status: 'noop'; item: DeletedItem }\n | { status: 'plan'; plan: DeletePlan };\n\n/**\n * Phase 1 (no mutation): validate, stat, and decide whether a path needs a\n * confirmation before anything is deleted. A pending path is a recursive\n * non-empty directory; everything else is ready to delete directly.\n */\nasync function planPath(\n inputPath: string,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n fs: Pick<GuardedFileSystem, 'pathGuard' | 'lstat' | 'hasChildrenUnchecked'>,\n): Promise<PlanResult> {\n let validPath: string;\n try {\n validPath = await fs.pathGuard.validatePathForDelete(inputPath);\n } catch (error) {\n if (\n args.ignoreIfNotExists &&\n ((isFsError(error) && error.code === ErrorCode.NOT_FOUND) || isNotFoundErrno(error))\n ) {\n return { status: 'noop', item: { path: inputPath } };\n }\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n\n if (fs.pathGuard.isAllowedRoot(validPath)) {\n return {\n status: 'fail',\n // Keyed by the REQUESTED path, like every other failure here: handleDelete\n // orders results by input path, and a resolved key would not be found for\n // a relative request.\n failure: {\n path: inputPath,\n error: Problem.accessDenied('Deleting a workspace root directory is not allowed', {\n path: validPath,\n }),\n },\n };\n }\n\n let firstStats: LstatResult;\n try {\n firstStats = await fs.lstat(validPath);\n } catch (error) {\n if (isNotFoundErrno(error) && args.ignoreIfNotExists) {\n return { status: 'noop', item: { path: inputPath } };\n }\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n\n const itemType = getFileType(firstStats.stats);\n let hasChildren = false;\n if (args.recursive && itemType === 'directory') {\n try {\n hasChildren = await fs.hasChildrenUnchecked(validPath);\n } catch (error) {\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n }\n const pending = hasChildren;\n return { status: 'plan', plan: { inputPath, validPath, itemType, firstStats, pending } };\n}\n\nasync function performDeletion(\n validPath: string,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n isDirectory: boolean,\n fsOps: Pick<GuardedFileSystem, 'rm' | 'rmdir'>,\n): Promise<void> {\n if (isDirectory && !args.recursive) {\n await fsOps.rmdir(validPath);\n } else {\n await fsOps.rm(validPath, {\n recursive: args.recursive,\n force: args.ignoreIfNotExists,\n });\n }\n}\n\n/**\n * Phase 2 (mutation): TOCTOU re-stat against the plan's first stat, then\n * delete. A type or identity change across the confirmation gap fails closed\n * rather than deleting a replacement object the user never confirmed.\n */\nasync function finalizeDeletion(\n plan: DeletePlan,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n ctx: Pick<ToolCtx, 'fs' | 'log'>,\n): Promise<{ item: DeletedItem } | { failure: DeleteFailure }> {\n let currentStats: LstatResult;\n try {\n currentStats = await ctx.fs.lstat(plan.validPath);\n } catch (error) {\n if (isNotFoundErrno(error) && args.ignoreIfNotExists) {\n return { item: { path: plan.validPath } };\n }\n return { failure: toDeleteFailure(plan.inputPath, error) };\n }\n\n const currentItemType = getFileType(currentStats.stats);\n // Identity comparison, not just the coarse category: a swap during the\n // confirmation gap (delete original, create a same-named replacement) keeps\n // the type but changes dev/ino/birthtimeMs. birthtimeMs is the primary\n // cross-platform signal — dev/ino can read 0 on some non-POSIX drivers — so\n // combine all three rather than trusting dev/ino alone.\n const identityChanged =\n plan.firstStats.stats.dev !== currentStats.stats.dev ||\n plan.firstStats.stats.ino !== currentStats.stats.ino ||\n plan.firstStats.stats.birthtimeMs !== currentStats.stats.birthtimeMs;\n if (plan.itemType !== 'other' && (currentItemType !== plan.itemType || identityChanged)) {\n return {\n failure: {\n path: plan.validPath,\n error: Problem.invalidInput(\n `Delete failed: item type changed from ${plan.itemType} to ${currentItemType} during confirmation.`,\n { path: plan.validPath },\n ),\n },\n };\n }\n\n try {\n await performDeletion(plan.validPath, args, currentStats.stats.isDirectory(), ctx.fs);\n } catch (error) {\n return { failure: toDeleteFailure(plan.inputPath, error) };\n }\n\n ctx.log?.('info', `rm: ${plan.inputPath}`, 'delete');\n return { item: { path: plan.validPath } };\n}\n\n/**\n * Execute one planned path on the retry round. A pending path deletes only on\n * an accepted `confirm: true`; decline, cancel, or a missing key report\n * `CANCELLED` for that path (R3 proceed, R4/R5 cancelled). A non-pending path\n * deletes directly (R14: non-pending items proceed alongside accepted ones).\n */\nasync function executePlan(\n plan: DeletePlan,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n ctx: Pick<ToolCtx, 'fs' | 'inputResponses' | 'log'>,\n pendingSorted: readonly string[],\n): Promise<{ item: DeletedItem } | { failure: DeleteFailure } | { skipped: true; path: string }> {\n if (plan.pending) {\n const key = `confirm_${pendingSorted.indexOf(plan.validPath)}`;\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: true as const, path: plan.validPath };\n }\n if (choice !== 'delete') {\n return {\n failure: {\n path: plan.validPath,\n error: Problem.cancelled('Delete cancelled: confirmation was declined or missing', {\n path: plan.validPath,\n }),\n },\n };\n }\n }\n return finalizeDeletion(plan, args, ctx);\n}\n\nasync function handleDelete(\n args: DeleteInput,\n ctx: ToolCtx,\n): Promise<DeleteOutput | InputRequiredResult> {\n // Duplicate paths collapse: results are keyed by path, so a repeated entry\n // would emit two rows for one deletion and inflate `summary.total`.\n const paths = [...new Set(args.paths)];\n\n // Phase 1 (no mutation): plan every path.\n const planned = await processInParallel(\n paths,\n (inputPath) => planPath(inputPath, args, ctx.fs),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n const plans: DeletePlan[] = [];\n const earlyFailures: DeleteFailure[] = [];\n const earlyNoop: DeletedItem[] = [];\n for (const { value: r } of planned.results) {\n if (r.status === 'fail') earlyFailures.push(r.failure);\n else if (r.status === 'noop') earlyNoop.push(r.item);\n else plans.push(r.plan);\n }\n for (const { index, error } of planned.errors) {\n const path = paths[index] ?? '(unknown)';\n earlyFailures.push({ path, error: { code: ErrorCode.UNKNOWN, message: error.message } });\n }\n\n // Pending set: recursive + non-empty directories, sorted and de-duplicated.\n // `buildInputRequired` seals exactly this set into the requestState, and the\n // retried round recomputes it from the same args so a swapped retry (accept\n // for X, retry with Y) is rejected — the codec only proves the state was not\n // tampered, not that it matches the current request (R9).\n const pendingSorted = [...new Set(plans.filter((p) => p.pending).map((p) => p.validPath))].sort();\n\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required (atomic — R14: nothing deleted yet, not\n // even the non-pending items in the same call); a retry whose verified\n // state does not bind this pending set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip({\n op: 'delete',\n pending: pendingSorted,\n requestState: ctx.requestState,\n clientCapabilities: ctx.clientCapabilities,\n buildInputs: (ps) =>\n ps.map((p, i) =>\n choiceInput(\n `confirm_${i}`,\n `Permanently delete \"${p}\" and all its contents? This cannot be undone.`,\n [\n { value: 'delete', title: 'Delete' },\n { value: 'skip', title: 'Skip' },\n ],\n ),\n ),\n });\n if (round !== undefined) return round;\n }\n\n // Phase 2 (mutation): execute deletions for every planned path.\n const executed = await processInParallel(\n plans,\n (plan) => executePlan(plan, args, ctx, pendingSorted),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n // Collect by path first, then emit in the caller's input order so\n // `results[i]` lines up with `paths[i]` the way read/stat guarantee.\n const byPath = new Map<string, DeletePerPathResult>();\n const record = (path: string, entry: DeletePerPathResult): void => {\n byPath.set(path, entry);\n };\n for (const n of earlyNoop) record(n.path, { path: n.path, value: { deleted: true } });\n for (const f of earlyFailures) record(f.path, { path: f.path, error: f.error });\n for (const { value: r } of executed.results) {\n if ('skipped' in r) {\n record(r.path, { path: r.path, value: { deleted: false } });\n } else if ('failure' in r) {\n record(r.failure.path, { path: r.failure.path, error: r.failure.error });\n } else if (r.item.path) {\n record(r.item.path, { path: r.item.path, value: { deleted: true } });\n }\n }\n for (const { index, error } of executed.errors) {\n const plan = plans[index];\n const path = plan?.validPath ?? '(unknown)';\n record(path, {\n path,\n error: { code: ErrorCode.UNKNOWN, message: error.message },\n });\n }\n\n // A plan's `validPath` is the resolved absolute path, so a requested relative\n // path will not find itself in the map by name — fall back through the plan.\n const planByRequested = new Map(plans.map((p) => [p.inputPath, p.validPath]));\n const results: DeletePerPathResult[] = paths.map((requested) => {\n const resolved = planByRequested.get(requested);\n const entry =\n byPath.get(requested) ?? (resolved !== undefined ? byPath.get(resolved) : undefined);\n return (\n entry ?? {\n path: requested,\n error: { code: ErrorCode.UNKNOWN, message: 'Unknown delete failure' },\n }\n );\n });\n\n const failed = results.filter((r) => r.error !== undefined).length;\n return {\n results,\n summary: { total: results.length, succeeded: results.length - failed, failed },\n };\n}\n\nexport const DELETE_FILE = defineTool({\n name: 'delete',\n title: 'Delete File',\n description:\n 'Permanently delete one or more files, directories, or symlinks (max 1000 per call). This action is irreversible. ' +\n 'Pass paths: [...] — there is no single-path form. ' +\n 'Non-empty directories require recursive=true and additionally prompt the user to confirm each one, ' +\n 'so the call returns without deleting anything until that confirmation comes back; ' +\n 'a client that cannot prompt gets an error naming the alternative. ' +\n 'Workspace root directories cannot be deleted.',\n input: DeleteInputSchema,\n output: DeleteOutputSchema,\n // results[].value XOR results[].error, and `deleted: false` means the user\n // chose Skip rather than a failure — not inferable from the description.\n publishOutputSchema: true,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n defaultErrorCode: ErrorCode.UNKNOWN,\n progress: (args) => ({\n label: 'Delete',\n subject:\n args.paths.length === 1\n ? basename(args.paths[0] ?? '')\n : `${String(args.paths.length)} paths`,\n }),\n accessPaths: (args) => [...args.paths],\n run: async (args, ctx) => {\n const structured = await handleDelete(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(structured)) return structured;\n // Name every path and its outcome. The old text said \"deleted 2 paths\"\n // without saying which two, so a partial failure was unreadable without\n // parsing the structured half.\n const { failed, total } = structured.summary;\n // A lone failure carries its reason in the text. \"delete: . FAILED (0/1 ok)\"\n // made the model re-read structuredContent to learn it was ACCESS_DENIED;\n // with one path there is no ambiguity about which message applies.\n if (total === 1 && failed === 1) {\n const only = structured.results[0];\n return {\n structured,\n text: `delete: ${only?.path ?? ''} FAILED — ${only?.error?.message ?? 'unknown error'}`,\n };\n }\n const tokens = structured.results.map((r) => {\n const label = pathLabel(r.path);\n if (r.error) return `${label} FAILED`;\n return r.value?.deleted ? label : `${label} SKIPPED`;\n });\n const ratio = failed > 0 ? ` (${String(total - failed)}/${String(total)} ok)` : '';\n return { structured, text: `delete: ${joinRoster(tokens)}${ratio}` };\n },\n});\n"]}
|
|
1
|
+
{"version":3,"file":"delete-file.js","sourceRoot":"","sources":["../../src/tools/delete-file.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,WAAW,EACX,eAAe,EACf,OAAO,GACR,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC9F,OAAO,EACL,mBAAmB,EAC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;aACxF,CAAC;QACJ,CAAC;QACD,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YAC1C,MAAM,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAChC,IAAI,CAAC,CAAC,KAAK;gBAAE,OAAO,GAAG,KAAK,SAAS,CAAC;YACtC,OAAO,CAAC,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,UAAU,CAAC;QACvD,CAAC,CAAC,CAAC;QACH,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACnF,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW,UAAU,CAAC,MAAM,CAAC,GAAG,KAAK,EAAE,EAAE,CAAC;IACvE,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { InputRequiredResult } from '@modelcontextprotocol/server';\nimport { isInputRequiredResult } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.js';\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n isNotFoundErrno,\n Problem,\n} from '../core/errors.js';\nimport { joinRoster, pathLabel } from '../core/fmt.js';\nimport type { FileType, GuardedFileSystem } from '../core/fs.js';\nimport { getFileType } from '../core/fs.js';\nimport { choiceInput, pendingRoundTrip, readAcceptedChoice } from '../core/input-required.js';\nimport {\n defaultFalseBoolean,\n OperationSummarySchema,\n PerFileErrorSchema,\n RequiredPath,\n} from '../core/schema.js';\nimport { PARALLEL_CONCURRENCY } from '../core/util.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst DeleteInputSchema = z.strictObject({\n paths: z\n .array(RequiredPath)\n .min(1)\n .max(1000)\n .describe('Paths to delete (max 1000); accepts files, directories, or symlinks'),\n recursive: defaultFalseBoolean(\n 'Delete directory contents recursively (required for non-empty directories)',\n ),\n ignoreIfNotExists: defaultFalseBoolean(\n 'Silently succeed if a path does not exist instead of returning an error',\n ),\n});\n\nconst DeletePerPathValueSchema = z.strictObject({\n deleted: z.boolean().describe('True when the path was removed; false when the user chose Skip'),\n});\n\nconst DeletePerPathSchema = z.strictObject({\n path: z.string().describe('Requested path'),\n value: DeletePerPathValueSchema.optional().describe('Delete outcome; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\n// One envelope for every batch tool: `read` and `stat` already answer with\n// `{ results, summary }`, so `delete` does too. The old shape switched between\n// `{ ok, path }` and `{ ok: false, failures }` depending on the outcome, which\n// left a caller parsing two schemas for one tool and never named the paths in a\n// multi-delete's text.\nconst DeleteOutputSchema = z.strictObject({\n results: z\n .array(DeletePerPathSchema)\n .describe('Per-path results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype DeleteInput = z.infer<typeof DeleteInputSchema>;\ntype DeleteOutput = z.infer<typeof DeleteOutputSchema>;\ntype DeletePerPathResult = z.infer<typeof DeletePerPathSchema>;\n\n// Internal types for error handling\ninterface DeletedItem {\n path: string;\n}\ninterface DeleteFailure {\n path: string;\n error: {\n code: string;\n message: string;\n path?: string;\n suggestion?: string;\n };\n}\n\nconst ERR_NOT_EMPTY = new Error('Directory not empty. Set recursive: true.');\n\nfunction toDeleteFailure(path: string, error: unknown): DeleteFailure {\n // A missing path reached here as the raw errno text (\"ENOENT: no such file or\n // directory, lstat 'c:\\...'\"), while `stat` reported the same condition as\n // \"Path not found\". One condition, one message — and the syscall name stays\n // off the wire.\n if (isNotFoundErrno(error)) {\n return {\n path,\n error: Problem.toPerFileError(\n new FsError(ErrorCode.NOT_FOUND, 'Path not found', path),\n ErrorCode.NOT_FOUND,\n path,\n ),\n };\n }\n if (\n isNodeError(error) &&\n (error.code === 'ENOTEMPTY' || error.code === 'EISDIR' || error.code === 'EEXIST')\n ) {\n return {\n path,\n error: Problem.toPerFileError(ERR_NOT_EMPTY, ErrorCode.INVALID_INPUT, path),\n };\n }\n return { path, error: Problem.toPerFileError(error, ErrorCode.UNKNOWN, path) };\n}\n\ntype LstatResult = Awaited<ReturnType<GuardedFileSystem['lstat']>>;\ntype ItemType = FileType;\n\n/** A path's pre-checked plan: validated, statted, and flagged if it needs confirmation. */\ninterface DeletePlan {\n inputPath: string;\n validPath: string;\n itemType: ItemType;\n firstStats: LstatResult;\n /** Recursive + non-empty directory: needs a round-trip confirmation. */\n pending: boolean;\n}\n\ntype PlanResult =\n | { status: 'fail'; failure: DeleteFailure }\n | { status: 'noop'; item: DeletedItem }\n | { status: 'plan'; plan: DeletePlan };\n\n/**\n * Phase 1 (no mutation): validate, stat, and decide whether a path needs a\n * confirmation before anything is deleted. A pending path is a recursive\n * non-empty directory; everything else is ready to delete directly.\n */\nasync function planPath(\n inputPath: string,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n fs: Pick<GuardedFileSystem, 'pathGuard' | 'lstat' | 'hasChildrenUnchecked'>,\n): Promise<PlanResult> {\n let validPath: string;\n try {\n validPath = await fs.pathGuard.validatePathForDelete(inputPath);\n } catch (error) {\n if (\n args.ignoreIfNotExists &&\n ((isFsError(error) && error.code === ErrorCode.NOT_FOUND) || isNotFoundErrno(error))\n ) {\n return { status: 'noop', item: { path: inputPath } };\n }\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n\n if (fs.pathGuard.isAllowedRoot(validPath)) {\n return {\n status: 'fail',\n // Keyed by the REQUESTED path, like every other failure here: handleDelete\n // orders results by input path, and a resolved key would not be found for\n // a relative request.\n failure: {\n path: inputPath,\n error: Problem.accessDenied('Deleting a workspace root directory is not allowed', {\n path: validPath,\n }),\n },\n };\n }\n\n let firstStats: LstatResult;\n try {\n firstStats = await fs.lstat(validPath);\n } catch (error) {\n if (isNotFoundErrno(error) && args.ignoreIfNotExists) {\n return { status: 'noop', item: { path: inputPath } };\n }\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n\n const itemType = getFileType(firstStats.stats);\n let hasChildren = false;\n if (args.recursive && itemType === 'directory') {\n try {\n hasChildren = await fs.hasChildrenUnchecked(validPath);\n } catch (error) {\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n }\n const pending = hasChildren;\n return { status: 'plan', plan: { inputPath, validPath, itemType, firstStats, pending } };\n}\n\nasync function performDeletion(\n validPath: string,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n isDirectory: boolean,\n fsOps: Pick<GuardedFileSystem, 'rm' | 'rmdir'>,\n): Promise<void> {\n if (isDirectory && !args.recursive) {\n await fsOps.rmdir(validPath);\n } else {\n await fsOps.rm(validPath, {\n recursive: args.recursive,\n force: args.ignoreIfNotExists,\n });\n }\n}\n\n/**\n * Phase 2 (mutation): TOCTOU re-stat against the plan's first stat, then\n * delete. A type or identity change across the confirmation gap fails closed\n * rather than deleting a replacement object the user never confirmed.\n */\nasync function finalizeDeletion(\n plan: DeletePlan,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n ctx: Pick<ToolCtx, 'fs' | 'log'>,\n): Promise<{ item: DeletedItem } | { failure: DeleteFailure }> {\n let currentStats: LstatResult;\n try {\n currentStats = await ctx.fs.lstat(plan.validPath);\n } catch (error) {\n if (isNotFoundErrno(error) && args.ignoreIfNotExists) {\n return { item: { path: plan.validPath } };\n }\n return { failure: toDeleteFailure(plan.inputPath, error) };\n }\n\n const currentItemType = getFileType(currentStats.stats);\n // Identity comparison, not just the coarse category: a swap during the\n // confirmation gap (delete original, create a same-named replacement) keeps\n // the type but changes dev/ino/birthtimeMs. birthtimeMs is the primary\n // cross-platform signal — dev/ino can read 0 on some non-POSIX drivers — so\n // combine all three rather than trusting dev/ino alone.\n const identityChanged =\n plan.firstStats.stats.dev !== currentStats.stats.dev ||\n plan.firstStats.stats.ino !== currentStats.stats.ino ||\n plan.firstStats.stats.birthtimeMs !== currentStats.stats.birthtimeMs;\n if (plan.itemType !== 'other' && (currentItemType !== plan.itemType || identityChanged)) {\n return {\n failure: {\n path: plan.validPath,\n error: Problem.invalidInput(\n `Delete failed: item type changed from ${plan.itemType} to ${currentItemType} during confirmation.`,\n { path: plan.validPath },\n ),\n },\n };\n }\n\n try {\n await performDeletion(plan.validPath, args, currentStats.stats.isDirectory(), ctx.fs);\n } catch (error) {\n return { failure: toDeleteFailure(plan.inputPath, error) };\n }\n\n ctx.log?.('info', `rm: ${plan.inputPath}`, 'delete');\n return { item: { path: plan.validPath } };\n}\n\n/**\n * Execute one planned path on the retry round. A pending path deletes only on\n * an accepted `confirm: true`; decline, cancel, or a missing key report\n * `CANCELLED` for that path (R3 proceed, R4/R5 cancelled). A non-pending path\n * deletes directly (R14: non-pending items proceed alongside accepted ones).\n */\nasync function executePlan(\n plan: DeletePlan,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n ctx: Pick<ToolCtx, 'fs' | 'inputResponses' | 'log'>,\n pendingSorted: readonly string[],\n): Promise<{ item: DeletedItem } | { failure: DeleteFailure } | { skipped: true; path: string }> {\n if (plan.pending) {\n const key = `confirm_${pendingSorted.indexOf(plan.validPath)}`;\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: true as const, path: plan.validPath };\n }\n if (choice !== 'delete') {\n return {\n failure: {\n path: plan.validPath,\n error: Problem.cancelled('Delete cancelled: confirmation was declined or missing', {\n path: plan.validPath,\n }),\n },\n };\n }\n }\n return finalizeDeletion(plan, args, ctx);\n}\n\nasync function handleDelete(\n args: DeleteInput,\n ctx: ToolCtx,\n): Promise<DeleteOutput | InputRequiredResult> {\n // Duplicate paths collapse: results are keyed by path, so a repeated entry\n // would emit two rows for one deletion and inflate `summary.total`.\n const paths = [...new Set(args.paths)];\n\n // Phase 1 (no mutation): plan every path.\n const planned = await processInParallel(\n paths,\n (inputPath) => planPath(inputPath, args, ctx.fs),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n const plans: DeletePlan[] = [];\n const earlyFailures: DeleteFailure[] = [];\n const earlyNoop: DeletedItem[] = [];\n for (const { value: r } of planned.results) {\n if (r.status === 'fail') earlyFailures.push(r.failure);\n else if (r.status === 'noop') earlyNoop.push(r.item);\n else plans.push(r.plan);\n }\n for (const { index, error } of planned.errors) {\n const path = paths[index] ?? '(unknown)';\n earlyFailures.push({ path, error: { code: ErrorCode.UNKNOWN, message: error.message } });\n }\n\n // Pending set: recursive + non-empty directories, sorted and de-duplicated.\n // `buildInputRequired` seals exactly this set into the requestState, and the\n // retried round recomputes it from the same args so a swapped retry (accept\n // for X, retry with Y) is rejected — the codec only proves the state was not\n // tampered, not that it matches the current request (R9).\n const pendingSorted = [...new Set(plans.filter((p) => p.pending).map((p) => p.validPath))].sort();\n\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required (atomic — R14: nothing deleted yet, not\n // even the non-pending items in the same call); a retry whose verified\n // state does not bind this pending set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip({\n op: 'delete',\n pending: pendingSorted,\n requestState: ctx.requestState,\n clientCapabilities: ctx.clientCapabilities,\n buildInputs: (ps) =>\n ps.map((p, i) =>\n choiceInput(\n `confirm_${i}`,\n `Permanently delete \"${p}\" and all its contents? This cannot be undone.`,\n [\n { value: 'delete', title: 'Delete' },\n { value: 'skip', title: 'Skip' },\n ],\n ),\n ),\n });\n if (round !== undefined) return round;\n }\n\n // Phase 2 (mutation): execute deletions for every planned path.\n const executed = await processInParallel(\n plans,\n (plan) => executePlan(plan, args, ctx, pendingSorted),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n // Collect by path first, then emit in the caller's input order so\n // `results[i]` lines up with `paths[i]` the way read/stat guarantee.\n const byPath = new Map<string, DeletePerPathResult>();\n const record = (path: string, entry: DeletePerPathResult): void => {\n byPath.set(path, entry);\n };\n for (const n of earlyNoop) record(n.path, { path: n.path, value: { deleted: true } });\n for (const f of earlyFailures) record(f.path, { path: f.path, error: f.error });\n for (const { value: r } of executed.results) {\n if ('skipped' in r) {\n record(r.path, { path: r.path, value: { deleted: false } });\n } else if ('failure' in r) {\n record(r.failure.path, { path: r.failure.path, error: r.failure.error });\n } else if (r.item.path) {\n record(r.item.path, { path: r.item.path, value: { deleted: true } });\n }\n }\n for (const { index, error } of executed.errors) {\n const plan = plans[index];\n const path = plan?.validPath ?? '(unknown)';\n record(path, {\n path,\n error: { code: ErrorCode.UNKNOWN, message: error.message },\n });\n }\n\n // A plan's `validPath` is the resolved absolute path, so a requested relative\n // path will not find itself in the map by name — fall back through the plan.\n const planByRequested = new Map(plans.map((p) => [p.inputPath, p.validPath]));\n const results: DeletePerPathResult[] = paths.map((requested) => {\n const resolved = planByRequested.get(requested);\n const entry =\n byPath.get(requested) ?? (resolved !== undefined ? byPath.get(resolved) : undefined);\n return (\n entry ?? {\n path: requested,\n error: { code: ErrorCode.UNKNOWN, message: 'Unknown delete failure' },\n }\n );\n });\n\n const failed = results.filter((r) => r.error !== undefined).length;\n return {\n results,\n summary: { total: results.length, succeeded: results.length - failed, failed },\n };\n}\n\nexport const DELETE_FILE = defineTool({\n name: 'delete',\n title: 'Delete File',\n description:\n 'Permanently delete one or more files, directories, or symlinks (max 1000 per call). This action is irreversible. ' +\n 'Pass paths: [...] — there is no single-path form. ' +\n 'Non-empty directories require recursive=true and additionally prompt the user to confirm each one, ' +\n 'so the call returns without deleting anything until that confirmation comes back; ' +\n 'a client that cannot prompt gets an error naming the alternative. ' +\n 'Workspace root directories cannot be deleted.',\n input: DeleteInputSchema,\n output: DeleteOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n defaultErrorCode: ErrorCode.UNKNOWN,\n progress: (args) => ({\n label: 'Delete',\n subject:\n args.paths.length === 1\n ? basename(args.paths[0] ?? '')\n : `${String(args.paths.length)} paths`,\n }),\n accessPaths: (args) => [...args.paths],\n run: async (args, ctx) => {\n const structured = await handleDelete(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(structured)) return structured;\n // Name every path and its outcome. The old text said \"deleted 2 paths\"\n // without saying which two, so a partial failure was unreadable without\n // parsing the structured half.\n const { failed, total } = structured.summary;\n // A lone failure carries its reason in the text. \"delete: . FAILED (0/1 ok)\"\n // made the model re-read structuredContent to learn it was ACCESS_DENIED;\n // with one path there is no ambiguity about which message applies.\n if (total === 1 && failed === 1) {\n const only = structured.results[0];\n return {\n structured,\n text: `delete: ${only?.path ?? ''} FAILED — ${only?.error?.message ?? 'unknown error'}`,\n };\n }\n const tokens = structured.results.map((r) => {\n const label = pathLabel(r.path);\n if (r.error) return `${label} FAILED`;\n return r.value?.deleted ? label : `${label} SKIPPED`;\n });\n const ratio = failed > 0 ? ` (${String(total - failed)}/${String(total)} ok)` : '';\n return { structured, text: `delete: ${joinRoster(tokens)}${ratio}` };\n },\n});\n"]}
|
package/dist/tools/edit.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAogBA,eAAO,MAAM,IAAI,
|
|
1
|
+
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAogBA,eAAO,MAAM,IAAI,mCAuEf,CAAC"}
|
package/dist/tools/edit.js
CHANGED
|
@@ -386,8 +386,6 @@ export const EDIT = defineTool({
|
|
|
386
386
|
'For glob-based bulk regex replacement across many files, use replace_text instead.',
|
|
387
387
|
input: EditFileInputSchema,
|
|
388
388
|
output: EditFileOutputSchema,
|
|
389
|
-
// Same per-path union as read, plus diff, which is present only under dryRun.
|
|
390
|
-
publishOutputSchema: true,
|
|
391
389
|
annotations: {
|
|
392
390
|
readOnlyHint: false,
|
|
393
391
|
idempotentHint: false,
|