@j0hanz/filesystem-mcp 1.19.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/README.md +333 -838
  2. package/dist/cli-help.d.ts +3 -0
  3. package/dist/cli-help.d.ts.map +1 -0
  4. package/dist/cli-help.js +169 -0
  5. package/dist/cli-help.js.map +1 -0
  6. package/dist/cli.d.ts +28 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +168 -123
  9. package/dist/cli.js.map +1 -0
  10. package/dist/core/concurrency.d.ts +70 -0
  11. package/dist/core/concurrency.d.ts.map +1 -0
  12. package/dist/core/concurrency.js +173 -0
  13. package/dist/core/concurrency.js.map +1 -0
  14. package/dist/core/config.d.ts +26 -0
  15. package/dist/core/config.d.ts.map +1 -0
  16. package/dist/core/config.js +18 -0
  17. package/dist/core/config.js.map +1 -0
  18. package/dist/core/cursor.d.ts +23 -0
  19. package/dist/core/cursor.d.ts.map +1 -0
  20. package/dist/core/cursor.js +62 -0
  21. package/dist/core/cursor.js.map +1 -0
  22. package/dist/core/errors.d.ts +96 -0
  23. package/dist/core/errors.d.ts.map +1 -0
  24. package/dist/core/errors.js +356 -0
  25. package/dist/core/errors.js.map +1 -0
  26. package/dist/core/file-uri.d.ts +24 -0
  27. package/dist/core/file-uri.d.ts.map +1 -0
  28. package/dist/core/file-uri.js +52 -0
  29. package/dist/core/file-uri.js.map +1 -0
  30. package/dist/core/fmt.d.ts +37 -0
  31. package/dist/core/fmt.d.ts.map +1 -0
  32. package/dist/core/fmt.js +93 -0
  33. package/dist/core/fmt.js.map +1 -0
  34. package/dist/core/fs.d.ts +108 -0
  35. package/dist/core/fs.d.ts.map +1 -0
  36. package/dist/core/fs.js +243 -0
  37. package/dist/core/fs.js.map +1 -0
  38. package/dist/core/glob.d.ts +41 -0
  39. package/dist/core/glob.d.ts.map +1 -0
  40. package/dist/core/glob.js +399 -0
  41. package/dist/core/glob.js.map +1 -0
  42. package/dist/core/input-required.d.ts +147 -0
  43. package/dist/core/input-required.d.ts.map +1 -0
  44. package/dist/core/input-required.js +261 -0
  45. package/dist/core/input-required.js.map +1 -0
  46. package/dist/core/mime.d.ts +15 -0
  47. package/dist/core/mime.d.ts.map +1 -0
  48. package/dist/core/mime.js +188 -0
  49. package/dist/core/mime.js.map +1 -0
  50. package/dist/core/observability.d.ts +10 -0
  51. package/dist/core/observability.d.ts.map +1 -0
  52. package/dist/core/observability.js +76 -0
  53. package/dist/core/observability.js.map +1 -0
  54. package/dist/core/page-store.d.ts +41 -0
  55. package/dist/core/page-store.d.ts.map +1 -0
  56. package/dist/core/page-store.js +74 -0
  57. package/dist/core/page-store.js.map +1 -0
  58. package/dist/core/path-completer.d.ts +10 -0
  59. package/dist/core/path-completer.d.ts.map +1 -0
  60. package/dist/core/path-completer.js +227 -0
  61. package/dist/core/path-completer.js.map +1 -0
  62. package/dist/core/path-discovery.d.ts +8 -0
  63. package/dist/core/path-discovery.d.ts.map +1 -0
  64. package/dist/core/path-discovery.js +105 -0
  65. package/dist/core/path-discovery.js.map +1 -0
  66. package/dist/core/path-utils.d.ts +9 -0
  67. package/dist/core/path-utils.d.ts.map +1 -0
  68. package/dist/core/path-utils.js +121 -0
  69. package/dist/core/path-utils.js.map +1 -0
  70. package/dist/core/path.d.ts +148 -0
  71. package/dist/core/path.d.ts.map +1 -0
  72. package/dist/core/path.js +674 -0
  73. package/dist/core/path.js.map +1 -0
  74. package/dist/core/primitives.d.ts +23 -0
  75. package/dist/core/primitives.d.ts.map +1 -0
  76. package/dist/core/primitives.js +54 -0
  77. package/dist/core/primitives.js.map +1 -0
  78. package/dist/core/read.d.ts +74 -0
  79. package/dist/core/read.d.ts.map +1 -0
  80. package/dist/core/read.js +562 -0
  81. package/dist/core/read.js.map +1 -0
  82. package/dist/core/schema.d.ts +139 -0
  83. package/dist/core/schema.d.ts.map +1 -0
  84. package/dist/core/schema.js +348 -0
  85. package/dist/core/schema.js.map +1 -0
  86. package/dist/core/search.d.ts +100 -0
  87. package/dist/core/search.d.ts.map +1 -0
  88. package/dist/core/search.js +248 -0
  89. package/dist/core/search.js.map +1 -0
  90. package/dist/core/sensitive.d.ts +6 -0
  91. package/dist/core/sensitive.d.ts.map +1 -0
  92. package/dist/core/sensitive.js +142 -0
  93. package/dist/core/sensitive.js.map +1 -0
  94. package/dist/core/store.d.ts +57 -0
  95. package/dist/core/store.d.ts.map +1 -0
  96. package/dist/core/store.js +162 -0
  97. package/dist/core/store.js.map +1 -0
  98. package/dist/core/util.d.ts +24 -0
  99. package/dist/core/util.d.ts.map +1 -0
  100. package/dist/core/util.js +65 -0
  101. package/dist/core/util.js.map +1 -0
  102. package/dist/core/watcher-registry.d.ts +68 -0
  103. package/dist/core/watcher-registry.d.ts.map +1 -0
  104. package/dist/core/watcher-registry.js +312 -0
  105. package/dist/core/watcher-registry.js.map +1 -0
  106. package/dist/http-policy.d.ts +121 -0
  107. package/dist/http-policy.d.ts.map +1 -0
  108. package/dist/http-policy.js +340 -0
  109. package/dist/http-policy.js.map +1 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.d.ts.map +1 -0
  112. package/dist/index.js +77 -41
  113. package/dist/index.js.map +1 -0
  114. package/dist/instructions.d.ts +11 -0
  115. package/dist/instructions.d.ts.map +1 -0
  116. package/dist/instructions.js +70 -0
  117. package/dist/instructions.js.map +1 -0
  118. package/dist/prompts.d.ts +8 -6
  119. package/dist/prompts.d.ts.map +1 -0
  120. package/dist/prompts.js +74 -168
  121. package/dist/prompts.js.map +1 -0
  122. package/dist/resources.d.ts +73 -9
  123. package/dist/resources.d.ts.map +1 -0
  124. package/dist/resources.js +392 -163
  125. package/dist/resources.js.map +1 -0
  126. package/dist/server.d.ts +62 -1
  127. package/dist/server.d.ts.map +1 -0
  128. package/dist/server.js +139 -1
  129. package/dist/server.js.map +1 -0
  130. package/dist/tools/batch.d.ts +89 -0
  131. package/dist/tools/batch.d.ts.map +1 -0
  132. package/dist/tools/batch.js +157 -0
  133. package/dist/tools/batch.js.map +1 -0
  134. package/dist/tools/create.d.ts +2 -0
  135. package/dist/tools/create.d.ts.map +1 -0
  136. package/dist/tools/create.js +124 -0
  137. package/dist/tools/create.js.map +1 -0
  138. package/dist/tools/define.d.ts +102 -0
  139. package/dist/tools/define.d.ts.map +1 -0
  140. package/dist/tools/define.js +404 -0
  141. package/dist/tools/define.js.map +1 -0
  142. package/dist/tools/delete-file.d.ts +2 -4
  143. package/dist/tools/delete-file.d.ts.map +1 -0
  144. package/dist/tools/delete-file.js +327 -87
  145. package/dist/tools/delete-file.js.map +1 -0
  146. package/dist/tools/diff.d.ts +2 -0
  147. package/dist/tools/diff.d.ts.map +1 -0
  148. package/dist/tools/diff.js +94 -0
  149. package/dist/tools/diff.js.map +1 -0
  150. package/dist/tools/edit.d.ts +2 -0
  151. package/dist/tools/edit.d.ts.map +1 -0
  152. package/dist/tools/edit.js +440 -0
  153. package/dist/tools/edit.js.map +1 -0
  154. package/dist/tools/index.d.ts +26 -0
  155. package/dist/tools/index.d.ts.map +1 -0
  156. package/dist/tools/index.js +52 -0
  157. package/dist/tools/index.js.map +1 -0
  158. package/dist/tools/list.d.ts +2 -0
  159. package/dist/tools/list.d.ts.map +1 -0
  160. package/dist/tools/list.js +301 -0
  161. package/dist/tools/list.js.map +1 -0
  162. package/dist/tools/move.d.ts +2 -0
  163. package/dist/tools/move.d.ts.map +1 -0
  164. package/dist/tools/move.js +321 -0
  165. package/dist/tools/move.js.map +1 -0
  166. package/dist/tools/patch.d.ts +2 -0
  167. package/dist/tools/patch.d.ts.map +1 -0
  168. package/dist/tools/patch.js +155 -0
  169. package/dist/tools/patch.js.map +1 -0
  170. package/dist/tools/progress.d.ts +52 -0
  171. package/dist/tools/progress.d.ts.map +1 -0
  172. package/dist/tools/progress.js +172 -0
  173. package/dist/tools/progress.js.map +1 -0
  174. package/dist/tools/read.d.ts +2 -4
  175. package/dist/tools/read.d.ts.map +1 -0
  176. package/dist/tools/read.js +423 -150
  177. package/dist/tools/read.js.map +1 -0
  178. package/dist/tools/replace-in-files.d.ts +2 -4
  179. package/dist/tools/replace-in-files.d.ts.map +1 -0
  180. package/dist/tools/replace-in-files.js +432 -264
  181. package/dist/tools/replace-in-files.js.map +1 -0
  182. package/dist/tools/roots.d.ts +2 -4
  183. package/dist/tools/roots.d.ts.map +1 -0
  184. package/dist/tools/roots.js +45 -52
  185. package/dist/tools/roots.js.map +1 -0
  186. package/dist/tools/search-content.d.ts +2 -4
  187. package/dist/tools/search-content.d.ts.map +1 -0
  188. package/dist/tools/search-content.js +262 -228
  189. package/dist/tools/search-content.js.map +1 -0
  190. package/dist/tools/search-files.d.ts +2 -4
  191. package/dist/tools/search-files.d.ts.map +1 -0
  192. package/dist/tools/search-files.js +162 -161
  193. package/dist/tools/search-files.js.map +1 -0
  194. package/dist/tools/stat.d.ts +2 -4
  195. package/dist/tools/stat.d.ts.map +1 -0
  196. package/dist/tools/stat.js +189 -62
  197. package/dist/tools/stat.js.map +1 -0
  198. package/dist/transport/http.d.ts +5 -0
  199. package/dist/transport/http.d.ts.map +1 -0
  200. package/dist/transport/http.js +276 -0
  201. package/dist/transport/http.js.map +1 -0
  202. package/dist/transport/shared.d.ts +45 -0
  203. package/dist/transport/shared.d.ts.map +1 -0
  204. package/dist/transport/shared.js +65 -0
  205. package/dist/transport/shared.js.map +1 -0
  206. package/dist/transport/stdio.d.ts +32 -0
  207. package/dist/transport/stdio.d.ts.map +1 -0
  208. package/dist/transport/stdio.js +279 -0
  209. package/dist/transport/stdio.js.map +1 -0
  210. package/dist/transport.d.ts +5 -0
  211. package/dist/transport.d.ts.map +1 -0
  212. package/dist/transport.js +4 -0
  213. package/dist/transport.js.map +1 -0
  214. package/package.json +37 -46
  215. package/dist/assets/logo.svg +0 -35
  216. package/dist/completions.d.ts +0 -2
  217. package/dist/completions.js +0 -572
  218. package/dist/config.d.ts +0 -119
  219. package/dist/config.js +0 -31
  220. package/dist/lib/abort.d.ts +0 -7
  221. package/dist/lib/abort.js +0 -81
  222. package/dist/lib/constants.d.ts +0 -42
  223. package/dist/lib/constants.js +0 -313
  224. package/dist/lib/errors.d.ts +0 -28
  225. package/dist/lib/errors.js +0 -301
  226. package/dist/lib/file-operations/core.d.ts +0 -53
  227. package/dist/lib/file-operations/core.js +0 -144
  228. package/dist/lib/file-operations/metadata.d.ts +0 -77
  229. package/dist/lib/file-operations/metadata.js +0 -878
  230. package/dist/lib/file-operations/search.d.ts +0 -46
  231. package/dist/lib/file-operations/search.js +0 -1194
  232. package/dist/lib/file-operations/traversal.d.ts +0 -40
  233. package/dist/lib/file-operations/traversal.js +0 -310
  234. package/dist/lib/fs-helpers.d.ts +0 -46
  235. package/dist/lib/fs-helpers.js +0 -606
  236. package/dist/lib/globs.d.ts +0 -2
  237. package/dist/lib/globs.js +0 -19
  238. package/dist/lib/logger.d.ts +0 -27
  239. package/dist/lib/logger.js +0 -91
  240. package/dist/lib/observability.d.ts +0 -33
  241. package/dist/lib/observability.js +0 -373
  242. package/dist/lib/paths.d.ts +0 -35
  243. package/dist/lib/paths.js +0 -634
  244. package/dist/lib/resource-store.d.ts +0 -28
  245. package/dist/lib/resource-store.js +0 -195
  246. package/dist/lib/utils.d.ts +0 -7
  247. package/dist/lib/utils.js +0 -37
  248. package/dist/lib/zod-codecs.d.ts +0 -2
  249. package/dist/lib/zod-codecs.js +0 -18
  250. package/dist/pkg-info.d.ts +0 -7
  251. package/dist/pkg-info.js +0 -9
  252. package/dist/resources/generated-instructions.d.ts +0 -1
  253. package/dist/resources/generated-instructions.js +0 -105
  254. package/dist/resources/tool-catalog.d.ts +0 -2
  255. package/dist/resources/tool-catalog.js +0 -78
  256. package/dist/resources/tool-info.d.ts +0 -9
  257. package/dist/resources/tool-info.js +0 -206
  258. package/dist/resources/workflows.d.ts +0 -1
  259. package/dist/resources/workflows.js +0 -72
  260. package/dist/schemas.d.ts +0 -505
  261. package/dist/schemas.js +0 -676
  262. package/dist/server/bootstrap.d.ts +0 -6
  263. package/dist/server/bootstrap.js +0 -585
  264. package/dist/server/event-store.d.ts +0 -18
  265. package/dist/server/event-store.js +0 -71
  266. package/dist/server/roots-manager.d.ts +0 -28
  267. package/dist/server/roots-manager.js +0 -227
  268. package/dist/server/task-store.d.ts +0 -10
  269. package/dist/server/task-store.js +0 -91
  270. package/dist/tools/apply-patch.d.ts +0 -4
  271. package/dist/tools/apply-patch.js +0 -235
  272. package/dist/tools/calculate-hash.d.ts +0 -4
  273. package/dist/tools/calculate-hash.js +0 -187
  274. package/dist/tools/contract.d.ts +0 -50
  275. package/dist/tools/contract.js +0 -1
  276. package/dist/tools/create-directory.d.ts +0 -4
  277. package/dist/tools/create-directory.js +0 -68
  278. package/dist/tools/diff-files.d.ts +0 -4
  279. package/dist/tools/diff-files.js +0 -136
  280. package/dist/tools/edit-file.d.ts +0 -4
  281. package/dist/tools/edit-file.js +0 -256
  282. package/dist/tools/icons.d.ts +0 -15
  283. package/dist/tools/icons.js +0 -24
  284. package/dist/tools/list-directory.d.ts +0 -4
  285. package/dist/tools/list-directory.js +0 -218
  286. package/dist/tools/move-file.d.ts +0 -4
  287. package/dist/tools/move-file.js +0 -178
  288. package/dist/tools/read-multiple.d.ts +0 -4
  289. package/dist/tools/read-multiple.js +0 -207
  290. package/dist/tools/shared.d.ts +0 -172
  291. package/dist/tools/shared.js +0 -599
  292. package/dist/tools/stat-many.d.ts +0 -4
  293. package/dist/tools/stat-many.js +0 -104
  294. package/dist/tools/task-support.d.ts +0 -29
  295. package/dist/tools/task-support.js +0 -473
  296. package/dist/tools/tree.d.ts +0 -4
  297. package/dist/tools/tree.js +0 -102
  298. package/dist/tools/write-file.d.ts +0 -4
  299. package/dist/tools/write-file.js +0 -60
  300. package/dist/tools.d.ts +0 -5
  301. package/dist/tools.js +0 -54
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAiBA,OAAO,EACL,4BAA4B,EAC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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,4 +1,2 @@
1
- import type { McpServer } from '@modelcontextprotocol/server';
2
- import { type ToolContract, type ToolRegistrationOptions } from './shared.js';
3
- export declare const DELETE_FILE_TOOL: ToolContract;
4
- export declare function registerDeleteFileTool(server: McpServer, options?: ToolRegistrationOptions): void;
1
+ export declare const DELETE_FILE: import("./define.js").DefinedTool;
2
+ //# sourceMappingURL=delete-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delete-file.d.ts","sourceRoot":"","sources":["../../src/tools/delete-file.ts"],"names":[],"mappings":"AAwZA,eAAO,MAAM,WAAW,mCAsDtB,CAAC"}
@@ -1,101 +1,341 @@
1
- import { lstat, rm, rmdir } from 'node:fs/promises';
1
+ import { isInputRequiredResult } from '@modelcontextprotocol/server';
2
2
  import { basename } from 'node:path';
