n8n-ops-mcp 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -32,6 +32,7 @@ For a catalog/docs tool that indexes n8n's node library, see [n8n-mcp](https://w
32
32
  | `n8n_cancel_execution` | Stop a running or waiting execution by id | ✓ |
33
33
  | `n8n_retry_execution` | Retry a failed execution by id (returns a new execution) | ✓ |
34
34
  | `n8n_delete_execution` | Permanently delete an execution record (confirm-gated, irreversible) | ✓ |
35
+ | `n8n_delete_executions` | Batch form of delete (client-side fan-out, confirm-gated, irreversible, max 50 ids) | ✓ |
35
36
 
36
37
  Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
37
38
 
@@ -58,7 +59,7 @@ Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
58
59
 
59
60
  **`n8n_activate`** / **`n8n_deactivate`** — idempotent. Deactivating does not cancel running executions.
60
61
 
61
- **`n8n_save_workflow`** — before writing: fetches the current version, snapshots it to `backupDir` as `<id>-<timestamp>.json` (mode 0600), runs `validateWorkflow` on the proposed state, and aborts on error-severity issues (pass `skipValidation: true` to bypass). Requires `confirm: true` to actually PUT. Response includes the backup path and a `restoreHint`.
62
+ **`n8n_save_workflow`** — before writing: fetches the current version, snapshots it to `backupDir` as `<id>-<timestamp>.json` (mode 0600), runs `validateWorkflow` on the proposed state, and aborts on error-severity issues (pass `skipValidation: true` to bypass). Requires `confirm: true` to actually PUT; calling with `confirm: false` returns `ok: false` and never touches the API (omitting `confirm` is rejected at the MCP schema layer). Response includes the backup path and a `restoreHint`.
62
63
 
63
64
  **`n8n_cancel_execution`** — `POST /executions/{id}/stop`. Closes the triage loop after `n8n_search_executions` locates a stuck run. Returns a success summary with the execution's final status, or `ok: false` with `reason: "not_found_or_finished"` if the id no longer matches a running execution (404).
64
65
 
@@ -66,6 +67,8 @@ Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
66
67
 
67
68
  **`n8n_delete_execution`** — `DELETE /executions/{id}`. Permanently removes an execution record: logs, per-node run data, and error payloads are erased from n8n. Requires `confirm: true` to actually delete; calling with `confirm: false` returns `ok: false` and never touches the API (omitting `confirm` is rejected at the MCP schema layer). Returns `ok: false` with `reason: "not_found"` on 404; all other API errors rethrow. Not idempotent from an agent's perspective: the record is gone after the first successful call, so fetch `n8n_get_execution` first if you may need it later.
68
69
 
70
+ **`n8n_delete_executions`** — batch form. Client-side fan-out over `DELETE /executions/{id}` with bounded concurrency (default 3, max 10). Takes an `ids` array (deduped before fan-out, capped at 50), requires `confirm: true`. Response surfaces `requested`/`attempted`/`deleted`/`alreadyDeleted`/`failed`/`skipped`/`aborted` counters plus a `results: Array<{id, ok, reason?, message?}>` — order is completion order, not input order, so look up by id. 404 per id is treated as `already_deleted` (idempotent). A 5xx on any id aborts the batch via an `AbortController`: no new ids are claimed and any already-in-flight `fetch`es are cancelled client-side. Under concurrency N, up to N-1 deletes may have already reached the server before the 5xx is observed, so the batch is best-effort, not transactional — clear signal the server is sick; don't retry blindly. Per-id error messages are passed through the API-key redactor. Compose with `n8n_search_executions` to purge a known set of noisy runs in one call.
71
+
69
72
  </details>
70
73
 
71
74
  ## Install
@@ -248,7 +251,7 @@ Calls `n8n_search_executions` to find the failed id, then `n8n_retry_execution`
248
251
 
249
252
  > Purge the noisy test-run execution logs from last week *(requires `N8N_ENABLE_EDIT=true`)*
250
253
 
