@j0hanz/filesystem-mcp 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +27 -86
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +6 -31
  4. package/dist/cli.js.map +1 -1
  5. package/dist/core/fmt.d.ts +1 -1
  6. package/dist/core/fmt.d.ts.map +1 -1
  7. package/dist/core/fmt.js +0 -5
  8. package/dist/core/fmt.js.map +1 -1
  9. package/dist/core/input-required.d.ts +0 -9
  10. package/dist/core/input-required.d.ts.map +1 -1
  11. package/dist/core/input-required.js +4 -26
  12. package/dist/core/input-required.js.map +1 -1
  13. package/dist/core/primitives.d.ts +0 -1
  14. package/dist/core/primitives.d.ts.map +1 -1
  15. package/dist/core/primitives.js +0 -3
  16. package/dist/core/primitives.js.map +1 -1
  17. package/dist/core/schema.d.ts +0 -1
  18. package/dist/core/schema.d.ts.map +1 -1
  19. package/dist/core/schema.js +1 -1
  20. package/dist/core/schema.js.map +1 -1
  21. package/dist/prompts.d.ts.map +1 -1
  22. package/dist/prompts.js +5 -11
  23. package/dist/prompts.js.map +1 -1
  24. package/dist/tools/define.d.ts.map +1 -1
  25. package/dist/tools/define.js +4 -5
  26. package/dist/tools/define.js.map +1 -1
  27. package/dist/tools/progress.d.ts +2 -7
  28. package/dist/tools/progress.d.ts.map +1 -1
  29. package/dist/tools/progress.js +10 -26
  30. package/dist/tools/progress.js.map +1 -1
  31. package/dist/transport/http.d.ts.map +1 -1
  32. package/dist/transport/http.js +12 -12
  33. package/dist/transport/http.js.map +1 -1
  34. package/dist/transport/shared.d.ts +0 -5
  35. package/dist/transport/shared.d.ts.map +1 -1
  36. package/dist/transport/shared.js +4 -0
  37. package/dist/transport/shared.js.map +1 -1
  38. package/dist/transport/stdio.d.ts.map +1 -1
  39. package/dist/transport/stdio.js +54 -8
  40. package/dist/transport/stdio.js.map +1 -1
  41. package/package.json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AAW;IAC5C,OAAO,GAAG,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAuB;IAClD,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,OAAO,GAAG;SACP,KAAK,CAAC,SAAS,CAAC;SAChB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;SACpB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,MAAc;IAC5C,OAAO,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,gFAAgF;AAEhF,MAAM,CAAC,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AAEvD,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAW,EAAE,CAAC,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,EAAE,CAAC;AAE7E,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAW,EAAE,CAC/C,CAAC,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,GAAG,CAAC,CAAC;AAE5D,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC","sourcesContent":["import { delimiter } from 'node:path';\n\n/**\n * Minimal shared primitives with no intra-package dependencies.\n * Kept separate to avoid import cycles between observability.ts and util.ts.\n */\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** The four filesystem entry types. Produced by `resolveEntryType` (glob.ts)\n * and `getFileType` (fs.ts); published as the `FileType` schema. */\nexport const ENTRY_TYPES = ['file', 'directory', 'symlink', 'other'] as const;\nexport type EntryType = (typeof ENTRY_TYPES)[number];\n\nconst warnedFlagValues = new Set<string>();\n\n/**\n * Parse a boolean env flag: `true`/`1` enable, `false`/`0`/empty disable.\n * Any other value warns once per var (when `name` is given) and reads as\n * false, so a typo like `FS_ALLOW_SENSITIVE=yes` is never silent.\n */\nexport function parseTrueEnvFlag(value: string | undefined, name?: string): boolean {\n if (value === undefined) return false;\n const trimmed = value.trim().toLowerCase();\n if (trimmed === 'true' || trimmed === '1') return true;\n if (name && trimmed !== '' && trimmed !== 'false' && trimmed !== '0') {\n const key = `${name}:${trimmed}`;\n if (!warnedFlagValues.has(key)) {\n warnedFlagValues.add(key);\n // console.error, not Logger: this module stays dependency-free to avoid\n // import cycles (same precedent as parseLogLevel in observability.ts).\n console.error(\n `[warning] Invalid ${name} value: ${value} (must be \"true\" or \"1\"). Using default: false`,\n );\n }\n }\n return false;\n}\n\nexport function escapeRegexLiteral(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function splitDirList(val: string | undefined): string[] {\n if (!val) return [];\n return val\n .split(delimiter)\n .map((p) => p.trim())\n .filter((p) => p.length > 0);\n}\n\nexport function parseEnvDirList(envVar: string): string[] {\n return splitDirList(process.env[envVar]);\n}\n\n// ─── Path primitives (moved from path.ts to break the path↔sensitive cycle) ──\n\nexport const IS_WINDOWS = process.platform === 'win32';\n\nexport const isSlash = (code: number): boolean => code === 47 || code === 92;\n\nexport const isAlpha = (code: number): boolean =>\n (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n\nexport const toPosixPath = (value: string): string => value.replaceAll('\\\\', '/');\n"]}
1
+ {"version":3,"file":"primitives.js","sourceRoot":"","sources":["../../src/core/primitives.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AA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M,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,MAAc;IAC5C,OAAO,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,gFAAgF;AAEhF,MAAM,CAAC,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AAEvD,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAW,EAAE,CAAC,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,EAAE,CAAC;AAE7E,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAW,EAAE,CAC/C,CAAC,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,GAAG,CAAC,CAAC;AAE5D,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC","sourcesContent":["import { delimiter } from 'node:path';\n\n/**\n * Minimal shared primitives with no intra-package dependencies.\n * Kept separate to avoid import cycles between observability.ts and util.ts.\n */\n\n/** The four filesystem entry types. Produced by `resolveEntryType` (glob.ts)\n * and `getFileType` (fs.ts); published as the `FileType` schema. */\nexport const ENTRY_TYPES = ['file', 'directory', 'symlink', 'other'] as const;\nexport type EntryType = (typeof ENTRY_TYPES)[number];\n\nconst warnedFlagValues = new Set<string>();\n\n/**\n * Parse a boolean env flag: `true`/`1` enable, `false`/`0`/empty disable.\n * Any other value warns once per var (when `name` is given) and reads as\n * false, so a typo like `FS_ALLOW_SENSITIVE=yes` is never silent.\n */\nexport function parseTrueEnvFlag(value: string | undefined, name?: string): boolean {\n if (value === undefined) return false;\n const trimmed = value.trim().toLowerCase();\n if (trimmed === 'true' || trimmed === '1') return true;\n if (name && trimmed !== '' && trimmed !== 'false' && trimmed !== '0') {\n const key = `${name}:${trimmed}`;\n if (!warnedFlagValues.has(key)) {\n warnedFlagValues.add(key);\n // console.error, not Logger: this module stays dependency-free to avoid\n // import cycles (same precedent as parseLogLevel in observability.ts).\n console.error(\n `[warning] Invalid ${name} value: ${value} (must be \"true\" or \"1\"). Using default: false`,\n );\n }\n }\n return false;\n}\n\nexport function escapeRegexLiteral(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function splitDirList(val: string | undefined): string[] {\n if (!val) return [];\n return val\n .split(delimiter)\n .map((p) => p.trim())\n .filter((p) => p.length > 0);\n}\n\nexport function parseEnvDirList(envVar: string): string[] {\n return splitDirList(process.env[envVar]);\n}\n\n// ─── Path primitives (moved from path.ts to break the path↔sensitive cycle) ──\n\nexport const IS_WINDOWS = process.platform === 'win32';\n\nexport const isSlash = (code: number): boolean => code === 47 || code === 92;\n\nexport const isAlpha = (code: number): boolean =>\n (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n\nexport const toPosixPath = (value: string): string => value.replaceAll('\\\\', '/');\n"]}
@@ -20,7 +20,6 @@ export declare const FileKind: z.ZodEnum<{
20
20
  audio: "audio";
21
21
  pdf: "pdf";
22
22
  }>;
23
- export declare const SHELL_METACHAR_RE: RegExp;
24
23
  export declare const isBlank: (val: string) => boolean;
25
24
  export declare const OptionalPath: z.ZodOptional<z.ZodString>;
26
25
  export declare const RequiredPath: z.ZodString;
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAY5B,eAAO,MAAM,WAAW,kBAMtB,CAAC;AAIH,eAAO,MAAM,SAAS,aAG2D,CAAC;AAElF,eAAO,MAAM,SAAS,UAEoB,CAAC;AAE3C,eAAO,MAAM,WAAW,UAEe,CAAC;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AAG;IACtE,IAAI,EAAE,CAAC,CAAC,WAAW,CAAC,OAAO,YAAY,CAAC,CAAC;IACzC,KAAK,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC;CACvD,CAAC;AAEF,wBAAgB,uBAAuB,CAAC,MAAM,SAAS,CAAC,CAAC,WAAW,EAAE,IAAI,EAAE;IAC1E,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,GAAG,CAAC,CAAC,SAAS,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CA4C1C;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE;IAC7C,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;IAC7B,KAAK,CAAC,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,GAAG,SAAS,CAAC;CACjD,GAAG,MAAM,EAAE,CAKX;AAQD,eAAO,MAAM,kBAAkB;;;;;;;;kBAM7B,CAAC;AAQH,eAAO,MAAM,YAAY,4BAKtB,CAAC;AAEJ,eAAO,MAAM,gBAAgB,4BAEgD,CAAC"}
@@ -32,7 +32,7 @@ export const FileType = z.enum(FILE_TYPES);
32
32
  const FILE_KINDS = MIME_KINDS;
33
33
  export const FileKind = z.enum(FILE_KINDS);
34
34
  const MAX_PATH_LENGTH = 4096;
35
- export const SHELL_METACHAR_RE = /[\n\r;|`]/;
35
+ const SHELL_METACHAR_RE = /[\n\r;|`]/;
36
36
  export const isBlank = (val) => val.trim().length === 0;
37
37
  const PathBase = z
38
38
  .string()
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,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AAE,CAAC;AACZ,CAAC;AAED,+DAA+D;AAC/D,+DAA+D;AAC/D,6EAA6E;AAC7E,+EAA+E;AAC/E,gFAAgF;AAChF,sEAAsE;AACtE,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC,YAAY,CAAC;IAC/C,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,sCAAsC,CAAC;IACjE,IAAI,EAAE,CAAC;SACJ,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC;SAChF,QAAQ,CAAC,yDAAyD,CAAC;IACtE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,iEAAiE,CAAC;CAC7F,CAAC,CAAC;AAEH,0EAA0E;AAC1E,8EAA8E;AAC9E,6EAA6E;AAC7E,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;AAE7D,0EAA0E;AAC1E,MAAM,CAAC,MAAM,YAAY,GAAG,eAAe;KACxC,QAAQ,EAAE;KACV,QAAQ,CACP,uFAAuF;IACrF,2FAA2F,CAC9F,CAAC;AAEJ,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe;KAC5C,QAAQ,EAAE;KACV,QAAQ,CAAC,gEAAgE,CAAC,CAAC","sourcesContent":["import * as z from 'zod/v4';\n\nimport { isSafeGlobSyntax } from './glob.js';\nimport { MIME_KINDS } from './mime.js';\nimport { ENTRY_TYPES } from './primitives.js';\nimport { MAX_SEARCH_DEPTH } from './util.js';\n\n// Runtime: full ISO-8601 UTC; emits the standard `date-time` format on the wire\n// (no AJV warning — it is a known format, unlike sha256_hex / base64url).\n// No `id` on this or any other shared schema below: an `id` hoists the schema\n// into `$defs` and leaves a `$ref` at every use site, which is exactly the wire\n// weight `toDraft202012` (tools/define.ts) publishes without.\nexport const IsoDateTime = z.iso.datetime().meta({\n description: 'ISO 8601 UTC date-time string (e.g. 2024-01-15T12:00:00.000Z)',\n // `format: \"date-time\"` already pins the value; zod's ~330-char calendar\n // regex is pure wire weight. Runtime validation still runs it — this\n // suppresses the emitted keyword only.\n pattern: undefined,\n});\n\n// pattern (not z.hash('sha256')) so no `format: \"sha256_hex\"` keyword is emitted;\n// the SDK's AJV validator warns on that unknown format at every server start.\nexport const Sha256Hex = z\n .string()\n .regex(/^[0-9a-f]{64}$/)\n .meta({ description: 'SHA-256 digest as a 64-character lowercase hex string' });\n\nexport const NonNegInt = z\n .int({ message: 'Must be integer' })\n .nonnegative({ message: 'Must be ≥ 0' });\n\nexport const PositiveInt = z\n .int({ message: 'Must be integer' })\n .positive({ message: 'Must be > 0' });\n\nconst FILE_TYPES = ENTRY_TYPES;\nexport type FileType = (typeof FILE_TYPES)[number];\nexport const FileType = z.enum(FILE_TYPES);\n\nconst FILE_KINDS = MIME_KINDS;\nexport type FileKind = (typeof FILE_KINDS)[number];\nexport const FileKind = z.enum(FILE_KINDS);\n\nconst MAX_PATH_LENGTH = 4096;\n\nexport const SHELL_METACHAR_RE = /[\\n\\r;|`]/;\n\nexport const isBlank = (val: string): boolean => val.trim().length === 0;\n\nconst PathBase = z\n .string()\n .min(1, { message: 'Path required' })\n .max(MAX_PATH_LENGTH, { message: `Path too long (max ${MAX_PATH_LENGTH} chars)` })\n .superRefine((val, ctx) => {\n if (val.length === 0) {\n return;\n }\n if (val.trim().length === 0) {\n ctx.addIssue({\n code: 'custom',\n message: 'Path cannot be empty or whitespace-only',\n fatal: true,\n });\n return z.NEVER;\n }\n if (val.includes('\\0')) {\n ctx.addIssue({\n code: 'custom',\n message: 'Path cannot contain null bytes',\n fatal: true,\n });\n return z.NEVER;\n }\n if (val.includes('..')) {\n ctx.addIssue({\n code: 'custom',\n message: 'Directory traversal sequences (\"..\") are forbidden',\n fatal: true,\n });\n return z.NEVER;\n }\n if (SHELL_METACHAR_RE.test(val)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Path contains prohibited characters (newlines or shell metacharacters)',\n fatal: true,\n });\n return z.NEVER;\n }\n })\n .describe('File or directory path inside an allowed workspace root.');\n\nexport const OptionalPath = PathBase.optional();\nexport const RequiredPath = PathBase;\n\nexport const SafeGlobPattern = z\n .string()\n .min(1, { message: 'Pattern required' })\n .max(1000, { message: 'Max 1000 chars' })\n .superRefine((val, ctx) => {\n if (val.length === 0) {\n return;\n }\n if (val.trim().length === 0) {\n ctx.addIssue({\n code: 'custom',\n message: 'Pattern cannot be empty or whitespace-only',\n fatal: true,\n });\n return z.NEVER;\n }\n if (val.includes('\\0')) {\n ctx.addIssue({\n code: 'custom',\n message: 'Pattern cannot contain null bytes',\n fatal: true,\n });\n return z.NEVER;\n }\n if (!isSafeGlobSyntax(val)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Invalid glob or unsafe path (absolute/.. forbidden)',\n fatal: true,\n });\n return z.NEVER;\n }\n if (SHELL_METACHAR_RE.test(val)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Pattern contains prohibited characters (newlines or shell metacharacters)',\n fatal: true,\n });\n return z.NEVER;\n }\n })\n .describe('Relative glob pattern under the search root (e.g. \"**/*.ts\", \"src/**/*.js\").')\n .meta({ examples: ['**/*.ts', 'src/**/*.js', '*.{ts,tsx}'] });\n\n// Only the fields whose key does not already say what they hold carry a\n// description. A `.describe('Name')` on `name` costs every client tokens to\n// learn nothing.\nexport const FileInfoSchema = z.strictObject({\n name: z.string(),\n path: z.string(),\n type: FileType,\n // A directory's own inode size says nothing about what is inside it — 0 on\n // Windows, 4096 on ext4 — so say so rather than letting a caller read it as\n // \"empty\". This caveat used to live in stat's text summary, which is gone.\n size: NonNegInt.describe('Bytes; meaningless for a directory — use list for its contents'),\n tokenEstimate: NonNegInt.optional().describe('Rough token estimate; use to pre-screen read cost'),\n created: IsoDateTime,\n modified: IsoDateTime,\n accessed: IsoDateTime,\n permissions: z.string(),\n isHidden: z.boolean(),\n mimeType: z.string().optional(),\n symlinkTarget: z.string().optional().describe('Target (symlink)'),\n});\n\nexport const OperationSummarySchema = z.strictObject({\n total: NonNegInt,\n succeeded: NonNegInt,\n failed: NonNegInt,\n});\n\nexport const PerFileErrorSchema = z.strictObject({\n code: z.string(),\n message: z.string(),\n path: z.string().optional(),\n suggestion: z.string().optional(),\n});\n\n/** One entry of a tool's `failures[]`: the path that failed and why. */\nexport const PathFailureSchema = z.strictObject({\n path: z.string(),\n error: PerFileErrorSchema,\n});\n\n/**\n * One entry of a source→destination tool's `failures[]`. The verb and noun stay\n * per-op so the `.describe()` text reads correctly for each caller.\n */\nexport function pairFailureSchema(verb: 'copied' | 'moved', noun: 'copy' | 'move') {\n return z.strictObject({\n source: z.string().describe(`Source path that could not be ${verb}`),\n destination: z.string().describe(`Intended destination path for the failed ${noun}`),\n error: PerFileErrorSchema,\n });\n}\n\n/** Wire shape of a `pairFailureSchema` entry — the runtime twin of the schema. */\nexport type PairFailureItem = z.infer<ReturnType<typeof pairFailureSchema>>;\n\n// TODO(future): Wrap createReadRangeFields output in a typed Zod object with built-in\n// cross-validation. Safe for now — the only caller (read.ts) calls validateReadRange in its own superRefine.\ninterface ReadRangeDescriptions {\n head: string;\n tail: string;\n startLine: string;\n endLine: string;\n}\n\nexport function createReadRangeFields(descs: ReadRangeDescriptions) {\n return {\n head: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.head),\n tail: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.tail),\n startLine: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.startLine),\n endLine: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.endLine),\n };\n}\n\nexport function validateReadRange(\n value: {\n head?: number | undefined;\n tail?: number | undefined;\n startLine?: number | undefined;\n endLine?: number | undefined;\n },\n ctx: z.RefinementCtx,\n): void {\n const hasHead = value.head !== undefined;\n const hasTail = value.tail !== undefined;\n const hasStart = value.startLine !== undefined;\n const hasEnd = value.endLine !== undefined;\n\n if (hasHead && (hasStart || hasEnd)) {\n ctx.addIssue({\n code: 'custom',\n path: ['head'],\n message: \"Cannot use 'head' with 'startLine'/'endLine'\",\n params: {\n rule: 'head_no_line_range',\n conflictsWith: ['startLine', 'endLine'],\n suggestion: \"Use either 'head' alone or 'startLine'/'endLine' together.\",\n },\n input: value,\n });\n }\n if (hasTail && (hasHead || hasStart || hasEnd)) {\n ctx.addIssue({\n code: 'custom',\n path: ['tail'],\n message: \"Cannot use 'tail' with 'head'/'startLine'/'endLine'\",\n params: {\n rule: 'tail_exclusive',\n conflictsWith: ['head', 'startLine', 'endLine'],\n suggestion: \"Use 'tail' alone or use 'startLine'/'endLine' without 'tail'.\",\n },\n input: value,\n });\n }\n if (hasEnd && !hasStart) {\n ctx.addIssue({\n code: 'custom',\n path: ['endLine'],\n message: \"'endLine' requires 'startLine' to be set\",\n params: {\n rule: 'endLine_requires_startLine',\n suggestion: \"Provide both 'startLine' and 'endLine' together.\",\n },\n input: value,\n });\n }\n const effectiveStart = value.startLine ?? 1;\n if (value.endLine !== undefined && value.endLine < effectiveStart) {\n ctx.addIssue({\n code: 'custom',\n path: ['endLine'],\n message: \"'endLine' must be >= 'startLine'\",\n params: {\n rule: 'endLine_gte_startLine',\n conflictsWith: ['startLine'],\n suggestion: 'Set endLine to a value greater than or equal to startLine.',\n },\n input: value,\n });\n }\n}\n\nexport function defaultFalseBoolean(description: string): z.ZodDefault<z.ZodBoolean> {\n return z.boolean().default(false).describe(description);\n}\n\nexport const includeHiddenField = (): z.ZodDefault<z.ZodBoolean> =>\n defaultFalseBoolean('Include hidden items (starting with .)');\nexport const includeIgnoredField = (): z.ZodDefault<z.ZodBoolean> =>\n defaultFalseBoolean('Include ignored items (node_modules, .git, etc).');\nexport const maxDepthField = (): z.ZodOptional<z.ZodNumber> =>\n z\n .uint32()\n .min(0)\n .max(MAX_SEARCH_DEPTH)\n .optional()\n .describe('Max directory depth to scan; 0 = base directory only, omit for unlimited');\n\nconst DEFAULT_MAX_BATCH = 1000;\n\nexport type SingleOrBatchShape<TExtra extends z.ZodRawShape> = TExtra & {\n path: z.ZodOptional<typeof RequiredPath>;\n paths: z.ZodOptional<z.ZodArray<typeof RequiredPath>>;\n};\n\nexport function singleOrBatchPathsInput<TExtra extends z.ZodRawShape>(opts: {\n extra: TExtra;\n maxBatch?: number;\n}): z.ZodObject<SingleOrBatchShape<TExtra>> {\n const maxBatch = opts.maxBatch ?? DEFAULT_MAX_BATCH;\n\n const shape: z.ZodRawShape = {\n ...opts.extra,\n path: RequiredPath.optional().describe('Single file path; mutually exclusive with paths'),\n paths: z\n .array(RequiredPath)\n .min(1)\n .max(maxBatch)\n .optional()\n .describe(\n `Array of file paths for batch mode (max ${String(maxBatch)}); mutually exclusive with path`,\n ),\n };\n\n const base = z.strictObject(shape).superRefine((value, ctx) => {\n const hasPath = value['path'] !== undefined;\n const hasPaths = value['paths'] !== undefined;\n\n if (!hasPath && !hasPaths) {\n ctx.addIssue({\n code: 'custom',\n path: ['path'],\n message: \"Either 'path' or 'paths' must be provided\",\n input: value,\n });\n return;\n }\n if (hasPath && hasPaths) {\n ctx.addIssue({\n code: 'custom',\n path: ['paths'],\n message: \"Cannot use both 'path' and 'paths'\",\n input: value,\n });\n }\n });\n\n // Mirror the superRefine above on the wire: exactly one input mode. `{}` and\n // `path`+`paths` both fail this oneOf, matching the runtime rule.\n return base.meta({\n oneOf: [{ required: ['path'] }, { required: ['paths'] }],\n }) as z.ZodObject<SingleOrBatchShape<TExtra>>;\n}\n\n/**\n * Extract the filesystem paths from a {@link singleOrBatchPathsInput} shape\n * (`{ path?, paths?, files?[{path}] }`) for the executor's access-grant\n * pre-check. Exactly one of the three is set (enforced by the schema's\n * superRefine), so they are checked in priority order.\n */\nexport function singleOrBatchAccessPaths(args: {\n path?: string | undefined;\n paths?: string[] | undefined;\n files?: readonly { path: string }[] | undefined;\n}): string[] {\n if (args.path) return [args.path];\n if (args.paths) return [...args.paths];\n if (args.files) return args.files.map((f) => f.path);\n return [];\n}\n\n// `args` is the exact argument object the one producer (read's\n// buildReadContinuation) emits, not a free-form record: a bare\n// `z.record(z.string(), z.unknown())` renders as `additionalProperties: {}`,\n// which carries no validation keyword and constrains nothing — the Inspector's\n// portability check flags it, and a client cannot tell what to pass. Widen this\n// (to a union) only when a second tool starts emitting continuations.\nexport const ContinuationSchema = z.strictObject({\n tool: z.string().describe('Tool name to call for the next chunk'),\n args: z\n .strictObject({ path: z.string(), startLine: PositiveInt, endLine: PositiveInt })\n .describe('Ready-to-use arguments for the next call; pass verbatim'),\n hint: z.string().describe('One-sentence description of the data still remaining to be read'),\n});\n\n// ponytail: charset regex, not z.base64url() — the SDK's AJV warns on the\n// unknown `base64url` format; the server's own decode (cursor.ts) is the real\n// validation, so loosening the client-facing schema to the alphabet is safe.\nconst base64urlCursor = z.string().regex(/^[A-Za-z0-9_-]+$/);\n\n// Ships once per paginated tool — wording is budgeted (TOOL-SURFACE-002).\nexport const CursorSchema = base64urlCursor\n .optional()\n .describe(\n 'Opaque pagination cursor; pass unchanged for the next page. Pages slice one snapshot ' +\n 'taken on the first call; it expires after ~60s — re-request without a cursor if rejected.',\n );\n\nexport const NextCursorSchema = base64urlCursor\n .optional()\n .describe('Cursor for the next page; omitted when this is the final page.');\n"]}
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/core/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE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AC/C,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,sCAAsC,CAAC;IACjE,IAAI,EAAE,CAAC;SACJ,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC;SAChF,QAAQ,CAAC,yDAAyD,CAAC;IACtE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,iEAAiE,CAAC;CAC7F,CAAC,CAAC;AAEH,0EAA0E;AAC1E,8EAA8E;AAC9E,6EAA6E;AAC7E,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;AAE7D,0EAA0E;AAC1E,MAAM,CAAC,MAAM,YAAY,GAAG,eAAe;KACxC,QAAQ,EAAE;KACV,QAAQ,CACP,uFAAuF;IACrF,2FAA2F,CAC9F,CAAC;AAEJ,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe;KAC5C,QAAQ,EAAE;KACV,QAAQ,CAAC,gEAAgE,CAAC,CAAC","sourcesContent":["import * as z from 'zod/v4';\n\nimport { isSafeGlobSyntax } from './glob.js';\nimport { MIME_KINDS } from './mime.js';\nimport { ENTRY_TYPES } from './primitives.js';\nimport { MAX_SEARCH_DEPTH } from './util.js';\n\n// Runtime: full ISO-8601 UTC; emits the standard `date-time` format on the wire\n// (no AJV warning — it is a known format, unlike sha256_hex / base64url).\n// No `id` on this or any other shared schema below: an `id` hoists the schema\n// into `$defs` and leaves a `$ref` at every use site, which is exactly the wire\n// weight `toDraft202012` (tools/define.ts) publishes without.\nexport const IsoDateTime = z.iso.datetime().meta({\n description: 'ISO 8601 UTC date-time string (e.g. 2024-01-15T12:00:00.000Z)',\n // `format: \"date-time\"` already pins the value; zod's ~330-char calendar\n // regex is pure wire weight. Runtime validation still runs it — this\n // suppresses the emitted keyword only.\n pattern: undefined,\n});\n\n// pattern (not z.hash('sha256')) so no `format: \"sha256_hex\"` keyword is emitted;\n// the SDK's AJV validator warns on that unknown format at every server start.\nexport const Sha256Hex = z\n .string()\n .regex(/^[0-9a-f]{64}$/)\n .meta({ description: 'SHA-256 digest as a 64-character lowercase hex string' });\n\nexport const NonNegInt = z\n .int({ message: 'Must be integer' })\n .nonnegative({ message: 'Must be ≥ 0' });\n\nexport const PositiveInt = z\n .int({ message: 'Must be integer' })\n .positive({ message: 'Must be > 0' });\n\nconst FILE_TYPES = ENTRY_TYPES;\nexport type FileType = (typeof FILE_TYPES)[number];\nexport const FileType = z.enum(FILE_TYPES);\n\nconst FILE_KINDS = MIME_KINDS;\nexport type FileKind = (typeof FILE_KINDS)[number];\nexport const FileKind = z.enum(FILE_KINDS);\n\nconst MAX_PATH_LENGTH = 4096;\n\nconst SHELL_METACHAR_RE = /[\\n\\r;|`]/;\n\nexport const isBlank = (val: string): boolean => val.trim().length === 0;\n\nconst PathBase = z\n .string()\n .min(1, { message: 'Path required' })\n .max(MAX_PATH_LENGTH, { message: `Path too long (max ${MAX_PATH_LENGTH} chars)` })\n .superRefine((val, ctx) => {\n if (val.length === 0) {\n return;\n }\n if (val.trim().length === 0) {\n ctx.addIssue({\n code: 'custom',\n message: 'Path cannot be empty or whitespace-only',\n fatal: true,\n });\n return z.NEVER;\n }\n if (val.includes('\\0')) {\n ctx.addIssue({\n code: 'custom',\n message: 'Path cannot contain null bytes',\n fatal: true,\n });\n return z.NEVER;\n }\n if (val.includes('..')) {\n ctx.addIssue({\n code: 'custom',\n message: 'Directory traversal sequences (\"..\") are forbidden',\n fatal: true,\n });\n return z.NEVER;\n }\n if (SHELL_METACHAR_RE.test(val)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Path contains prohibited characters (newlines or shell metacharacters)',\n fatal: true,\n });\n return z.NEVER;\n }\n })\n .describe('File or directory path inside an allowed workspace root.');\n\nexport const OptionalPath = PathBase.optional();\nexport const RequiredPath = PathBase;\n\nexport const SafeGlobPattern = z\n .string()\n .min(1, { message: 'Pattern required' })\n .max(1000, { message: 'Max 1000 chars' })\n .superRefine((val, ctx) => {\n if (val.length === 0) {\n return;\n }\n if (val.trim().length === 0) {\n ctx.addIssue({\n code: 'custom',\n message: 'Pattern cannot be empty or whitespace-only',\n fatal: true,\n });\n return z.NEVER;\n }\n if (val.includes('\\0')) {\n ctx.addIssue({\n code: 'custom',\n message: 'Pattern cannot contain null bytes',\n fatal: true,\n });\n return z.NEVER;\n }\n if (!isSafeGlobSyntax(val)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Invalid glob or unsafe path (absolute/.. forbidden)',\n fatal: true,\n });\n return z.NEVER;\n }\n if (SHELL_METACHAR_RE.test(val)) {\n ctx.addIssue({\n code: 'custom',\n message: 'Pattern contains prohibited characters (newlines or shell metacharacters)',\n fatal: true,\n });\n return z.NEVER;\n }\n })\n .describe('Relative glob pattern under the search root (e.g. \"**/*.ts\", \"src/**/*.js\").')\n .meta({ examples: ['**/*.ts', 'src/**/*.js', '*.{ts,tsx}'] });\n\n// Only the fields whose key does not already say what they hold carry a\n// description. A `.describe('Name')` on `name` costs every client tokens to\n// learn nothing.\nexport const FileInfoSchema = z.strictObject({\n name: z.string(),\n path: z.string(),\n type: FileType,\n // A directory's own inode size says nothing about what is inside it — 0 on\n // Windows, 4096 on ext4 — so say so rather than letting a caller read it as\n // \"empty\". This caveat used to live in stat's text summary, which is gone.\n size: NonNegInt.describe('Bytes; meaningless for a directory — use list for its contents'),\n tokenEstimate: NonNegInt.optional().describe('Rough token estimate; use to pre-screen read cost'),\n created: IsoDateTime,\n modified: IsoDateTime,\n accessed: IsoDateTime,\n permissions: z.string(),\n isHidden: z.boolean(),\n mimeType: z.string().optional(),\n symlinkTarget: z.string().optional().describe('Target (symlink)'),\n});\n\nexport const OperationSummarySchema = z.strictObject({\n total: NonNegInt,\n succeeded: NonNegInt,\n failed: NonNegInt,\n});\n\nexport const PerFileErrorSchema = z.strictObject({\n code: z.string(),\n message: z.string(),\n path: z.string().optional(),\n suggestion: z.string().optional(),\n});\n\n/** One entry of a tool's `failures[]`: the path that failed and why. */\nexport const PathFailureSchema = z.strictObject({\n path: z.string(),\n error: PerFileErrorSchema,\n});\n\n/**\n * One entry of a source→destination tool's `failures[]`. The verb and noun stay\n * per-op so the `.describe()` text reads correctly for each caller.\n */\nexport function pairFailureSchema(verb: 'copied' | 'moved', noun: 'copy' | 'move') {\n return z.strictObject({\n source: z.string().describe(`Source path that could not be ${verb}`),\n destination: z.string().describe(`Intended destination path for the failed ${noun}`),\n error: PerFileErrorSchema,\n });\n}\n\n/** Wire shape of a `pairFailureSchema` entry — the runtime twin of the schema. */\nexport type PairFailureItem = z.infer<ReturnType<typeof pairFailureSchema>>;\n\n// TODO(future): Wrap createReadRangeFields output in a typed Zod object with built-in\n// cross-validation. Safe for now — the only caller (read.ts) calls validateReadRange in its own superRefine.\ninterface ReadRangeDescriptions {\n head: string;\n tail: string;\n startLine: string;\n endLine: string;\n}\n\nexport function createReadRangeFields(descs: ReadRangeDescriptions) {\n return {\n head: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.head),\n tail: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.tail),\n startLine: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.startLine),\n endLine: z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(descs.endLine),\n };\n}\n\nexport function validateReadRange(\n value: {\n head?: number | undefined;\n tail?: number | undefined;\n startLine?: number | undefined;\n endLine?: number | undefined;\n },\n ctx: z.RefinementCtx,\n): void {\n const hasHead = value.head !== undefined;\n const hasTail = value.tail !== undefined;\n const hasStart = value.startLine !== undefined;\n const hasEnd = value.endLine !== undefined;\n\n if (hasHead && (hasStart || hasEnd)) {\n ctx.addIssue({\n code: 'custom',\n path: ['head'],\n message: \"Cannot use 'head' with 'startLine'/'endLine'\",\n params: {\n rule: 'head_no_line_range',\n conflictsWith: ['startLine', 'endLine'],\n suggestion: \"Use either 'head' alone or 'startLine'/'endLine' together.\",\n },\n input: value,\n });\n }\n if (hasTail && (hasHead || hasStart || hasEnd)) {\n ctx.addIssue({\n code: 'custom',\n path: ['tail'],\n message: \"Cannot use 'tail' with 'head'/'startLine'/'endLine'\",\n params: {\n rule: 'tail_exclusive',\n conflictsWith: ['head', 'startLine', 'endLine'],\n suggestion: \"Use 'tail' alone or use 'startLine'/'endLine' without 'tail'.\",\n },\n input: value,\n });\n }\n if (hasEnd && !hasStart) {\n ctx.addIssue({\n code: 'custom',\n path: ['endLine'],\n message: \"'endLine' requires 'startLine' to be set\",\n params: {\n rule: 'endLine_requires_startLine',\n suggestion: \"Provide both 'startLine' and 'endLine' together.\",\n },\n input: value,\n });\n }\n const effectiveStart = value.startLine ?? 1;\n if (value.endLine !== undefined && value.endLine < effectiveStart) {\n ctx.addIssue({\n code: 'custom',\n path: ['endLine'],\n message: \"'endLine' must be >= 'startLine'\",\n params: {\n rule: 'endLine_gte_startLine',\n conflictsWith: ['startLine'],\n suggestion: 'Set endLine to a value greater than or equal to startLine.',\n },\n input: value,\n });\n }\n}\n\nexport function defaultFalseBoolean(description: string): z.ZodDefault<z.ZodBoolean> {\n return z.boolean().default(false).describe(description);\n}\n\nexport const includeHiddenField = (): z.ZodDefault<z.ZodBoolean> =>\n defaultFalseBoolean('Include hidden items (starting with .)');\nexport const includeIgnoredField = (): z.ZodDefault<z.ZodBoolean> =>\n defaultFalseBoolean('Include ignored items (node_modules, .git, etc).');\nexport const maxDepthField = (): z.ZodOptional<z.ZodNumber> =>\n z\n .uint32()\n .min(0)\n .max(MAX_SEARCH_DEPTH)\n .optional()\n .describe('Max directory depth to scan; 0 = base directory only, omit for unlimited');\n\nconst DEFAULT_MAX_BATCH = 1000;\n\nexport type SingleOrBatchShape<TExtra extends z.ZodRawShape> = TExtra & {\n path: z.ZodOptional<typeof RequiredPath>;\n paths: z.ZodOptional<z.ZodArray<typeof RequiredPath>>;\n};\n\nexport function singleOrBatchPathsInput<TExtra extends z.ZodRawShape>(opts: {\n extra: TExtra;\n maxBatch?: number;\n}): z.ZodObject<SingleOrBatchShape<TExtra>> {\n const maxBatch = opts.maxBatch ?? DEFAULT_MAX_BATCH;\n\n const shape: z.ZodRawShape = {\n ...opts.extra,\n path: RequiredPath.optional().describe('Single file path; mutually exclusive with paths'),\n paths: z\n .array(RequiredPath)\n .min(1)\n .max(maxBatch)\n .optional()\n .describe(\n `Array of file paths for batch mode (max ${String(maxBatch)}); mutually exclusive with path`,\n ),\n };\n\n const base = z.strictObject(shape).superRefine((value, ctx) => {\n const hasPath = value['path'] !== undefined;\n const hasPaths = value['paths'] !== undefined;\n\n if (!hasPath && !hasPaths) {\n ctx.addIssue({\n code: 'custom',\n path: ['path'],\n message: \"Either 'path' or 'paths' must be provided\",\n input: value,\n });\n return;\n }\n if (hasPath && hasPaths) {\n ctx.addIssue({\n code: 'custom',\n path: ['paths'],\n message: \"Cannot use both 'path' and 'paths'\",\n input: value,\n });\n }\n });\n\n // Mirror the superRefine above on the wire: exactly one input mode. `{}` and\n // `path`+`paths` both fail this oneOf, matching the runtime rule.\n return base.meta({\n oneOf: [{ required: ['path'] }, { required: ['paths'] }],\n }) as z.ZodObject<SingleOrBatchShape<TExtra>>;\n}\n\n/**\n * Extract the filesystem paths from a {@link singleOrBatchPathsInput} shape\n * (`{ path?, paths?, files?[{path}] }`) for the executor's access-grant\n * pre-check. Exactly one of the three is set (enforced by the schema's\n * superRefine), so they are checked in priority order.\n */\nexport function singleOrBatchAccessPaths(args: {\n path?: string | undefined;\n paths?: string[] | undefined;\n files?: readonly { path: string }[] | undefined;\n}): string[] {\n if (args.path) return [args.path];\n if (args.paths) return [...args.paths];\n if (args.files) return args.files.map((f) => f.path);\n return [];\n}\n\n// `args` is the exact argument object the one producer (read's\n// buildReadContinuation) emits, not a free-form record: a bare\n// `z.record(z.string(), z.unknown())` renders as `additionalProperties: {}`,\n// which carries no validation keyword and constrains nothing — the Inspector's\n// portability check flags it, and a client cannot tell what to pass. Widen this\n// (to a union) only when a second tool starts emitting continuations.\nexport const ContinuationSchema = z.strictObject({\n tool: z.string().describe('Tool name to call for the next chunk'),\n args: z\n .strictObject({ path: z.string(), startLine: PositiveInt, endLine: PositiveInt })\n .describe('Ready-to-use arguments for the next call; pass verbatim'),\n hint: z.string().describe('One-sentence description of the data still remaining to be read'),\n});\n\n// ponytail: charset regex, not z.base64url() — the SDK's AJV warns on the\n// unknown `base64url` format; the server's own decode (cursor.ts) is the real\n// validation, so loosening the client-facing schema to the alphabet is safe.\nconst base64urlCursor = z.string().regex(/^[A-Za-z0-9_-]+$/);\n\n// Ships once per paginated tool — wording is budgeted (TOOL-SURFACE-002).\nexport const CursorSchema = base64urlCursor\n .optional()\n .describe(\n 'Opaque pagination cursor; pass unchanged for the next page. Pages slice one snapshot ' +\n 'taken on the first call; it expires after ~60s — re-request without a cursor if rejected.',\n );\n\nexport const NextCursorSchema = base64urlCursor\n .optional()\n .describe('Cursor for the next page; omitted when this is the final page.');\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,SAAS,EAGV,MAAM,8BAA8B,CAAC;AAkBtC,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AA+DD,wBAAgB,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAoC/D"}
1
+ {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,SAAS,EAGV,MAAM,8BAA8B,CAAC;AAiBtC,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AAyDD,wBAAgB,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAoC/D"}
package/dist/prompts.js CHANGED
@@ -2,20 +2,14 @@ import { completable, getDisplayName, ProtocolError } from '@modelcontextprotoco
2
2
  import * as z from 'zod/v4';
3
3
  import { formatUnknownErrorMessage, fsErrorCode, hasErrorShape } from './core/errors.js';
4
4
  import { Logger } from './core/observability.js';
5
- import { isBlank, SHELL_METACHAR_RE } from './core/schema.js';
6
5
  import { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';
7
6
  // --- Helpers ---
8
7
  function topicArg(topics, description) {
9
- return completable(z
10
- .string()
11
- .min(1, { message: 'Topic required' })
12
- .refine((val) => !isBlank(val), {
13
- message: 'Topic cannot be empty or whitespace-only',
14
- })
15
- .refine((val) => !SHELL_METACHAR_RE.test(val), {
16
- message: 'Topic contains prohibited characters (newlines or shell metacharacters)',
17
- })
18
- .describe(description), (value) => {
8
+ return completable(
9
+ // No content validation beyond non-empty: the handler resolves a topic by
10
+ // `Object.hasOwn` against a frozen record, so anything unrecognized already
11
+ // falls through to the not-found reply without reaching an interpreter.
12
+ z.string().min(1, { message: 'Topic required' }).describe(description), (value) => {
19
13
  const lower = value.toLowerCase();
20
14
  return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];
21
15
  });
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAE1F,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACzF,OAAO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,KAAK;QACrB,WAAW,EAAE,QAAQ,CAAC,WAAW;QACjC,UAAU,EAAE,CAAC,CAAC,YAAY,CAAC;YACzB,KAAK,EAAE,QAAQ,CACb,MAAM,EACN,+CAA+C,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,qCAAqC,CACtG,CAAC,QAAQ,EAAE;SACb,CAAC;KACH,EACD,CAAC,EAAE,KAAK,EAAkC,EAA8C,EAAE,CACxF,WAAW,CAAC,QAAQ,EAAE,GAAG,EAAE;QACzB,MAAM,UAAU,GAAG,KAAK,EAAE,WAAW,EAAE,CAAC;QACxC,MAAM,OAAO,GACX,UAAU,IAAI,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACvF,IAAI,KAAK,IAAI,CAAC,OAAO,EAAE,CAAC;YACtB,MAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/D,CAAC;QACD,MAAM,IAAI,GACR,OAAO;YACP,CAAC,KAAK;gBACJ,CAAC,CAAC,YAAY,KAAK,2BAA2B,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,YAAY,EAAE;gBACpF,CAAC,CAAC,YAAY,CAAC,CAAC;QACpB,OAAO;YACL,WAAW,EAAE,QAAQ,CAAC,WAAW;YACjC,QAAQ,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC,CAAC,CACL,CAAC;AACJ,CAAC","sourcesContent":["import type {\n GetPromptResult,\n McpServer,\n PromptMessage,\n TextContent,\n} from '@modelcontextprotocol/server';\nimport { completable, getDisplayName, ProtocolError } from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { formatUnknownErrorMessage, fsErrorCode, hasErrorShape } from './core/errors.js';\nimport { Logger } from './core/observability.js';\nimport { isBlank, SHELL_METACHAR_RE } from './core/schema.js';\nimport { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';\n\n// --- Types ---\n\ninterface PromptContract {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n}\n\ninterface PromptRegistrarDeps {\n readonly server: McpServer;\n readonly readOnly?: boolean;\n}\n\n// --- Helpers ---\n\nfunction topicArg(\n topics: readonly string[],\n description: string,\n): ReturnType<typeof completable<z.ZodString>> {\n return completable(\n z\n .string()\n .min(1, { message: 'Topic required' })\n .refine((val) => !isBlank(val), {\n message: 'Topic cannot be empty or whitespace-only',\n })\n .refine((val) => !SHELL_METACHAR_RE.test(val), {\n message: 'Topic contains prohibited characters (newlines or shell metacharacters)',\n })\n .describe(description),\n (value) => {\n const lower = value.toLowerCase();\n return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];\n },\n );\n}\n\nfunction userText(text: string): PromptMessage {\n const content: TextContent = {\n type: 'text',\n text,\n annotations: { audience: ['assistant'], priority: 1 },\n };\n return { role: 'user', content };\n}\n\nasync function wrapHandler<T>(contract: PromptContract, fn: () => Promise<T> | T): Promise<T> {\n const displayName = getDisplayName(contract);\n\n try {\n const result = await fn();\n Logger.debug(`prompt resolved`, { name: contract.name, displayName });\n return result;\n } catch (error) {\n if (hasErrorShape(error, 'ProtocolError')) throw error;\n const message = formatUnknownErrorMessage(error);\n Logger.error(`Prompt handler failed: ${message}`, {\n promptName: contract.name,\n error,\n });\n const protocolError = new ProtocolError(fsErrorCode(error), message);\n protocolError.cause = error;\n throw protocolError;\n }\n}\n\n// --- Prompt entries ---\n\nconst GET_HELP: PromptContract = {\n name: 'get-help',\n title: 'Get Help',\n description: INSTRUCTIONS_SUMMARY,\n};\n\nexport function registerPrompts(deps: PromptRegistrarDeps): void {\n const sections = buildSectionsRecord(deps.readOnly ?? false);\n const instructions = renderSections(sections);\n const topics = Object.keys(sections);\n\n deps.server.registerPrompt(\n GET_HELP.name,\n {\n title: GET_HELP.title,\n description: GET_HELP.description,\n argsSchema: z.strictObject({\n topic: topicArg(\n topics,\n `Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`,\n ).optional(),\n }),\n },\n ({ topic }: { topic?: string | undefined }): GetPromptResult | Promise<GetPromptResult> =>\n wrapHandler(GET_HELP, () => {\n const lowerTopic = topic?.toLowerCase();\n const section =\n lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;\n if (topic && !section) {\n Logger.debug('get-help: unknown topic requested', { topic });\n }\n const text =\n section ??\n (topic\n ? `Section '${topic}' not found. Available: ${topics.join(', ')}\\n\\n${instructions}`\n : instructions);\n return {\n description: GET_HELP.description,\n messages: [userText(text)],\n };\n }),\n );\n}\n"]}
1
+ {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAE1F,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACzF,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAe9F,kBAAkB;AAElB,SAAS,QAAQ,CACf,MAAyB,EACzB,WAAmB;IAEnB,OAAO,WAAW;IAChB,0EAA0E;IAC1E,4EAA4E;IAC5E,wEAAwE;IACxE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,EACtE,CAAC,KAAK,EAAE,EAAE;QACR,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;QAClC,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAA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F,CAAC,CAAC,YAAY,CAAC,CAAC;QACpB,OAAO;YACL,WAAW,EAAE,QAAQ,CAAC,WAAW;YACjC,QAAQ,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;SAC3B,CAAC;IACJ,CAAC,CAAC,CACL,CAAC;AACJ,CAAC","sourcesContent":["import type {\n GetPromptResult,\n McpServer,\n PromptMessage,\n TextContent,\n} from '@modelcontextprotocol/server';\nimport { completable, getDisplayName, ProtocolError } from '@modelcontextprotocol/server';\n\nimport * as z from 'zod/v4';\n\nimport { formatUnknownErrorMessage, fsErrorCode, hasErrorShape } from './core/errors.js';\nimport { Logger } from './core/observability.js';\nimport { buildSectionsRecord, INSTRUCTIONS_SUMMARY, renderSections } from './instructions.js';\n\n// --- Types ---\n\ninterface PromptContract {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n}\n\ninterface PromptRegistrarDeps {\n readonly server: McpServer;\n readonly readOnly?: boolean;\n}\n\n// --- Helpers ---\n\nfunction topicArg(\n topics: readonly string[],\n description: string,\n): ReturnType<typeof completable<z.ZodString>> {\n return completable(\n // No content validation beyond non-empty: the handler resolves a topic by\n // `Object.hasOwn` against a frozen record, so anything unrecognized already\n // falls through to the not-found reply without reaching an interpreter.\n z.string().min(1, { message: 'Topic required' }).describe(description),\n (value) => {\n const lower = value.toLowerCase();\n return lower ? topics.filter((t) => t.startsWith(lower)) : [...topics];\n },\n );\n}\n\nfunction userText(text: string): PromptMessage {\n const content: TextContent = {\n type: 'text',\n text,\n annotations: { audience: ['assistant'], priority: 1 },\n };\n return { role: 'user', content };\n}\n\nasync function wrapHandler<T>(contract: PromptContract, fn: () => Promise<T> | T): Promise<T> {\n const displayName = getDisplayName(contract);\n\n try {\n const result = await fn();\n Logger.debug(`prompt resolved`, { name: contract.name, displayName });\n return result;\n } catch (error) {\n if (hasErrorShape(error, 'ProtocolError')) throw error;\n const message = formatUnknownErrorMessage(error);\n Logger.error(`Prompt handler failed: ${message}`, {\n promptName: contract.name,\n error,\n });\n const protocolError = new ProtocolError(fsErrorCode(error), message);\n protocolError.cause = error;\n throw protocolError;\n }\n}\n\n// --- Prompt entries ---\n\nconst GET_HELP: PromptContract = {\n name: 'get-help',\n title: 'Get Help',\n description: INSTRUCTIONS_SUMMARY,\n};\n\nexport function registerPrompts(deps: PromptRegistrarDeps): void {\n const sections = buildSectionsRecord(deps.readOnly ?? false);\n const instructions = renderSections(sections);\n const topics = Object.keys(sections);\n\n deps.server.registerPrompt(\n GET_HELP.name,\n {\n title: GET_HELP.title,\n description: GET_HELP.description,\n argsSchema: z.strictObject({\n topic: topicArg(\n topics,\n `Section key to filter instructions (one of: ${topics.join(', ')}); omit to return all instructions.`,\n ).optional(),\n }),\n },\n ({ topic }: { topic?: string | undefined }): GetPromptResult | Promise<GetPromptResult> =>\n wrapHandler(GET_HELP, () => {\n const lowerTopic = topic?.toLowerCase();\n const section =\n lowerTopic && Object.hasOwn(sections, lowerTopic) ? sections[lowerTopic] : undefined;\n if (topic && !section) {\n Logger.debug('get-help: unknown topic requested', { topic });\n }\n const text =\n section ??\n (topic\n ? `Section '${topic}' not found. Available: ${topics.join(', ')}\\n\\n${instructions}`\n : instructions);\n return {\n description: GET_HELP.description,\n messages: [userText(text)],\n };\n }),\n );\n}\n"]}
@@ -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,EACT,YAAY,EACZ,cAAc,EACd,WAAW,EACX,oBAAoB,EAEpB,eAAe,EAChB,MAAM,8BAA8B,CAAC;AAOtC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAsC,MAAM,mBAAmB,CAAC;AAClF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eA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AY,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IACvF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,SAAS,CAAC;IACtC;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,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;AAsYD,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"}
@@ -133,15 +133,14 @@ class ToolExecutor {
133
133
  this.parsedArgs = parsedArgs;
134
134
  this.signal = composeSignal(ctx.signal, def.timeoutMs);
135
135
  this.#progressCtx = resolveProgressCtx(def, parsedArgs);
136
- const sinks = [];
137
- if (ctx._meta?.progressToken !== undefined && ctx.sendNotification !== undefined) {
138
- this.#mcpSink = new McpProgressSink(toolName, ctx._meta.progressToken, ctx.sendNotification);
139
- sinks.push(this.#mcpSink);
136
+ const token = ctx._meta?.progressToken;
137
+ if (token !== undefined && ctx.sendNotification !== undefined) {
138
+ this.#mcpSink = new McpProgressSink(toolName, token, ctx.sendNotification);
140
139
  }
141
140
  const isTest = process.env['NODE_ENV'] === 'test' || process.execArgv.includes('--test');
142
141
  this.#progressSession = new ProgressSession({
143
142
  label: this.#progressCtx.label,
144
- sinks,
143
+ ...(this.#mcpSink ? { sink: this.#mcpSink } : {}),
145
144
  ...(isTest ? { rateLimitMs: 0 } : {}),
146
145
  });
147
146
  this.toolCtx = {
@@ -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;AAiGjE,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,EAA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GAAG,CAAC,GAAG,CAAC,WAAW,CAAC,YAAY;YAC9B,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,eAAe,EAAE,GAAG,CAAC,WAAW,CAAC,eAAe,IAAI,IAAI,EAAE,CAAC;KAClE,CAAC;IAEF,MAAM,YAAY,GAAG;QACnB,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,WAAW,EAAE,cAAc,CAAa,eAAe,EAAE,sBAAsB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC3F,sEAAsE;QACtE,4EAA4E;QAC5E,0DAA0D;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
+ {"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;AAGnD,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAiGjE,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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YAC9B,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,eAAe,EAAE,GAAG,CAAC,WAAW,CAAC,eAAe,IAAI,IAAI,EAAE,CAAC;KAClE,CAAC;IAEF,MAAM,YAAY,GAAG;QACnB,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,WAAW,EAAE,cAAc,CAAa,eAAe,EAAE,sBAAsB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC3F,sEAAsE;QACtE,4EAA4E;QAC5E,0DAA0D;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 { 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 token = ctx._meta?.progressToken;\n if (token !== undefined && ctx.sendNotification !== undefined) {\n this.#mcpSink = new McpProgressSink(toolName, token, ctx.sendNotification);\n }\n const isTest = process.env['NODE_ENV'] === 'test' || process.execArgv.includes('--test');\n this.#progressSession = new ProgressSession({\n label: this.#progressCtx.label,\n ...(this.#mcpSink ? { sink: this.#mcpSink } : {}),\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"]}
@@ -16,14 +16,10 @@ export type ProgressEvent = {
16
16
  message: string;
17
17
  error: unknown;
18
18
  };
19
- export interface ProgressSink {
20
- readonly name: string;
21
- readonly emit: (event: ProgressEvent) => Promise<void> | void;
22
- }
23
19
  interface ProgressSessionOptions {
24
20
  label: string;
25
21
  total?: number;
26
- sinks: ProgressSink[];
22
+ sink?: McpProgressSink;
27
23
  /** Override the rate limit window. Default: 50ms. */
28
24
  rateLimitMs?: number;
29
25
  }
@@ -38,9 +34,8 @@ export declare class ProgressSession {
38
34
  complete(message: string): void;
39
35
  fail(error: unknown, message?: string): void;
40
36
  }
41
- export declare class McpProgressSink implements ProgressSink {
37
+ export declare class McpProgressSink {
42
38
  #private;
43
- readonly name = "mcp";
44
39
  private readonly toolName;
45
40
  private readonly token;
46
41
  private readonly notify;
@@ -1 +1 @@
1
- {"version":3,"file":"progress.d.ts","sourceRoot":"","sources":["../../src/tools/progress.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA8B,MAAM,8BAA8B,CAAC;AAU7F,MAAM,MAAM,aAAa,GACrB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAClE;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACtE;IACE,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IA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AE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,MAAM,EACtB,MAAM,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC;IAO5C,IAAI,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IAsC1B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAK7B"}
@@ -8,7 +8,7 @@ const DEFAULT_RATE_LIMIT_MS = 50;
8
8
  export class ProgressSession {
9
9
  #label;
10
10
  #total;
11
- #sinks;
11
+ #sink;
12
12
  #rateLimitMs;
13
13
  #startTime;
14
14
  #cursor = 0;
@@ -17,7 +17,7 @@ export class ProgressSession {
17
17
  constructor(opts) {
18
18
  this.#label = opts.label;
19
19
  this.#total = opts.total;
20
- this.#sinks = opts.sinks;
20
+ this.#sink = opts.sink;
21
21
  this.#rateLimitMs = opts.rateLimitMs ?? DEFAULT_RATE_LIMIT_MS;
22
22
  const now = Date.now();
23
23
  this.#startTime = now;
@@ -75,8 +75,14 @@ export class ProgressSession {
75
75
  return;
76
76
  }
77
77
  this.#lastSentMs = Date.now();
78
- for (const sink of this.#sinks) {
79
- this.#emitGuarded(sink, event);
78
+ if (!this.#sink)
79
+ return;
80
+ try {
81
+ this.#sink.emit(event);
82
+ }
83
+ catch (err) {
84
+ // A sink failure must never fail the tool call it is reporting on.
85
+ Logger.warn('progress sink emit failed', { eventKind: event.kind, err });
80
86
  }
81
87
  }
82
88
  #shouldRateLimit(event) {
@@ -90,30 +96,8 @@ export class ProgressSession {
90
96
  const elapsed = now - this.#lastSentMs;
91
97
  return elapsed < effectiveRateLimit;
92
98
  }
93
- #emitGuarded(sink, event) {
94
- try {
95
- const result = sink.emit(event);
96
- if (result instanceof Promise) {
97
- result.catch((err) => {
98
- Logger.warn('ProgressSink emit failed', {
99
- sink: sink.name,
100
- eventKind: event.kind,
101
- err,
102
- });
103
- });
104
- }
105
- }
106
- catch (err) {
107
- Logger.warn('ProgressSink emit failed', {
108
- sink: sink.name,
109
- eventKind: event.kind,
110
- err,
111
- });
112
- }
113
- }
114
99
  }
115
100
  export class McpProgressSink {
116
- name = 'mcp';
117
101
  toolName;
118
102
  token;
119
103
  notify;