3
- import { withAbort } from '../lib/abort.js';
4
- import { ErrorCode, isNodeError, McpError } from '../lib/errors.js';
5
- import { Logger } from '../lib/logger.js';
6
- import { isAllowedDirectoryRoot, validatePathForWrite } from '../lib/paths.js';
7
- import { DeleteFileInputSchema, DeleteFileOutputSchema } from '../schemas.js';
8
- import { FILE_DELETE_ICONS } from './icons.js';
9
- import { buildToolErrorResponse, buildToolResponse, DESTRUCTIVE_WRITE_TOOL_ANNOTATIONS, executeToolWithDiagnostics, } from './shared.js';
10
- import { registerStandardTool } from './task-support.js';
11
- export const DELETE_FILE_TOOL = {
12
- name: 'rm',
13
- title: 'Delete File',
14
- description: 'Permanently delete a file or directory. This action is irreversible.',
15
- inputSchema: DeleteFileInputSchema,
16
- outputSchema: DeleteFileOutputSchema,
17
- annotations: DESTRUCTIVE_WRITE_TOOL_ANNOTATIONS,
18
- icons: FILE_DELETE_ICONS,
19
- gotchas: ['Non-empty directories require `recursive=true`.'],
20
- taskSupport: 'forbidden',
21
- };
22
- async function handleDeleteFile(args, signal) {
23
- const validPath = await validatePathForWrite(args.path, signal);
24
- if (isAllowedDirectoryRoot(validPath)) {
25
- throw new McpError(ErrorCode.ACCESS_DENIED, 'Deleting a workspace root directory is not allowed');
26
- }
27
- let stats;
3
+ import * as z from 'zod/v4';
4
+ import { processInParallel } from '../core/concurrency.js';
5
+ import { ErrorCode, FsError, isFsError, isNodeError, isNotFoundErrno, Problem, } from '../core/errors.js';
6
+ import { joinRoster, pathLabel } from '../core/fmt.js';
7
+ import { getFileType } from '../core/fs.js';
8
+ import { choiceInput, pendingRoundTrip, readAcceptedChoice } from '../core/input-required.js';
9
+ import { defaultFalseBoolean, OperationSummarySchema, PerFileErrorSchema, RequiredPath, } from '../core/schema.js';
10
+ import { PARALLEL_CONCURRENCY } from '../core/util.js';
11
+ import { defineTool } from './define.js';
12
+ const DeleteInputSchema = z.strictObject({
13
+ paths: z
14
+ .array(RequiredPath)
15
+ .min(1)
16
+ .max(1000)
17
+ .describe('Paths to delete (max 1000); accepts files, directories, or symlinks'),
18
+ recursive: defaultFalseBoolean('Delete directory contents recursively (required for non-empty directories)'),
19
+ ignoreIfNotExists: defaultFalseBoolean('Silently succeed if a path does not exist instead of returning an error'),
20
+ });
21
+ const DeletePerPathValueSchema = z.strictObject({
22
+ deleted: z.boolean().describe('True when the path was removed; false when the user chose Skip'),
23
+ });
24
+ const DeletePerPathSchema = z.strictObject({
25
+ path: z.string().describe('Requested path'),
26
+ value: DeletePerPathValueSchema.optional().describe('Delete outcome; present on success'),
27
+ error: PerFileErrorSchema.optional().describe('Error details; present on failure'),
28
+ });
29
+ // One envelope for every batch tool: `read` and `stat` already answer with
30
+ // `{ results, summary }`, so `delete` does too. The old shape switched between
31
+ // `{ ok, path }` and `{ ok: false, failures }` depending on the outcome, which
32
+ // left a caller parsing two schemas for one tool and never named the paths in a
33
+ // multi-delete's text.
34
+ const DeleteOutputSchema = z.strictObject({
35
+ results: z
36
+ .array(DeletePerPathSchema)
37
+ .describe('Per-path results ordered to match the input paths'),
38
+ summary: OperationSummarySchema,
39
+ });
40
+ const ERR_NOT_EMPTY = new Error('Directory not empty. Set recursive: true.');
41
+ function toDeleteFailure(path, error) {
42
+ // A missing path reached here as the raw errno text ("ENOENT: no such file or
43
+ // directory, lstat 'c:\...'"), while `stat` reported the same condition as
44
+ // "Path not found". One condition, one message — and the syscall name stays
45
+ // off the wire.
46
+ if (isNotFoundErrno(error)) {
47
+ return {
48
+ path,
49
+ error: Problem.toPerFileError(new FsError(ErrorCode.NOT_FOUND, 'Path not found', path), ErrorCode.NOT_FOUND, path),
50
+ };
51
+ }
52
+ if (isNodeError(error) &&
53
+ (error.code === 'ENOTEMPTY' || error.code === 'EISDIR' || error.code === 'EEXIST')) {
54
+ return {
55
+ path,
56
+ error: Problem.toPerFileError(ERR_NOT_EMPTY, ErrorCode.INVALID_INPUT, path),
57
+ };
58
+ }
59
+ return { path, error: Problem.toPerFileError(error, ErrorCode.UNKNOWN, path) };
60
+ }
61
+ /**
62
+ * Phase 1 (no mutation): validate, stat, and decide whether a path needs a
63
+ * confirmation before anything is deleted. A pending path is a recursive
64
+ * non-empty directory; everything else is ready to delete directly.
65
+ */
66
+ async function planPath(inputPath, args, fs) {
67
+ let validPath;
28
68
  try {
29
- stats = await withAbort(lstat(validPath), signal);
69
+ validPath = await fs.pathGuard.validatePathForDelete(inputPath);
30
70
  }
31
71
  catch (error) {
32
- if (isNodeError(error) &&
33
- error.code === 'ENOENT' &&
34
- args.ignoreIfNotExists) {
35
- return buildToolResponse(`Successfully deleted: ${args.path}`, {
36
- ok: true,
37
- path: validPath,
38
- });
72
+ if (args.ignoreIfNotExists &&
73
+ ((isFsError(error) && error.code === ErrorCode.NOT_FOUND) || isNotFoundErrno(error))) {
74
+ return { status: 'noop', item: { path: inputPath } };
39
75
  }
40
- throw error;
76
+ return { status: 'fail', failure: toDeleteFailure(inputPath, error) };
77
+ }
78
+ if (fs.pathGuard.isAllowedRoot(validPath)) {
79
+ return {
80
+ status: 'fail',
81
+ // Keyed by the REQUESTED path, like every other failure here: handleDelete
82
+ // orders results by input path, and a resolved key would not be found for
83
+ // a relative request.
84
+ failure: {
85
+ path: inputPath,
86
+ error: Problem.accessDenied('Deleting a workspace root directory is not allowed', {
87
+ path: validPath,
88
+ }),
89
+ },
90
+ };
41
91
  }
42
- if (stats.isDirectory() && !args.recursive) {
43
- // Use rmdir for non-recursive directory deletes so non-empty directories
44
- // consistently return ENOTEMPTY-style errors with actionable guidance.
45
- await withAbort(rmdir(validPath), signal);
92
+ let firstStats;
93
+ try {
94
+ firstStats = await fs.lstat(validPath);
95
+ }
96
+ catch (error) {
97
+ if (isNotFoundErrno(error) && args.ignoreIfNotExists) {
98
+ return { status: 'noop', item: { path: inputPath } };
99
+ }
100
+ return { status: 'fail', failure: toDeleteFailure(inputPath, error) };
101
+ }
102
+ const itemType = getFileType(firstStats.stats);
103
+ let hasChildren = false;
104
+ if (args.recursive && itemType === 'directory') {
105
+ try {
106
+ hasChildren = await fs.hasChildrenUnchecked(validPath);
107
+ }
108
+ catch (error) {
109
+ return { status: 'fail', failure: toDeleteFailure(inputPath, error) };
110
+ }
111
+ }
112
+ const pending = hasChildren;
113
+ return { status: 'plan', plan: { inputPath, validPath, itemType, firstStats, pending } };
114
+ }
115
+ async function performDeletion(validPath, args, isDirectory, fsOps) {
116
+ if (isDirectory && !args.recursive) {
117
+ await fsOps.rmdir(validPath);
46
118
  }
47
119
  else {
48
- await withAbort(rm(validPath, {
120
+ await fsOps.rm(validPath, {
49
121
  recursive: args.recursive,
50
122
  force: args.ignoreIfNotExists,
51
- }), signal);
123
+ });
52
124
  }
53
- Logger.info(`rm: ${args.path}`);
54
- return buildToolResponse(`Successfully deleted: ${args.path}`, {
55
- ok: true,
56
- path: validPath,
57
- });
58
125
  }
59
- export function registerDeleteFileTool(server, options = {}) {
60
- const handler = (args, ctx) => executeToolWithDiagnostics({
61
- toolName: 'rm',
62
- ctx,
63
- outputSchema: DeleteFileOutputSchema,
64
- timedSignal: {},
65
- context: { path: args.path },
66
- run: async (signal) => {
67
- const result = await handleDeleteFile(args, signal);
68
- void ctx.log?.('info', `rm: ${args.path}`);
69
- return result;
70
- },
71
- onError: (error) => {
72
- if (isNodeError(error)) {
73
- if (error.code === 'ENOENT') {
74
- return buildToolErrorResponse(error, ErrorCode.NOT_FOUND, args.path);
75
- }
76
- if (error.code === 'ENOTEMPTY') {
77
- return buildToolErrorResponse(new Error('Directory not empty. Set recursive: true.'), ErrorCode.INVALID_INPUT, args.path);
78
- }
79
- if (error.code === 'EISDIR') {
80
- return buildToolErrorResponse(new Error('Path is a directory. Set recursive: true.'), ErrorCode.INVALID_INPUT, args.path);
81
- }
82
- if (error.code === 'EEXIST') {
83
- return buildToolErrorResponse(new Error('Directory not empty. Set recursive: true.'), ErrorCode.INVALID_INPUT, args.path);
84
- }
85
- if (error.code === 'EPERM' || error.code === 'EACCES') {
86
- return buildToolErrorResponse(error, ErrorCode.PERMISSION_DENIED, args.path);
87
- }
88
- }
89
- return buildToolErrorResponse(error, ErrorCode.UNKNOWN, args.path);
90
- },
91
- });
92
- registerStandardTool(server, DELETE_FILE_TOOL, handler, options, {
93
- progressMessage: (args) => `${DELETE_FILE_TOOL.title}: ${basename(args.path)}`,
94
- completionMessage: (args, result) => {
95
- const name = basename(args.path);
96
- if (result.isError)
97
- return `${DELETE_FILE_TOOL.title}: ${name} • ${result.errorCode}`;
98
- return `${DELETE_FILE_TOOL.title}: ${name}`;
99
- },
126
+ /**
127
+ * Phase 2 (mutation): TOCTOU re-stat against the plan's first stat, then
128
+ * delete. A type or identity change across the confirmation gap fails closed
129
+ * rather than deleting a replacement object the user never confirmed.
130
+ */
131
+ async function finalizeDeletion(plan, args, ctx) {
132
+ let currentStats;
133
+ try {
134
+ currentStats = await ctx.fs.lstat(plan.validPath);
135
+ }
136
+ catch (error) {
137
+ if (isNotFoundErrno(error) && args.ignoreIfNotExists) {
138
+ return { item: { path: plan.validPath } };
139
+ }
140
+ return { failure: toDeleteFailure(plan.inputPath, error) };
141
+ }
142
+ const currentItemType = getFileType(currentStats.stats);
143
+ // Identity comparison, not just the coarse category: a swap during the
144
+ // confirmation gap (delete original, create a same-named replacement) keeps
145
+ // the type but changes dev/ino/birthtimeMs. birthtimeMs is the primary
146
+ // cross-platform signal dev/ino can read 0 on some non-POSIX drivers — so
147
+ // combine all three rather than trusting dev/ino alone.
148
+ const identityChanged = plan.firstStats.stats.dev !== currentStats.stats.dev ||
149
+ plan.firstStats.stats.ino !== currentStats.stats.ino ||
150
+ plan.firstStats.stats.birthtimeMs !== currentStats.stats.birthtimeMs;
151
+ if (plan.itemType !== 'other' && (currentItemType !== plan.itemType || identityChanged)) {
152
+ return {
153
+ failure: {
154
+ path: plan.validPath,
155
+ error: Problem.invalidInput(`Delete failed: item type changed from ${plan.itemType} to ${currentItemType} during confirmation.`, { path: plan.validPath }),
156
+ },
157
+ };
158
+ }
159
+ try {
160
+ await performDeletion(plan.validPath, args, currentStats.stats.isDirectory(), ctx.fs);
161
+ }
162
+ catch (error) {
163
+ return { failure: toDeleteFailure(plan.inputPath, error) };
164
+ }
165
+ ctx.log?.('info', `rm: ${plan.inputPath}`, 'delete');
166
+ return { item: { path: plan.validPath } };
167
+ }
168
+ /**
169
+ * Execute one planned path on the retry round. A pending path deletes only on
170
+ * an accepted `confirm: true`; decline, cancel, or a missing key report
171
+ * `CANCELLED` for that path (R3 proceed, R4/R5 cancelled). A non-pending path
172
+ * deletes directly (R14: non-pending items proceed alongside accepted ones).
173
+ */
174
+ async function executePlan(plan, args, ctx, pendingSorted) {
175
+ if (plan.pending) {
176
+ const key = `confirm_${pendingSorted.indexOf(plan.validPath)}`;
177
+ const choice = readAcceptedChoice(ctx.inputResponses, key);
178
+ if (choice === 'skip') {
179
+ return { skipped: true, path: plan.validPath };
180
+ }
181
+ if (choice !== 'delete') {
182
+ return {
183
+ failure: {
184
+ path: plan.validPath,
185
+ error: Problem.cancelled('Delete cancelled: confirmation was declined or missing', {
186
+ path: plan.validPath,
187
+ }),
188
+ },
189
+ };
190
+ }
191
+ }
192
+ return finalizeDeletion(plan, args, ctx);
193
+ }
194
+ async function handleDelete(args, ctx) {
195
+ // Duplicate paths collapse: results are keyed by path, so a repeated entry
196
+ // would emit two rows for one deletion and inflate `summary.total`.
197
+ const paths = [...new Set(args.paths)];
198
+ // Phase 1 (no mutation): plan every path.
199
+ const planned = await processInParallel(paths, (inputPath) => planPath(inputPath, args, ctx.fs), PARALLEL_CONCURRENCY, ctx.signal);
200
+ const plans = [];
201
+ const earlyFailures = [];
202
+ const earlyNoop = [];
203
+ for (const { value: r } of planned.results) {
204
+ if (r.status === 'fail')
205
+ earlyFailures.push(r.failure);
206
+ else if (r.status === 'noop')
207
+ earlyNoop.push(r.item);
208
+ else
209
+ plans.push(r.plan);
210
+ }
211
+ for (const { index, error } of planned.errors) {
212
+ const path = paths[index] ?? '(unknown)';
213
+ earlyFailures.push({ path, error: { code: ErrorCode.UNKNOWN, message: error.message } });
214
+ }
215
+ // Pending set: recursive + non-empty directories, sorted and de-duplicated.
216
+ // `buildInputRequired` seals exactly this set into the requestState, and the
217
+ // retried round recomputes it from the same args so a swapped retry (accept
218
+ // for X, retry with Y) is rejected — the codec only proves the state was not
219
+ // tampered, not that it matches the current request (R9).
220
+ const pendingSorted = [...new Set(plans.filter((p) => p.pending).map((p) => p.validPath))].sort();
221
+ if (pendingSorted.length > 0) {
222
+ // Round 1 returns input_required (atomic — R14: nothing deleted yet, not
223
+ // even the non-pending items in the same call); a retry whose verified
224
+ // state does not bind this pending set throws (R9) via `pendingRoundTrip`.
225
+ const round = await pendingRoundTrip({
226
+ op: 'delete',
227
+ pending: pendingSorted,
228
+ requestState: ctx.requestState,
229
+ clientCapabilities: ctx.clientCapabilities,
230
+ buildInputs: (ps) => ps.map((p, i) => choiceInput(`confirm_${i}`, `Permanently delete "${p}" and all its contents? This cannot be undone.`, [
231
+ { value: 'delete', title: 'Delete' },
232
+ { value: 'skip', title: 'Skip' },
233
+ ])),
234
+ });
235
+ if (round !== undefined)
236
+ return round;
237
+ }
238
+ // Phase 2 (mutation): execute deletions for every planned path.
239
+ const executed = await processInParallel(plans, (plan) => executePlan(plan, args, ctx, pendingSorted), PARALLEL_CONCURRENCY, ctx.signal);
240
+ // Collect by path first, then emit in the caller's input order so
241
+ // `results[i]` lines up with `paths[i]` the way read/stat guarantee.
242
+ const byPath = new Map();
243
+ const record = (path, entry) => {
244
+ byPath.set(path, entry);
245
+ };
246
+ for (const n of earlyNoop)
247
+ record(n.path, { path: n.path, value: { deleted: true } });
248
+ for (const f of earlyFailures)
249
+ record(f.path, { path: f.path, error: f.error });
250
+ for (const { value: r } of executed.results) {
251
+ if ('skipped' in r) {
252
+ record(r.path, { path: r.path, value: { deleted: false } });
253
+ }
254
+ else if ('failure' in r) {
255
+ record(r.failure.path, { path: r.failure.path, error: r.failure.error });
256
+ }
257
+ else if (r.item.path) {
258
+ record(r.item.path, { path: r.item.path, value: { deleted: true } });
259
+ }
260
+ }
261
+ for (const { index, error } of executed.errors) {
262
+ const plan = plans[index];
263
+ const path = plan?.validPath ?? '(unknown)';
264
+ record(path, {
265
+ path,
266
+ error: { code: ErrorCode.UNKNOWN, message: error.message },
267
+ });
268
+ }
269
+ // A plan's `validPath` is the resolved absolute path, so a requested relative
270
+ // path will not find itself in the map by name — fall back through the plan.
271
+ const planByRequested = new Map(plans.map((p) => [p.inputPath, p.validPath]));
272
+ const results = paths.map((requested) => {
273
+ const resolved = planByRequested.get(requested);
274
+ const entry = byPath.get(requested) ?? (resolved !== undefined ? byPath.get(resolved) : undefined);
275
+ return (entry ?? {
276
+ path: requested,
277
+ error: { code: ErrorCode.UNKNOWN, message: 'Unknown delete failure' },
278
+ });
100
279
  });
280
+ const failed = results.filter((r) => r.error !== undefined).length;
281
+ return {
282
+ results,
283
+ summary: { total: results.length, succeeded: results.length - failed, failed },
284
+ };
101
285
  }
286
+ export const DELETE_FILE = defineTool({
287
+ name: 'delete',
288
+ title: 'Delete File',
289
+ description: 'Permanently delete one or more files, directories, or symlinks (max 1000 per call). This action is irreversible. ' +
290
+ 'Pass paths: [...] — there is no single-path form. ' +
291
+ 'Non-empty directories require recursive=true and additionally prompt the user to confirm each one, ' +
292
+ 'so the call returns without deleting anything until that confirmation comes back; ' +
293
+ 'a client that cannot prompt gets an error naming the alternative. ' +
294
+ 'Workspace root directories cannot be deleted.',
295
+ input: DeleteInputSchema,
296
+ output: DeleteOutputSchema,
297
+ annotations: {
298
+ readOnlyHint: false,
299
+ idempotentHint: false,
300
+ destructiveHint: true,
301
+ openWorldHint: false,
302
+ },
303
+ defaultErrorCode: ErrorCode.UNKNOWN,
304
+ progress: (args) => ({
305
+ label: 'Delete',
306
+ subject: args.paths.length === 1
307
+ ? basename(args.paths[0] ?? '')
308
+ : `${String(args.paths.length)} paths`,
309
+ }),
310
+ accessPaths: (args) => [...args.paths],
311
+ run: async (args, ctx) => {
312
+ const structured = await handleDelete(args, ctx);
313
+ // input_required is a return value, not a completed call: surface it
314
+ // verbatim so the executor short-circuits before building a CallToolResult.
315
+ if (isInputRequiredResult(structured))
316
+ return structured;
317
+ // Name every path and its outcome. The old text said "deleted 2 paths"
318
+ // without saying which two, so a partial failure was unreadable without
319
+ // parsing the structured half.
320
+ const { failed, total } = structured.summary;
321
+ // A lone failure carries its reason in the text. "delete: . FAILED (0/1 ok)"
322
+ // made the model re-read structuredContent to learn it was ACCESS_DENIED;
323
+ // with one path there is no ambiguity about which message applies.
324
+ if (total === 1 && failed === 1) {
325
+ const only = structured.results[0];
326
+ return {
327
+ structured,
328
+ text: `delete: ${only?.path ?? ''} FAILED — ${only?.error?.message ?? 'unknown error'}`,
329
+ };
330
+ }
331
+ const tokens = structured.results.map((r) => {
332
+ const label = pathLabel(r.path);
333
+ if (r.error)
334
+ return `${label} FAILED`;
335
+ return r.value?.deleted ? label : `${label} SKIPPED`;
336
+ });
337
+ const ratio = failed > 0 ? ` (${String(total - failed)}/${String(total)} ok)` : '';
338
+ return { structured, text: `delete: ${joinRoster(tokens)}${ratio}` };
339
+ },
340
+ });
341
+ //# sourceMappingURL=delete-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delete-file.js","sourceRoot":"","sources":["../../src/tools/delete-file.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,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;QACxE,+BAA+B;QAC/B,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,UAAU,CAAC,OAAO,CAAC;QAC7C,6EAA6E;QAC7E,0EAA0E;QAC1E,mEAAmE;QACnE,IAAI,KAAK,KAAK,CAAC,IAAI,MAAM,KAAK,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YACnC,OAAO;gBACL,UAAU;gBACV,IAAI,EAAE,WAAW,IAAI,EAAE,IAAI,IAAI,EAAE,aAAa,IAAI,EAAE,KAAK,EAAE,OAAO,IAAI,eAAe,EAAE;aACxF,CAAC;QACJ,CAAC;QACD,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YAC1C,MAAM,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAChC,IAAI,CAAC,CAAC,KAAK;gBAAE,OAAO,GAAG,KAAK,SAAS,CAAC;YACtC,OAAO,CAAC,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,UAAU,CAAC;QACvD,CAAC,CAAC,CAAC;QACH,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACnF,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW,UAAU,CAAC,MAAM,CAAC,GAAG,KAAK,EAAE,EAAE,CAAC;IACvE,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { InputRequiredResult } from '@modelcontextprotocol/server';\nimport { isInputRequiredResult } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.js';\nimport {\n ErrorCode,\n FsError,\n isFsError,\n isNodeError,\n isNotFoundErrno,\n Problem,\n} from '../core/errors.js';\nimport { joinRoster, pathLabel } from '../core/fmt.js';\nimport type { FileType, GuardedFileSystem } from '../core/fs.js';\nimport { getFileType } from '../core/fs.js';\nimport { choiceInput, pendingRoundTrip, readAcceptedChoice } from '../core/input-required.js';\nimport {\n defaultFalseBoolean,\n OperationSummarySchema,\n PerFileErrorSchema,\n RequiredPath,\n} from '../core/schema.js';\nimport { PARALLEL_CONCURRENCY } from '../core/util.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst DeleteInputSchema = z.strictObject({\n paths: z\n .array(RequiredPath)\n .min(1)\n .max(1000)\n .describe('Paths to delete (max 1000); accepts files, directories, or symlinks'),\n recursive: defaultFalseBoolean(\n 'Delete directory contents recursively (required for non-empty directories)',\n ),\n ignoreIfNotExists: defaultFalseBoolean(\n 'Silently succeed if a path does not exist instead of returning an error',\n ),\n});\n\nconst DeletePerPathValueSchema = z.strictObject({\n deleted: z.boolean().describe('True when the path was removed; false when the user chose Skip'),\n});\n\nconst DeletePerPathSchema = z.strictObject({\n path: z.string().describe('Requested path'),\n value: DeletePerPathValueSchema.optional().describe('Delete outcome; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\n// One envelope for every batch tool: `read` and `stat` already answer with\n// `{ results, summary }`, so `delete` does too. The old shape switched between\n// `{ ok, path }` and `{ ok: false, failures }` depending on the outcome, which\n// left a caller parsing two schemas for one tool and never named the paths in a\n// multi-delete's text.\nconst DeleteOutputSchema = z.strictObject({\n results: z\n .array(DeletePerPathSchema)\n .describe('Per-path results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype DeleteInput = z.infer<typeof DeleteInputSchema>;\ntype DeleteOutput = z.infer<typeof DeleteOutputSchema>;\ntype DeletePerPathResult = z.infer<typeof DeletePerPathSchema>;\n\n// Internal types for error handling\ninterface DeletedItem {\n path: string;\n}\ninterface DeleteFailure {\n path: string;\n error: {\n code: string;\n message: string;\n path?: string;\n suggestion?: string;\n };\n}\n\nconst ERR_NOT_EMPTY = new Error('Directory not empty. Set recursive: true.');\n\nfunction toDeleteFailure(path: string, error: unknown): DeleteFailure {\n // A missing path reached here as the raw errno text (\"ENOENT: no such file or\n // directory, lstat 'c:\\...'\"), while `stat` reported the same condition as\n // \"Path not found\". One condition, one message — and the syscall name stays\n // off the wire.\n if (isNotFoundErrno(error)) {\n return {\n path,\n error: Problem.toPerFileError(\n new FsError(ErrorCode.NOT_FOUND, 'Path not found', path),\n ErrorCode.NOT_FOUND,\n path,\n ),\n };\n }\n if (\n isNodeError(error) &&\n (error.code === 'ENOTEMPTY' || error.code === 'EISDIR' || error.code === 'EEXIST')\n ) {\n return {\n path,\n error: Problem.toPerFileError(ERR_NOT_EMPTY, ErrorCode.INVALID_INPUT, path),\n };\n }\n return { path, error: Problem.toPerFileError(error, ErrorCode.UNKNOWN, path) };\n}\n\ntype LstatResult = Awaited<ReturnType<GuardedFileSystem['lstat']>>;\ntype ItemType = FileType;\n\n/** A path's pre-checked plan: validated, statted, and flagged if it needs confirmation. */\ninterface DeletePlan {\n inputPath: string;\n validPath: string;\n itemType: ItemType;\n firstStats: LstatResult;\n /** Recursive + non-empty directory: needs a round-trip confirmation. */\n pending: boolean;\n}\n\ntype PlanResult =\n | { status: 'fail'; failure: DeleteFailure }\n | { status: 'noop'; item: DeletedItem }\n | { status: 'plan'; plan: DeletePlan };\n\n/**\n * Phase 1 (no mutation): validate, stat, and decide whether a path needs a\n * confirmation before anything is deleted. A pending path is a recursive\n * non-empty directory; everything else is ready to delete directly.\n */\nasync function planPath(\n inputPath: string,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n fs: Pick<GuardedFileSystem, 'pathGuard' | 'lstat' | 'hasChildrenUnchecked'>,\n): Promise<PlanResult> {\n let validPath: string;\n try {\n validPath = await fs.pathGuard.validatePathForDelete(inputPath);\n } catch (error) {\n if (\n args.ignoreIfNotExists &&\n ((isFsError(error) && error.code === ErrorCode.NOT_FOUND) || isNotFoundErrno(error))\n ) {\n return { status: 'noop', item: { path: inputPath } };\n }\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n\n if (fs.pathGuard.isAllowedRoot(validPath)) {\n return {\n status: 'fail',\n // Keyed by the REQUESTED path, like every other failure here: handleDelete\n // orders results by input path, and a resolved key would not be found for\n // a relative request.\n failure: {\n path: inputPath,\n error: Problem.accessDenied('Deleting a workspace root directory is not allowed', {\n path: validPath,\n }),\n },\n };\n }\n\n let firstStats: LstatResult;\n try {\n firstStats = await fs.lstat(validPath);\n } catch (error) {\n if (isNotFoundErrno(error) && args.ignoreIfNotExists) {\n return { status: 'noop', item: { path: inputPath } };\n }\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n\n const itemType = getFileType(firstStats.stats);\n let hasChildren = false;\n if (args.recursive && itemType === 'directory') {\n try {\n hasChildren = await fs.hasChildrenUnchecked(validPath);\n } catch (error) {\n return { status: 'fail', failure: toDeleteFailure(inputPath, error) };\n }\n }\n const pending = hasChildren;\n return { status: 'plan', plan: { inputPath, validPath, itemType, firstStats, pending } };\n}\n\nasync function performDeletion(\n validPath: string,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n isDirectory: boolean,\n fsOps: Pick<GuardedFileSystem, 'rm' | 'rmdir'>,\n): Promise<void> {\n if (isDirectory && !args.recursive) {\n await fsOps.rmdir(validPath);\n } else {\n await fsOps.rm(validPath, {\n recursive: args.recursive,\n force: args.ignoreIfNotExists,\n });\n }\n}\n\n/**\n * Phase 2 (mutation): TOCTOU re-stat against the plan's first stat, then\n * delete. A type or identity change across the confirmation gap fails closed\n * rather than deleting a replacement object the user never confirmed.\n */\nasync function finalizeDeletion(\n plan: DeletePlan,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n ctx: Pick<ToolCtx, 'fs' | 'log'>,\n): Promise<{ item: DeletedItem } | { failure: DeleteFailure }> {\n let currentStats: LstatResult;\n try {\n currentStats = await ctx.fs.lstat(plan.validPath);\n } catch (error) {\n if (isNotFoundErrno(error) && args.ignoreIfNotExists) {\n return { item: { path: plan.validPath } };\n }\n return { failure: toDeleteFailure(plan.inputPath, error) };\n }\n\n const currentItemType = getFileType(currentStats.stats);\n // Identity comparison, not just the coarse category: a swap during the\n // confirmation gap (delete original, create a same-named replacement) keeps\n // the type but changes dev/ino/birthtimeMs. birthtimeMs is the primary\n // cross-platform signal — dev/ino can read 0 on some non-POSIX drivers — so\n // combine all three rather than trusting dev/ino alone.\n const identityChanged =\n plan.firstStats.stats.dev !== currentStats.stats.dev ||\n plan.firstStats.stats.ino !== currentStats.stats.ino ||\n plan.firstStats.stats.birthtimeMs !== currentStats.stats.birthtimeMs;\n if (plan.itemType !== 'other' && (currentItemType !== plan.itemType || identityChanged)) {\n return {\n failure: {\n path: plan.validPath,\n error: Problem.invalidInput(\n `Delete failed: item type changed from ${plan.itemType} to ${currentItemType} during confirmation.`,\n { path: plan.validPath },\n ),\n },\n };\n }\n\n try {\n await performDeletion(plan.validPath, args, currentStats.stats.isDirectory(), ctx.fs);\n } catch (error) {\n return { failure: toDeleteFailure(plan.inputPath, error) };\n }\n\n ctx.log?.('info', `rm: ${plan.inputPath}`, 'delete');\n return { item: { path: plan.validPath } };\n}\n\n/**\n * Execute one planned path on the retry round. A pending path deletes only on\n * an accepted `confirm: true`; decline, cancel, or a missing key report\n * `CANCELLED` for that path (R3 proceed, R4/R5 cancelled). A non-pending path\n * deletes directly (R14: non-pending items proceed alongside accepted ones).\n */\nasync function executePlan(\n plan: DeletePlan,\n args: Pick<DeleteInput, 'recursive' | 'ignoreIfNotExists'>,\n ctx: Pick<ToolCtx, 'fs' | 'inputResponses' | 'log'>,\n pendingSorted: readonly string[],\n): Promise<{ item: DeletedItem } | { failure: DeleteFailure } | { skipped: true; path: string }> {\n if (plan.pending) {\n const key = `confirm_${pendingSorted.indexOf(plan.validPath)}`;\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') {\n return { skipped: true as const, path: plan.validPath };\n }\n if (choice !== 'delete') {\n return {\n failure: {\n path: plan.validPath,\n error: Problem.cancelled('Delete cancelled: confirmation was declined or missing', {\n path: plan.validPath,\n }),\n },\n };\n }\n }\n return finalizeDeletion(plan, args, ctx);\n}\n\nasync function handleDelete(\n args: DeleteInput,\n ctx: ToolCtx,\n): Promise<DeleteOutput | InputRequiredResult> {\n // Duplicate paths collapse: results are keyed by path, so a repeated entry\n // would emit two rows for one deletion and inflate `summary.total`.\n const paths = [...new Set(args.paths)];\n\n // Phase 1 (no mutation): plan every path.\n const planned = await processInParallel(\n paths,\n (inputPath) => planPath(inputPath, args, ctx.fs),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n const plans: DeletePlan[] = [];\n const earlyFailures: DeleteFailure[] = [];\n const earlyNoop: DeletedItem[] = [];\n for (const { value: r } of planned.results) {\n if (r.status === 'fail') earlyFailures.push(r.failure);\n else if (r.status === 'noop') earlyNoop.push(r.item);\n else plans.push(r.plan);\n }\n for (const { index, error } of planned.errors) {\n const path = paths[index] ?? '(unknown)';\n earlyFailures.push({ path, error: { code: ErrorCode.UNKNOWN, message: error.message } });\n }\n\n // Pending set: recursive + non-empty directories, sorted and de-duplicated.\n // `buildInputRequired` seals exactly this set into the requestState, and the\n // retried round recomputes it from the same args so a swapped retry (accept\n // for X, retry with Y) is rejected — the codec only proves the state was not\n // tampered, not that it matches the current request (R9).\n const pendingSorted = [...new Set(plans.filter((p) => p.pending).map((p) => p.validPath))].sort();\n\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required (atomic — R14: nothing deleted yet, not\n // even the non-pending items in the same call); a retry whose verified\n // state does not bind this pending set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip({\n op: 'delete',\n pending: pendingSorted,\n requestState: ctx.requestState,\n clientCapabilities: ctx.clientCapabilities,\n buildInputs: (ps) =>\n ps.map((p, i) =>\n choiceInput(\n `confirm_${i}`,\n `Permanently delete \"${p}\" and all its contents? This cannot be undone.`,\n [\n { value: 'delete', title: 'Delete' },\n { value: 'skip', title: 'Skip' },\n ],\n ),\n ),\n });\n if (round !== undefined) return round;\n }\n\n // Phase 2 (mutation): execute deletions for every planned path.\n const executed = await processInParallel(\n plans,\n (plan) => executePlan(plan, args, ctx, pendingSorted),\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n // Collect by path first, then emit in the caller's input order so\n // `results[i]` lines up with `paths[i]` the way read/stat guarantee.\n const byPath = new Map<string, DeletePerPathResult>();\n const record = (path: string, entry: DeletePerPathResult): void => {\n byPath.set(path, entry);\n };\n for (const n of earlyNoop) record(n.path, { path: n.path, value: { deleted: true } });\n for (const f of earlyFailures) record(f.path, { path: f.path, error: f.error });\n for (const { value: r } of executed.results) {\n if ('skipped' in r) {\n record(r.path, { path: r.path, value: { deleted: false } });\n } else if ('failure' in r) {\n record(r.failure.path, { path: r.failure.path, error: r.failure.error });\n } else if (r.item.path) {\n record(r.item.path, { path: r.item.path, value: { deleted: true } });\n }\n }\n for (const { index, error } of executed.errors) {\n const plan = plans[index];\n const path = plan?.validPath ?? '(unknown)';\n record(path, {\n path,\n error: { code: ErrorCode.UNKNOWN, message: error.message },\n });\n }\n\n // A plan's `validPath` is the resolved absolute path, so a requested relative\n // path will not find itself in the map by name — fall back through the plan.\n const planByRequested = new Map(plans.map((p) => [p.inputPath, p.validPath]));\n const results: DeletePerPathResult[] = paths.map((requested) => {\n const resolved = planByRequested.get(requested);\n const entry =\n byPath.get(requested) ?? (resolved !== undefined ? byPath.get(resolved) : undefined);\n return (\n entry ?? {\n path: requested,\n error: { code: ErrorCode.UNKNOWN, message: 'Unknown delete failure' },\n }\n );\n });\n\n const failed = results.filter((r) => r.error !== undefined).length;\n return {\n results,\n summary: { total: results.length, succeeded: results.length - failed, failed },\n };\n}\n\nexport const DELETE_FILE = defineTool({\n name: 'delete',\n title: 'Delete File',\n description:\n 'Permanently delete one or more files, directories, or symlinks (max 1000 per call). This action is irreversible. ' +\n 'Pass paths: [...] — there is no single-path form. ' +\n 'Non-empty directories require recursive=true and additionally prompt the user to confirm each one, ' +\n 'so the call returns without deleting anything until that confirmation comes back; ' +\n 'a client that cannot prompt gets an error naming the alternative. ' +\n 'Workspace root directories cannot be deleted.',\n input: DeleteInputSchema,\n output: DeleteOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n defaultErrorCode: ErrorCode.UNKNOWN,\n progress: (args) => ({\n label: 'Delete',\n subject:\n args.paths.length === 1\n ? basename(args.paths[0] ?? '')\n : `${String(args.paths.length)} paths`,\n }),\n accessPaths: (args) => [...args.paths],\n run: async (args, ctx) => {\n const structured = await handleDelete(args, ctx);\n // input_required is a return value, not a completed call: surface it\n // verbatim so the executor short-circuits before building a CallToolResult.\n if (isInputRequiredResult(structured)) return structured;\n // Name every path and its outcome. The old text said \"deleted 2 paths\"\n // without saying which two, so a partial failure was unreadable without\n // parsing the structured half.\n const { failed, total } = structured.summary;\n // A lone failure carries its reason in the text. \"delete: . FAILED (0/1 ok)\"\n // made the model re-read structuredContent to learn it was ACCESS_DENIED;\n // with one path there is no ambiguity about which message applies.\n if (total === 1 && failed === 1) {\n const only = structured.results[0];\n return {\n structured,\n text: `delete: ${only?.path ?? ''} FAILED — ${only?.error?.message ?? 'unknown error'}`,\n };\n }\n const tokens = structured.results.map((r) => {\n const label = pathLabel(r.path);\n if (r.error) return `${label} FAILED`;\n return r.value?.deleted ? label : `${label} SKIPPED`;\n });\n const ratio = failed > 0 ? ` (${String(total - failed)}/${String(total)} ok)` : '';\n return { structured, text: `delete: ${joinRoster(tokens)}${ratio}` };\n },\n});\n"]}
@@ -0,0 +1,2 @@
1
+ export declare const DIFF: import("./define.js").DefinedTool;
2
+ //# sourceMappingURL=diff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff.d.ts","sourceRoot":"","sources":["../../src/tools/diff.ts"],"names":[],"mappings":"AAqGA,eAAO,MAAM,IAAI,mCAoBf,CAAC"}