251
- Calls `n8n_search_executions` to find the ids, then `n8n_delete_execution` with `confirm: true` on each. Deletion is irreversible.
254
+ Calls `n8n_search_executions` to find the ids, then `n8n_delete_executions` with `confirm: true` to purge up to 50 in one call. Deletion is irreversible.
252
255
 
253
256
  ## Development
254
257
 
@@ -143,14 +143,60 @@ var N8nClient = class {
143
143
  }
144
144
  return this.request(`/api/v1/executions/${id}/retry`, init);
145
145
  }
146
- async deleteExecution(id) {
146
+ async deleteExecution(id, opts = {}) {
147
147
  if (!/^[A-Za-z0-9_-]+$/.test(id)) {
148
148
  throw new Error(`Invalid execution id: ${id}`);
149
149
  }
150
150
  return this.request(`/api/v1/executions/${id}`, {
151
- method: "DELETE"
151
+ method: "DELETE",
152
+ signal: opts.signal
152
153
  });
153
154
  }
155
+ async deleteExecutions(ids, opts = {}) {
156
+ for (const id of ids) {
157
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
158
+ throw new Error(`Invalid execution id: ${id}`);
159
+ }
160
+ }
161
+ const concurrency = Math.max(1, Math.floor(opts.concurrency ?? 3));
162
+ const results = [];
163
+ const batchCtrl = new AbortController();
164
+ let cursor = 0;
165
+ const worker = async () => {
166
+ while (true) {
167
+ if (batchCtrl.signal.aborted) return;
168
+ const index = cursor++;
169
+ if (index >= ids.length) return;
170
+ if (batchCtrl.signal.aborted) return;
171
+ const id = ids[index];
172
+ try {
173
+ await this.deleteExecution(id, { signal: batchCtrl.signal });
174
+ results.push({ id, ok: true });
175
+ } catch (err) {
176
+ if (err instanceof N8nApiError && err.status === 404) {
177
+ results.push({ id, ok: true, reason: "already_deleted" });
178
+ continue;
179
+ }
180
+ if (isAbortError(err) && batchCtrl.signal.aborted) {
181
+ return;
182
+ }
183
+ const msg = err instanceof Error ? err.message : String(err);
184
+ const redacted = redactKey(msg, this.apiKey);
185
+ if (err instanceof N8nApiError && err.status >= 500) {
186
+ results.push({ id, ok: false, reason: "server_error", message: redacted });
187
+ batchCtrl.abort();
188
+ return;
189
+ }
190
+ results.push({ id, ok: false, reason: "error", message: redacted });
191
+ }
192
+ }
193
+ };
194
+ const workerCount = Math.min(concurrency, Math.max(ids.length, 1));
195
+ const workers = [];
196
+ for (let i = 0; i < workerCount; i++) workers.push(worker());
197
+ await Promise.all(workers);
198
+ return results;
199
+ }
154
200
  async listExecutions(params = {}) {
155
201
  const qs = new URLSearchParams();
156
202
  if (params.workflowId) qs.set("workflowId", params.workflowId);
@@ -166,9 +212,19 @@ var N8nClient = class {
166
212
  const url = `${this.baseUrl}${path2}`;
167
213
  const controller = new AbortController();
168
214
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
215
+ const caller = init.signal;
216
+ let onCallerAbort;
217
+ if (caller) {
218
+ if (caller.aborted) controller.abort();
219
+ else {
220
+ onCallerAbort = () => controller.abort();
221
+ caller.addEventListener("abort", onCallerAbort, { once: true });
222
+ }
223
+ }
169
224
  try {
225
+ const { signal: _drop, ...rest } = init;
170
226
  const res = await fetch(url, {
171
- ...init,
227
+ ...rest,
172
228
  headers: {
173
229
  "X-N8N-API-KEY": this.apiKey,
174
230
  "Accept": "application/json",
@@ -185,10 +241,18 @@ var N8nClient = class {
185
241
  return JSON.parse(text);
186
242
  } catch (err) {
187
243
  if (err instanceof N8nApiError) throw err;
244
+ if (isAbortError(err) && caller?.aborted) {
245
+ const e = new Error(`n8n request to ${path2} aborted`);
246
+ e.name = "AbortError";
247
+ throw e;
248
+ }
188
249
  const msg = err instanceof Error ? err.message : String(err);
189
250
  throw new Error(`n8n request to ${path2} failed: ${redactKey(msg, this.apiKey)}`);
190
251
  } finally {
191
252
  clearTimeout(timer);
253
+ if (caller && onCallerAbort) {
254
+ caller.removeEventListener("abort", onCallerAbort);
255
+ }
192
256
  }
193
257
  }
194
258
  };
@@ -196,6 +260,9 @@ function redactKey(text, apiKey) {
196
260
  if (!apiKey) return text;
197
261
  return text.split(apiKey).join("***REDACTED***");
198
262
  }
263
+ function isAbortError(err) {
264
+ return err instanceof Error && err.name === "AbortError";
265
+ }
199
266
 
200
267
  // src/config.ts
201
268
  function resolveApiKey(config) {
@@ -1492,8 +1559,96 @@ function createDeleteExecutionTool(getClient) {
1492
1559
  };
1493
1560
  }
1494
1561
 
1562
+ // src/tools/delete-executions.ts
1563
+ import { Type as Type15 } from "@sinclair/typebox";
1564
+ var DEFAULT_MAX_BATCH_SIZE = 50;
1565
+ var DEFAULT_CONCURRENCY = 3;
1566
+ var Schema15 = Type15.Object(
1567
+ {
1568
+ ids: Type15.Array(Type15.String(), {
1569
+ description: "Execution ids to delete (from n8n_search_executions or n8n_list_executions). Deduped before fan-out; non-empty required.",
1570
+ minItems: 1
1571
+ }),
1572
+ confirm: Type15.Boolean({
1573
+ description: "Must be true to actually delete. Deletion is irreversible: execution logs, run data, and error payloads are gone from n8n after this call. If you may need the records later, fetch n8n_get_execution first and save the output."
1574
+ }),
1575
+ concurrency: Type15.Optional(
1576
+ Type15.Integer({
1577
+ minimum: 1,
1578
+ maximum: 10,
1579
+ description: "Parallel DELETE requests against the n8n API. Default 3. Keep low \u2014 n8n shares a database."
1580
+ })
1581
+ )
1582
+ },
1583
+ { additionalProperties: false }
1584
+ );
1585
+ function createDeleteExecutionsTool(getClient) {
1586
+ return {
1587
+ name: "n8n_delete_executions",
1588
+ label: "n8n: delete executions (batch)",
1589
+ description: "Permanently delete multiple n8n execution records by id via DELETE /executions/{id}, client-side fan-out with bounded concurrency. Irreversible: per-node run data and error payloads are erased. Requires enableEdit and explicit confirm=true. Per-id outcome is surfaced in results (order is completion order, not input order; look up by id). 404 per id is treated as already_deleted (idempotent). A 5xx per id aborts the batch via AbortController; no new ids are claimed after the abort and any already-in-flight requests are cancelled client-side. Under concurrency N, up to N-1 in-flight deletes may have already reached the server by the time the 5xx is observed \u2014 the batch is best-effort, not transactional. `skipped` counts both never-claimed ids and in-flight cancellations. Batch size is capped at " + DEFAULT_MAX_BATCH_SIZE + " ids.",
1590
+ parameters: Schema15,
1591
+ execute: async (_toolCallId, rawParams) => {
1592
+ const { ids, confirm, concurrency } = rawParams;
1593
+ if (!confirm) {
1594
+ return jsonToolResult({
1595
+ ok: false,
1596
+ action: "delete_batch",
1597
+ error: "confirm must be true to delete",
1598
+ hint: "Batch deletion is irreversible. Fetch n8n_get_execution first for any record you may need later."
1599
+ });
1600
+ }
1601
+ if (!Array.isArray(ids) || ids.length === 0) {
1602
+ return jsonToolResult({
1603
+ ok: false,
1604
+ action: "delete_batch",
1605
+ reason: "empty_ids",
1606
+ error: "ids must be a non-empty array"
1607
+ });
1608
+ }
1609
+ const deduped = Array.from(new Set(ids));
1610
+ if (deduped.length > DEFAULT_MAX_BATCH_SIZE) {
1611
+ return jsonToolResult({
1612
+ ok: false,
1613
+ action: "delete_batch",
1614
+ reason: "batch_too_large",
1615
+ error: `ids count ${deduped.length} exceeds maxBatchSize ${DEFAULT_MAX_BATCH_SIZE}`,
1616
+ hint: `Split into batches of at most ${DEFAULT_MAX_BATCH_SIZE} ids.`
1617
+ });
1618
+ }
1619
+ const client = getClient();
1620
+ const results = await client.deleteExecutions(
1621
+ deduped,
1622
+ { concurrency: concurrency ?? DEFAULT_CONCURRENCY }
1623
+ );
1624
+ const attempted = results.length;
1625
+ const deleted = results.filter(
1626
+ (r) => r.ok && r.reason !== "already_deleted"
1627
+ ).length;
1628
+ const alreadyDeleted = results.filter(
1629
+ (r) => r.reason === "already_deleted"
1630
+ ).length;
1631
+ const failed = results.filter((r) => !r.ok).length;
1632
+ const aborted = results.some((r) => r.reason === "server_error");
1633
+ const skipped = deduped.length - attempted;
1634
+ return jsonToolResult({
1635
+ ok: failed === 0,
1636
+ action: "delete_batch",
1637
+ requested: deduped.length,
1638
+ attempted,
1639
+ deleted,
1640
+ alreadyDeleted,
1641
+ failed,
1642
+ skipped,
1643
+ aborted,
1644
+ results
1645
+ });
1646
+ }
1647
+ };
1648
+ }
1649
+
1495
1650
  // mcp-server.ts
1496
- var VERSION = "0.5.0";
1651
+ var VERSION = "0.6.0";
1497
1652
  function readConfigFromEnv() {
1498
1653
  const baseUrl = (process.env.N8N_BASE_URL ?? "").trim();
1499
1654
  if (!baseUrl) {
@@ -1670,6 +1825,15 @@ async function main() {
1670
1825
  "Must be true to actually delete. Deletion is irreversible: execution logs, per-node run data, and error payloads are erased."
1671
1826
  )
1672
1827
  });
1828
+ bind(server, createDeleteExecutionsTool(getClient), {
1829
+ ids: z.array(z.string()).min(1).describe(
1830
+ "Execution ids to delete (from n8n_search_executions or n8n_list_executions). Deduped server-side; non-empty required."
1831
+ ),
1832
+ confirm: z.boolean().describe(
1833
+ "Must be true to actually delete. Deletion is irreversible: execution logs, per-node run data, and error payloads are erased."
1834
+ ),
1835
+ concurrency: z.number().int().min(1).max(10).optional().describe("Parallel DELETE requests. Default 3. Keep low \u2014 n8n shares a database.")
1836
+ });
1673
1837
  }
1674
1838
  const transport = new StdioServerTransport();
1675
1839
  await server.connect(transport);
package/index.ts CHANGED
@@ -15,6 +15,7 @@ import { createSaveWorkflowTool } from "./src/tools/save-workflow.ts";
15
15
  import { createCancelExecutionTool } from "./src/tools/cancel-execution.ts";
16
16
  import { createRetryExecutionTool } from "./src/tools/retry-execution.ts";
17
17
  import { createDeleteExecutionTool } from "./src/tools/delete-execution.ts";
18
+ import { createDeleteExecutionsTool } from "./src/tools/delete-executions.ts";
18
19
 
19
20
  export default definePluginEntry({
20
21
  id: "n8n",
@@ -55,6 +56,7 @@ export default definePluginEntry({
55
56
  api.registerTool(createCancelExecutionTool(getClient) as AnyAgentTool);
56
57
  api.registerTool(createRetryExecutionTool(getClient) as AnyAgentTool);
57
58
  api.registerTool(createDeleteExecutionTool(getClient) as AnyAgentTool);
59
+ api.registerTool(createDeleteExecutionsTool(getClient) as AnyAgentTool);
58
60
  }
59
61
  },
60
62
  });
@@ -24,7 +24,7 @@
24
24
  "enableEdit": {
25
25
  "type": "boolean",
26
26
  "default": false,
27
- "description": "Enable write tools (save/activate/deactivate/cancel-execution/retry-execution/delete-execution). Off by default. delete-execution is irreversible and has a confirm gate."
27
+ "description": "Enable write tools (save/activate/deactivate/cancel-execution/retry-execution/delete-execution/delete-executions). Off by default. delete-execution and delete-executions are irreversible (batch is client-side fan-out, confirm-gated, capped at 50 ids, idempotent on 404)."
28
28
  },
29
29
  "maxExecutionLogBytes": {
30
30
  "type": "number",
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "enableEdit": {
57
57
  "label": "Enable Edit Tools",
58
- "help": "Exposes save/activate/deactivate/cancel-execution/retry-execution/delete-execution. save has a confirm-gate and auto-backup; cancel stops running executions; retry re-runs a failed execution and returns a NEW execution id; delete permanently removes an execution record (confirm-gated, irreversible)."
58
+ "help": "Exposes save/activate/deactivate/cancel-execution/retry-execution/delete-execution/delete-executions. save has a confirm-gate and auto-backup; cancel stops running executions; retry re-runs a failed execution and returns a NEW execution id; delete permanently removes one execution record (confirm-gated, irreversible); delete-executions is the batch form (client-side fan-out, confirm-gated, capped at 50 ids, idempotent on 404, 5xx aborts the batch)."
59
59
  },
60
60
  "maxExecutionLogBytes": {
61
61
  "label": "Max Log Bytes",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-ops-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Ops-focused n8n tools (list, inspect, trigger, validate, save) for Claude-compatible clients. MCP server + first-class OpenClaw plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/client.ts CHANGED
@@ -68,6 +68,13 @@ export interface N8nExecution extends N8nExecutionSummary {
68
68
  };
69
69
  }
70
70
 
71
+ export interface N8nBatchDeleteResult {
72
+ id: string;
73
+ ok: boolean;
74
+ reason?: "already_deleted" | "server_error" | "error";
75
+ message?: string;
76
+ }
77
+
71
78
  export class N8nApiError extends Error {
72
79
  constructor(
73
80
  public readonly status: number,
@@ -241,15 +248,73 @@ export class N8nClient {
241
248
  return this.request<N8nExecution>(`/api/v1/executions/${id}/retry`, init);
242
249
  }
243
250
 
244
- async deleteExecution(id: string): Promise<N8nExecution> {
251
+ async deleteExecution(
252
+ id: string,
253
+ opts: { signal?: AbortSignal } = {},
254
+ ): Promise<N8nExecution> {
245
255
  if (!/^[A-Za-z0-9_-]+$/.test(id)) {
246
256
  throw new Error(`Invalid execution id: ${id}`);
247
257
  }
248
258
  return this.request<N8nExecution>(`/api/v1/executions/${id}`, {
249
259
  method: "DELETE",
260
+ signal: opts.signal,
250
261
  });
251
262
  }
252
263
 
264
+ async deleteExecutions(
265
+ ids: string[],
266
+ opts: { concurrency?: number } = {},
267
+ ): Promise<N8nBatchDeleteResult[]> {
268
+ for (const id of ids) {
269
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
270
+ throw new Error(`Invalid execution id: ${id}`);
271
+ }
272
+ }
273
+ const concurrency = Math.max(1, Math.floor(opts.concurrency ?? 3));
274
+ const results: N8nBatchDeleteResult[] = [];
275
+ const batchCtrl = new AbortController();
276
+ let cursor = 0;
277
+
278
+ const worker = async (): Promise<void> => {
279
+ while (true) {
280
+ if (batchCtrl.signal.aborted) return;
281
+ const index = cursor++;
282
+ if (index >= ids.length) return;
283
+ if (batchCtrl.signal.aborted) return;
284
+ const id = ids[index];
285
+ try {
286
+ await this.deleteExecution(id, { signal: batchCtrl.signal });
287
+ results.push({ id, ok: true });
288
+ } catch (err) {
289
+ if (err instanceof N8nApiError && err.status === 404) {
290
+ results.push({ id, ok: true, reason: "already_deleted" });
291
+ continue;
292
+ }
293
+ if (isAbortError(err) && batchCtrl.signal.aborted) {
294
+ // In-flight when batch was aborted by a peer's 5xx. Don't record —
295
+ // intentionally absent from results so the tool can surface
296
+ // skipped = requested - attempted.
297
+ return;
298
+ }
299
+ const msg = err instanceof Error ? err.message : String(err);
300
+ const redacted = redactKey(msg, this.apiKey);
301
+ if (err instanceof N8nApiError && err.status >= 500) {
302
+ results.push({ id, ok: false, reason: "server_error", message: redacted });
303
+ batchCtrl.abort();
304
+ return;
305
+ }
306
+ results.push({ id, ok: false, reason: "error", message: redacted });
307
+ }
308
+ }
309
+ };
310
+
311
+ const workerCount = Math.min(concurrency, Math.max(ids.length, 1));
312
+ const workers: Promise<void>[] = [];
313
+ for (let i = 0; i < workerCount; i++) workers.push(worker());
314
+ await Promise.all(workers);
315
+ return results;
316
+ }
317
+
253
318
  async listExecutions(params: {
254
319
  workflowId?: string;
255
320
  status?: string;
@@ -275,9 +340,19 @@ export class N8nClient {
275
340
  const url = `${this.baseUrl}${path}`;
276
341
  const controller = new AbortController();
277
342
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
343
+ const caller = init.signal as AbortSignal | null | undefined;
344
+ let onCallerAbort: (() => void) | undefined;
345
+ if (caller) {
346
+ if (caller.aborted) controller.abort();
347
+ else {
348
+ onCallerAbort = () => controller.abort();
349
+ caller.addEventListener("abort", onCallerAbort, { once: true });
350
+ }
351
+ }
278
352
  try {
353
+ const { signal: _drop, ...rest } = init;
279
354
  const res = await fetch(url, {
280
- ...init,
355
+ ...rest,
281
356
  headers: {
282
357
  "X-N8N-API-KEY": this.apiKey,
283
358
  "Accept": "application/json",
@@ -294,10 +369,18 @@ export class N8nClient {
294
369
  return JSON.parse(text) as T;
295
370
  } catch (err) {
296
371
  if (err instanceof N8nApiError) throw err;
372
+ if (isAbortError(err) && caller?.aborted) {
373
+ const e = new Error(`n8n request to ${path} aborted`);
374
+ e.name = "AbortError";
375
+ throw e;
376
+ }
297
377
  const msg = err instanceof Error ? err.message : String(err);
298
378
  throw new Error(`n8n request to ${path} failed: ${redactKey(msg, this.apiKey)}`);
299
379
  } finally {
300
380
  clearTimeout(timer);
381
+ if (caller && onCallerAbort) {
382
+ caller.removeEventListener("abort", onCallerAbort);
383
+ }
301
384
  }
302
385
  }
303
386
  }
@@ -306,3 +389,7 @@ function redactKey(text: string, apiKey: string): string {
306
389
  if (!apiKey) return text;
307
390
  return text.split(apiKey).join("***REDACTED***");
308
391
  }
392
+
393
+ function isAbortError(err: unknown): boolean {
394
+ return err instanceof Error && err.name === "AbortError";
395
+ }
@@ -0,0 +1,108 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { N8nBatchDeleteResult, N8nClient } from "../client.ts";
3
+ import { jsonToolResult } from "./result.ts";
4
+
5
+ const DEFAULT_MAX_BATCH_SIZE = 50;
6
+ const DEFAULT_CONCURRENCY = 3;
7
+
8
+ const Schema = Type.Object(
9
+ {
10
+ ids: Type.Array(Type.String(), {
11
+ description:
12
+ "Execution ids to delete (from n8n_search_executions or n8n_list_executions). Deduped before fan-out; non-empty required.",
13
+ minItems: 1,
14
+ }),
15
+ confirm: Type.Boolean({
16
+ description:
17
+ "Must be true to actually delete. Deletion is irreversible: execution logs, run data, and error payloads are gone from n8n after this call. If you may need the records later, fetch n8n_get_execution first and save the output.",
18
+ }),
19
+ concurrency: Type.Optional(
20
+ Type.Integer({
21
+ minimum: 1,
22
+ maximum: 10,
23
+ description:
24
+ "Parallel DELETE requests against the n8n API. Default 3. Keep low — n8n shares a database.",
25
+ }),
26
+ ),
27
+ },
28
+ { additionalProperties: false },
29
+ );
30
+
31
+ export function createDeleteExecutionsTool(getClient: () => N8nClient) {
32
+ return {
33
+ name: "n8n_delete_executions",
34
+ label: "n8n: delete executions (batch)",
35
+ description:
36
+ "Permanently delete multiple n8n execution records by id via DELETE /executions/{id}, client-side fan-out with bounded concurrency. Irreversible: per-node run data and error payloads are erased. Requires enableEdit and explicit confirm=true. Per-id outcome is surfaced in results (order is completion order, not input order; look up by id). 404 per id is treated as already_deleted (idempotent). A 5xx per id aborts the batch via AbortController; no new ids are claimed after the abort and any already-in-flight requests are cancelled client-side. Under concurrency N, up to N-1 in-flight deletes may have already reached the server by the time the 5xx is observed — the batch is best-effort, not transactional. `skipped` counts both never-claimed ids and in-flight cancellations. Batch size is capped at " +
37
+ DEFAULT_MAX_BATCH_SIZE +
38
+ " ids.",
39
+ parameters: Schema,
40
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
41
+ const { ids, confirm, concurrency } = rawParams as {
42
+ ids: string[];
43
+ confirm: boolean;
44
+ concurrency?: number;
45
+ };
46
+
47
+ if (!confirm) {
48
+ return jsonToolResult({
49
+ ok: false,
50
+ action: "delete_batch",
51
+ error: "confirm must be true to delete",
52
+ hint: "Batch deletion is irreversible. Fetch n8n_get_execution first for any record you may need later.",
53
+ });
54
+ }
55
+
56
+ if (!Array.isArray(ids) || ids.length === 0) {
57
+ return jsonToolResult({
58
+ ok: false,
59
+ action: "delete_batch",
60
+ reason: "empty_ids",
61
+ error: "ids must be a non-empty array",
62
+ });
63
+ }
64
+
65
+ const deduped = Array.from(new Set(ids));
66
+
67
+ if (deduped.length > DEFAULT_MAX_BATCH_SIZE) {
68
+ return jsonToolResult({
69
+ ok: false,
70
+ action: "delete_batch",
71
+ reason: "batch_too_large",
72
+ error: `ids count ${deduped.length} exceeds maxBatchSize ${DEFAULT_MAX_BATCH_SIZE}`,
73
+ hint: `Split into batches of at most ${DEFAULT_MAX_BATCH_SIZE} ids.`,
74
+ });
75
+ }
76
+
77
+ const client = getClient();
78
+ const results: N8nBatchDeleteResult[] = await client.deleteExecutions(
79
+ deduped,
80
+ { concurrency: concurrency ?? DEFAULT_CONCURRENCY },
81
+ );
82
+
83
+ const attempted = results.length;
84
+ const deleted = results.filter(
85
+ (r) => r.ok && r.reason !== "already_deleted",
86
+ ).length;
87
+ const alreadyDeleted = results.filter(
88
+ (r) => r.reason === "already_deleted",
89
+ ).length;
90
+ const failed = results.filter((r) => !r.ok).length;
91
+ const aborted = results.some((r) => r.reason === "server_error");
92
+ const skipped = deduped.length - attempted;
93
+
94
+ return jsonToolResult({
95
+ ok: failed === 0,
96
+ action: "delete_batch",
97
+ requested: deduped.length,
98
+ attempted,
99
+ deleted,
100
+ alreadyDeleted,
101
+ failed,
102
+ skipped,
103
+ aborted,
104
+ results,
105
+ });
106
+ },
107
+ };
108
+ }