n8n-ops-mcp 0.5.1 → 0.7.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
@@ -29,9 +29,13 @@ For a catalog/docs tool that indexes n8n's node library, see [n8n-mcp](https://w
29
29
  | `n8n_activate` | Enable a workflow's triggers | ✓ |
30
30
  | `n8n_deactivate` | Disable a workflow's triggers | ✓ |
31
31
  | `n8n_save_workflow` | Overwrite a workflow with auto-backup + validation + confirm gate | ✓ |
32
+ | `n8n_archive_workflow` | Soft-delete a workflow (reversible; prefer over delete) | ✓ |
33
+ | `n8n_unarchive_workflow` | Restore an archived workflow (does NOT reactivate) | ✓ |
34
+ | `n8n_delete_workflow` | Permanently delete a workflow (confirm-gated, snapshot-before-delete) | ✓ |
32
35
  | `n8n_cancel_execution` | Stop a running or waiting execution by id | ✓ |
33
36
  | `n8n_retry_execution` | Retry a failed execution by id (returns a new execution) | ✓ |
34
37
  | `n8n_delete_execution` | Permanently delete an execution record (confirm-gated, irreversible) | ✓ |
38
+ | `n8n_delete_executions` | Batch form of delete (client-side fan-out, confirm-gated, irreversible, max 50 ids) | ✓ |
35
39
 
36
40
  Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
37
41
 
@@ -58,7 +62,13 @@ Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
58
62
 
59
63
  **`n8n_activate`** / **`n8n_deactivate`** — idempotent. Deactivating does not cancel running executions.
60
64
 
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`.
65
+ **`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`.
66
+
67
+ **`n8n_archive_workflow`** — `POST /workflows/{id}/archive`. Soft-deletes a workflow: triggers stop firing, the workflow disappears from the default UI list, but the definition and execution history are preserved. Idempotent (archiving an already-archived workflow returns the current state). No confirm gate — this is the safe cleanup path. Archiving deactivates as a side effect; the response surfaces `active: false` explicitly. Returns `ok: false` with `reason: "not_found"` on 404.
68
+
69
+ **`n8n_unarchive_workflow`** — `POST /workflows/{id}/unarchive`. Restores an archived workflow. Does NOT reactivate — triggers stay off until you call `n8n_activate` explicitly. Returns `ok: false` with `reason: "not_found"` on 404.
70
+
71
+ **`n8n_delete_workflow`** — `DELETE /workflows/{id}`. Permanent, irreversible. Before firing the DELETE: fetches the current workflow and snapshots it to `backupDir` as `<id>-DELETED-<timestamp>.json` (mode 0600). If the snapshot can't be written, the DELETE is aborted — there is no un-safety-netted path. Requires `confirm: true`; omitting it or passing `false` returns `ok: false` and never touches the API. Returns `ok: false` with `reason: "not_found"` on 404 (either before or after the snapshot). **Restore is NOT a one-call operation:** `n8n_save_workflow` overwrites an existing id, it does not recreate a deleted one. To restore, create a new workflow in the n8n UI (or via a future `n8n_create_workflow`) and paste the snapshot's nodes/connections/settings. Deleting does NOT cancel running executions — use `n8n_list_executions(workflowId, status='running')` + `n8n_cancel_execution` first if needed. **Prefer `n8n_archive_workflow` for cleanup** unless you truly need to scrub the workflow from n8n.
62
72
 
63
73
  **`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
74
 
@@ -66,6 +76,8 @@ Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
66
76
 
67
77
  **`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
78
 
79
+ **`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.
80
+
69
81
  </details>
70
82
 
71
83
  ## Install
@@ -248,7 +260,15 @@ Calls `n8n_search_executions` to find the failed id, then `n8n_retry_execution`
248
260
 
249
261
  > Purge the noisy test-run execution logs from last week *(requires `N8N_ENABLE_EDIT=true`)*
250
262
 
251
- Calls `n8n_search_executions` to find the ids, then `n8n_delete_execution` with `confirm: true` on each. Deletion is irreversible.
263
+ 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.
264
+
265
+ > Archive the old "staging-bot" workflow — I might need it back someday *(requires `N8N_ENABLE_EDIT=true`)*
266
+
267
+ Calls `n8n_list_workflows` with a name filter, then `n8n_archive_workflow` on the match. Reversible via `n8n_unarchive_workflow` (you'll still need `n8n_activate` to turn triggers back on).
268
+
269
+ > Delete the abandoned "poc-scraper" workflow — it's been dead for months *(requires `N8N_ENABLE_EDIT=true`)*
270
+
271
+ Calls `n8n_list_workflows` to find the id, then `n8n_delete_workflow` with `confirm: true`. A snapshot lands in `backupDir` first, but restore from backup is not a one-call operation — prefer `n8n_archive_workflow` unless you're sure.
252
272
 
253
273
  ## Development
254
274
 
@@ -7,10 +7,10 @@ import { z } from "zod";
7
7
 
8
8
  // src/client.ts
9
9
  var N8nApiError = class extends Error {
10
- constructor(status, path2, message) {
11
- super(`n8n ${status} on ${path2}: ${message}`);
10
+ constructor(status, path3, message) {
11
+ super(`n8n ${status} on ${path3}: ${message}`);
12
12
  this.status = status;
13
- this.path = path2;
13
+ this.path = path3;
14
14
  this.name = "N8nApiError";
15
15
  }
16
16
  status;
@@ -70,6 +70,30 @@ var N8nClient = class {
70
70
  method: "POST"
71
71
  });
72
72
  }
73
+ async archiveWorkflow(id) {
74
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
75
+ throw new Error(`Invalid workflow id: ${id}`);
76
+ }
77
+ return this.request(`/api/v1/workflows/${id}/archive`, {
78
+ method: "POST"
79
+ });
80
+ }
81
+ async unarchiveWorkflow(id) {
82
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
83
+ throw new Error(`Invalid workflow id: ${id}`);
84
+ }
85
+ return this.request(`/api/v1/workflows/${id}/unarchive`, {
86
+ method: "POST"
87
+ });
88
+ }
89
+ async deleteWorkflow(id) {
90
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
91
+ throw new Error(`Invalid workflow id: ${id}`);
92
+ }
93
+ return this.request(`/api/v1/workflows/${id}`, {
94
+ method: "DELETE"
95
+ });
96
+ }
73
97
  async executeWorkflow(id, payload) {
74
98
  if (!/^[A-Za-z0-9_-]+$/.test(id)) {
75
99
  throw new Error(`Invalid workflow id: ${id}`);
@@ -80,8 +104,8 @@ var N8nClient = class {
80
104
  });
81
105
  }
82
106
  async postWebhook(webhookPath, payload, opts = {}) {
83
- const path2 = webhookPath.startsWith("/") ? webhookPath : `/${webhookPath}`;
84
- const url = `${this.baseUrl}${path2}`;
107
+ const path3 = webhookPath.startsWith("/") ? webhookPath : `/${webhookPath}`;
108
+ const url = `${this.baseUrl}${path3}`;
85
109
  const method = (opts.method ?? "POST").toUpperCase();
86
110
  const controller = new AbortController();
87
111
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
@@ -110,7 +134,7 @@ var N8nClient = class {
110
134
  return { status: res.status, body };
111
135
  } catch (err) {
112
136
  const msg = err instanceof Error ? err.message : String(err);
113
- throw new Error(`n8n webhook to ${path2} failed: ${redactKey(msg, this.apiKey)}`);
137
+ throw new Error(`n8n webhook to ${path3} failed: ${redactKey(msg, this.apiKey)}`);
114
138
  } finally {
115
139
  clearTimeout(timer);
116
140
  }
@@ -143,14 +167,60 @@ var N8nClient = class {
143
167
  }
144
168
  return this.request(`/api/v1/executions/${id}/retry`, init);
145
169
  }
146
- async deleteExecution(id) {
170
+ async deleteExecution(id, opts = {}) {
147
171
  if (!/^[A-Za-z0-9_-]+$/.test(id)) {
148
172
  throw new Error(`Invalid execution id: ${id}`);
149
173
  }
150
174
  return this.request(`/api/v1/executions/${id}`, {
151
- method: "DELETE"
175
+ method: "DELETE",
176
+ signal: opts.signal
152
177
  });
153
178
  }
179
+ async deleteExecutions(ids, opts = {}) {
180
+ for (const id of ids) {
181
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
182
+ throw new Error(`Invalid execution id: ${id}`);
183
+ }
184
+ }
185
+ const concurrency = Math.max(1, Math.floor(opts.concurrency ?? 3));
186
+ const results = [];
187
+ const batchCtrl = new AbortController();
188
+ let cursor = 0;
189
+ const worker = async () => {
190
+ while (true) {
191
+ if (batchCtrl.signal.aborted) return;
192
+ const index = cursor++;
193
+ if (index >= ids.length) return;
194
+ if (batchCtrl.signal.aborted) return;
195
+ const id = ids[index];
196
+ try {
197
+ await this.deleteExecution(id, { signal: batchCtrl.signal });
198
+ results.push({ id, ok: true });
199
+ } catch (err) {
200
+ if (err instanceof N8nApiError && err.status === 404) {
201
+ results.push({ id, ok: true, reason: "already_deleted" });
202
+ continue;
203
+ }
204
+ if (isAbortError(err) && batchCtrl.signal.aborted) {
205
+ return;
206
+ }
207
+ const msg = err instanceof Error ? err.message : String(err);
208
+ const redacted = redactKey(msg, this.apiKey);
209
+ if (err instanceof N8nApiError && err.status >= 500) {
210
+ results.push({ id, ok: false, reason: "server_error", message: redacted });
211
+ batchCtrl.abort();
212
+ return;
213
+ }
214
+ results.push({ id, ok: false, reason: "error", message: redacted });
215
+ }
216
+ }
217
+ };
218
+ const workerCount = Math.min(concurrency, Math.max(ids.length, 1));
219
+ const workers = [];
220
+ for (let i = 0; i < workerCount; i++) workers.push(worker());
221
+ await Promise.all(workers);
222
+ return results;
223
+ }
154
224
  async listExecutions(params = {}) {
155
225
  const qs = new URLSearchParams();
156
226
  if (params.workflowId) qs.set("workflowId", params.workflowId);
@@ -162,13 +232,23 @@ var N8nClient = class {
162
232
  `/api/v1/executions${qs.toString() ? `?${qs}` : ""}`
163
233
  );
164
234
  }
165
- async request(path2, init = {}) {
166
- const url = `${this.baseUrl}${path2}`;
235
+ async request(path3, init = {}) {
236
+ const url = `${this.baseUrl}${path3}`;
167
237
  const controller = new AbortController();
168
238
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
239
+ const caller = init.signal;
240
+ let onCallerAbort;
241
+ if (caller) {
242
+ if (caller.aborted) controller.abort();
243
+ else {
244
+ onCallerAbort = () => controller.abort();
245
+ caller.addEventListener("abort", onCallerAbort, { once: true });
246
+ }
247
+ }
169
248
  try {
249
+ const { signal: _drop, ...rest } = init;
170
250
  const res = await fetch(url, {
171
- ...init,
251
+ ...rest,
172
252
  headers: {
173
253
  "X-N8N-API-KEY": this.apiKey,
174
254
  "Accept": "application/json",
@@ -179,16 +259,24 @@ var N8nClient = class {
179
259
  });
180
260
  const text = await res.text();
181
261
  if (!res.ok) {
182
- throw new N8nApiError(res.status, path2, redactKey(text, this.apiKey));
262
+ throw new N8nApiError(res.status, path3, redactKey(text, this.apiKey));
183
263
  }
184
264
  if (!text) return {};
185
265
  return JSON.parse(text);
186
266
  } catch (err) {
187
267
  if (err instanceof N8nApiError) throw err;
268
+ if (isAbortError(err) && caller?.aborted) {
269
+ const e = new Error(`n8n request to ${path3} aborted`);
270
+ e.name = "AbortError";
271
+ throw e;
272
+ }
188
273
  const msg = err instanceof Error ? err.message : String(err);
189
- throw new Error(`n8n request to ${path2} failed: ${redactKey(msg, this.apiKey)}`);
274
+ throw new Error(`n8n request to ${path3} failed: ${redactKey(msg, this.apiKey)}`);
190
275
  } finally {
191
276
  clearTimeout(timer);
277
+ if (caller && onCallerAbort) {
278
+ caller.removeEventListener("abort", onCallerAbort);
279
+ }
192
280
  }
193
281
  }
194
282
  };
@@ -196,6 +284,9 @@ function redactKey(text, apiKey) {
196
284
  if (!apiKey) return text;
197
285
  return text.split(apiKey).join("***REDACTED***");
198
286
  }
287
+ function isAbortError(err) {
288
+ return err instanceof Error && err.name === "AbortError";
289
+ }
199
290
 
200
291
  // src/config.ts
201
292
  function resolveApiKey(config) {
@@ -929,7 +1020,7 @@ function extractWebhook(rawNode, wf, baseUrl) {
929
1020
  if (type === "n8n-nodes-base.webhook") {
930
1021
  const pathRaw = typeof params.path === "string" && params.path.trim() ? params.path.trim() : typeof n.webhookId === "string" ? String(n.webhookId) : "";
931
1022
  if (!pathRaw) return null;
932
- const path2 = pathRaw.replace(/^\/+/, "");
1023
+ const path3 = pathRaw.replace(/^\/+/, "");
933
1024
  const method = typeof params.httpMethod === "string" && params.httpMethod.trim() ? params.httpMethod.toUpperCase() : "POST";
934
1025
  return {
935
1026
  workflowId: wf.id,
@@ -938,15 +1029,15 @@ function extractWebhook(rawNode, wf, baseUrl) {
938
1029
  nodeName: name,
939
1030
  nodeType: type,
940
1031
  method,
941
- path: `/webhook/${path2}`,
942
- triggerUrl: `${base}/webhook/${path2}`,
943
- testTriggerUrl: `${base}/webhook-test/${path2}`
1032
+ path: `/webhook/${path3}`,
1033
+ triggerUrl: `${base}/webhook/${path3}`,
1034
+ testTriggerUrl: `${base}/webhook-test/${path3}`
944
1035
  };
945
1036
  }
946
1037
  if (type === "n8n-nodes-base.formTrigger") {
947
1038
  const pathRaw = typeof params.path === "string" && params.path.trim() ? params.path.trim() : typeof n.webhookId === "string" ? String(n.webhookId) : "";
948
1039
  if (!pathRaw) return null;
949
- const path2 = pathRaw.replace(/^\/+/, "");
1040
+ const path3 = pathRaw.replace(/^\/+/, "");
950
1041
  return {
951
1042
  workflowId: wf.id,
952
1043
  workflowName: wf.name,
@@ -954,8 +1045,8 @@ function extractWebhook(rawNode, wf, baseUrl) {
954
1045
  nodeName: name,
955
1046
  nodeType: type,
956
1047
  method: "POST",
957
- path: `/form/${path2}`,
958
- triggerUrl: `${base}/form/${path2}`
1048
+ path: `/form/${path3}`,
1049
+ triggerUrl: `${base}/form/${path3}`
959
1050
  };
960
1051
  }
961
1052
  return null;
@@ -1492,8 +1583,256 @@ function createDeleteExecutionTool(getClient) {
1492
1583
  };
1493
1584
  }
1494
1585
 
1586
+ // src/tools/delete-executions.ts
1587
+ import { Type as Type15 } from "@sinclair/typebox";
1588
+ var DEFAULT_MAX_BATCH_SIZE = 50;
1589
+ var DEFAULT_CONCURRENCY = 3;
1590
+ var Schema15 = Type15.Object(
1591
+ {
1592
+ ids: Type15.Array(Type15.String(), {
1593
+ description: "Execution ids to delete (from n8n_search_executions or n8n_list_executions). Deduped before fan-out; non-empty required.",
1594
+ minItems: 1
1595
+ }),
1596
+ confirm: Type15.Boolean({
1597
+ 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."
1598
+ }),
1599
+ concurrency: Type15.Optional(
1600
+ Type15.Integer({
1601
+ minimum: 1,
1602
+ maximum: 10,
1603
+ description: "Parallel DELETE requests against the n8n API. Default 3. Keep low \u2014 n8n shares a database."
1604
+ })
1605
+ )
1606
+ },
1607
+ { additionalProperties: false }
1608
+ );
1609
+ function createDeleteExecutionsTool(getClient) {
1610
+ return {
1611
+ name: "n8n_delete_executions",
1612
+ label: "n8n: delete executions (batch)",
1613
+ 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.",
1614
+ parameters: Schema15,
1615
+ execute: async (_toolCallId, rawParams) => {
1616
+ const { ids, confirm, concurrency } = rawParams;
1617
+ if (!confirm) {
1618
+ return jsonToolResult({
1619
+ ok: false,
1620
+ action: "delete_batch",
1621
+ error: "confirm must be true to delete",
1622
+ hint: "Batch deletion is irreversible. Fetch n8n_get_execution first for any record you may need later."
1623
+ });
1624
+ }
1625
+ if (!Array.isArray(ids) || ids.length === 0) {
1626
+ return jsonToolResult({
1627
+ ok: false,
1628
+ action: "delete_batch",
1629
+ reason: "empty_ids",
1630
+ error: "ids must be a non-empty array"
1631
+ });
1632
+ }
1633
+ const deduped = Array.from(new Set(ids));
1634
+ if (deduped.length > DEFAULT_MAX_BATCH_SIZE) {
1635
+ return jsonToolResult({
1636
+ ok: false,
1637
+ action: "delete_batch",
1638
+ reason: "batch_too_large",
1639
+ error: `ids count ${deduped.length} exceeds maxBatchSize ${DEFAULT_MAX_BATCH_SIZE}`,
1640
+ hint: `Split into batches of at most ${DEFAULT_MAX_BATCH_SIZE} ids.`
1641
+ });
1642
+ }
1643
+ const client = getClient();
1644
+ const results = await client.deleteExecutions(
1645
+ deduped,
1646
+ { concurrency: concurrency ?? DEFAULT_CONCURRENCY }
1647
+ );
1648
+ const attempted = results.length;
1649
+ const deleted = results.filter(
1650
+ (r) => r.ok && r.reason !== "already_deleted"
1651
+ ).length;
1652
+ const alreadyDeleted = results.filter(
1653
+ (r) => r.reason === "already_deleted"
1654
+ ).length;
1655
+ const failed = results.filter((r) => !r.ok).length;
1656
+ const aborted = results.some((r) => r.reason === "server_error");
1657
+ const skipped = deduped.length - attempted;
1658
+ return jsonToolResult({
1659
+ ok: failed === 0,
1660
+ action: "delete_batch",
1661
+ requested: deduped.length,
1662
+ attempted,
1663
+ deleted,
1664
+ alreadyDeleted,
1665
+ failed,
1666
+ skipped,
1667
+ aborted,
1668
+ results
1669
+ });
1670
+ }
1671
+ };
1672
+ }
1673
+
1674
+ // src/tools/archive-workflow.ts
1675
+ import { Type as Type16 } from "@sinclair/typebox";
1676
+ var Schema16 = Type16.Object(
1677
+ {
1678
+ id: Type16.String({ description: "Workflow id (from n8n_list_workflows)." })
1679
+ },
1680
+ { additionalProperties: false }
1681
+ );
1682
+ function createArchiveWorkflowTool(getClient) {
1683
+ return buildTool(getClient, "archive");
1684
+ }
1685
+ function createUnarchiveWorkflowTool(getClient) {
1686
+ return buildTool(getClient, "unarchive");
1687
+ }
1688
+ function buildTool(getClient, action) {
1689
+ const name = action === "archive" ? "n8n_archive_workflow" : "n8n_unarchive_workflow";
1690
+ const label = action === "archive" ? "n8n: archive workflow" : "n8n: unarchive workflow";
1691
+ const description = action === "archive" ? "Soft-delete (archive) an n8n workflow via POST /workflows/{id}/archive. Reversible: pair with n8n_unarchive_workflow to restore. Idempotent: archiving an already-archived workflow returns the current state. Side effect: archiving deactivates the workflow, so triggers (webhooks, schedules) stop firing. Prefer this over n8n_delete_workflow for cleanup; it keeps history and definitions intact. Requires enableEdit." : "Restore an archived workflow via POST /workflows/{id}/unarchive. Does NOT reactivate: triggers stay off until n8n_activate is called explicitly. Requires enableEdit.";
1692
+ return {
1693
+ name,
1694
+ label,
1695
+ description,
1696
+ parameters: Schema16,
1697
+ execute: async (_toolCallId, rawParams) => {
1698
+ const { id } = rawParams;
1699
+ const client = getClient();
1700
+ try {
1701
+ const wf = action === "archive" ? await client.archiveWorkflow(id) : await client.unarchiveWorkflow(id);
1702
+ return jsonToolResult({
1703
+ ok: true,
1704
+ action,
1705
+ workflowId: wf.id,
1706
+ workflowName: wf.name,
1707
+ active: wf.active,
1708
+ isArchived: wf.isArchived ?? action === "archive",
1709
+ updatedAt: wf.updatedAt
1710
+ });
1711
+ } catch (err) {
1712
+ if (err instanceof N8nApiError && err.status === 404) {
1713
+ return jsonToolResult({
1714
+ ok: false,
1715
+ action,
1716
+ workflowId: id,
1717
+ reason: "not_found",
1718
+ message: "Workflow not found. It may have been deleted or never existed."
1719
+ });
1720
+ }
1721
+ throw err;
1722
+ }
1723
+ }
1724
+ };
1725
+ }
1726
+
1727
+ // src/tools/delete-workflow.ts
1728
+ import { Type as Type17 } from "@sinclair/typebox";
1729
+ import { promises as fs2 } from "fs";
1730
+ import { homedir as homedir2 } from "os";
1731
+ import path2 from "path";
1732
+ var Schema17 = Type17.Object(
1733
+ {
1734
+ id: Type17.String({ description: "Workflow id to delete (from n8n_list_workflows)." }),
1735
+ confirm: Type17.Boolean({
1736
+ description: "Must be true to actually delete. A snapshot of the workflow is written to backupDir before the DELETE fires. Deletion is irreversible via the Public API; restore is not a one-call operation (see restoreHint). Prefer n8n_archive_workflow for reversible cleanup."
1737
+ })
1738
+ },
1739
+ { additionalProperties: false }
1740
+ );
1741
+ function createDeleteWorkflowTool(deps) {
1742
+ return {
1743
+ name: "n8n_delete_workflow",
1744
+ label: "n8n: delete workflow",
1745
+ description: "Permanently delete an n8n workflow via DELETE /workflows/{id}. Irreversible. Snapshots the current workflow (nodes + connections + settings) to backupDir BEFORE firing the DELETE; if the snapshot fails, the delete is aborted. Does NOT cancel running executions first; those become orphans. Use n8n_list_executions(workflowId, status='running') + n8n_cancel_execution first if needed. Prefer n8n_archive_workflow for reversible cleanup. Requires enableEdit and explicit confirm=true.",
1746
+ parameters: Schema17,
1747
+ execute: async (_toolCallId, rawParams) => {
1748
+ const { id, confirm } = rawParams;
1749
+ if (!confirm) {
1750
+ return jsonToolResult({
1751
+ ok: false,
1752
+ action: "delete",
1753
+ workflowId: id,
1754
+ error: "confirm must be true to delete",
1755
+ hint: "Deletion is irreversible. Prefer n8n_archive_workflow for reversible cleanup, or fetch n8n_get_workflow with includeDefinition=true and save the output before calling this with confirm=true."
1756
+ });
1757
+ }
1758
+ const client = deps.getClient();
1759
+ let current;
1760
+ try {
1761
+ current = await client.getWorkflow(id);
1762
+ } catch (err) {
1763
+ if (err instanceof N8nApiError && err.status === 404) {
1764
+ return jsonToolResult({
1765
+ ok: false,
1766
+ action: "delete",
1767
+ workflowId: id,
1768
+ reason: "not_found",
1769
+ message: "Workflow not found. It may have already been deleted or never existed."
1770
+ });
1771
+ }
1772
+ throw err;
1773
+ }
1774
+ let backupPath;
1775
+ try {
1776
+ backupPath = await writeBackup2(resolveBackupDir2(deps.backupDir), current);
1777
+ } catch (err) {
1778
+ const msg = err instanceof Error ? err.message : String(err);
1779
+ return jsonToolResult({
1780
+ ok: false,
1781
+ action: "delete",
1782
+ workflowId: id,
1783
+ error: `backup failed; delete aborted: ${msg}`,
1784
+ hint: "The workflow was NOT deleted because the safety snapshot could not be written. Check backupDir permissions and retry."
1785
+ });
1786
+ }
1787
+ try {
1788
+ const deleted = await client.deleteWorkflow(id);
1789
+ return jsonToolResult({
1790
+ ok: true,
1791
+ action: "delete",
1792
+ workflowId: deleted.id ?? id,
1793
+ workflowName: deleted.name ?? current.name,
1794
+ backupPath,
1795
+ restoreHint: `Snapshot saved at ${backupPath}. Restore is NOT a one-call operation: n8n_save_workflow overwrites an existing workflow id, it does not recreate a deleted one. To restore, create a new workflow in the n8n UI (or via a future n8n_create_workflow) and paste the nodes/connections/settings from the snapshot.`
1796
+ });
1797
+ } catch (err) {
1798
+ if (err instanceof N8nApiError && err.status === 404) {
1799
+ return jsonToolResult({
1800
+ ok: false,
1801
+ action: "delete",
1802
+ workflowId: id,
1803
+ reason: "not_found",
1804
+ message: "Workflow disappeared between snapshot and delete (404). A snapshot was still captured.",
1805
+ backupPath
1806
+ });
1807
+ }
1808
+ const msg = err instanceof Error ? err.message : String(err);
1809
+ return jsonToolResult({
1810
+ ok: false,
1811
+ action: "delete",
1812
+ workflowId: id,
1813
+ error: `delete failed: ${msg}`,
1814
+ backupPath,
1815
+ hint: `Snapshot preserved at ${backupPath}. Server state may or may not have been mutated; fetch n8n_get_workflow to verify.`
1816
+ });
1817
+ }
1818
+ }
1819
+ };
1820
+ }
1821
+ function resolveBackupDir2(configured) {
1822
+ const raw = configured?.trim() || "~/.n8n-backups";
1823
+ return raw.startsWith("~") ? path2.join(homedir2(), raw.slice(1).replace(/^\/+/, "")) : raw;
1824
+ }
1825
+ async function writeBackup2(dir, wf) {
1826
+ await fs2.mkdir(dir, { recursive: true });
1827
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").replace("T", "_").replace("Z", "");
1828
+ const safeName = String(wf.id).replace(/[^A-Za-z0-9_-]/g, "_");
1829
+ const file = path2.join(dir, `${safeName}-DELETED-${stamp}.json`);
1830
+ await fs2.writeFile(file, JSON.stringify(wf, null, 2), { mode: 384 });
1831
+ return file;
1832
+ }
1833
+
1495
1834
  // mcp-server.ts
1496
- var VERSION = "0.5.0";
1835
+ var VERSION = "0.7.0";
1497
1836
  function readConfigFromEnv() {
1498
1837
  const baseUrl = (process.env.N8N_BASE_URL ?? "").trim();
1499
1838
  if (!baseUrl) {
@@ -1670,6 +2009,31 @@ async function main() {
1670
2009
  "Must be true to actually delete. Deletion is irreversible: execution logs, per-node run data, and error payloads are erased."
1671
2010
  )
1672
2011
  });
2012
+ bind(server, createDeleteExecutionsTool(getClient), {
2013
+ ids: z.array(z.string()).min(1).describe(
2014
+ "Execution ids to delete (from n8n_search_executions or n8n_list_executions). Deduped server-side; non-empty required."
2015
+ ),
2016
+ confirm: z.boolean().describe(
2017
+ "Must be true to actually delete. Deletion is irreversible: execution logs, per-node run data, and error payloads are erased."
2018
+ ),
2019
+ concurrency: z.number().int().min(1).max(10).optional().describe("Parallel DELETE requests. Default 3. Keep low - n8n shares a database.")
2020
+ });
2021
+ bind(server, createArchiveWorkflowTool(getClient), {
2022
+ id: z.string().describe("Workflow id to archive (from n8n_list_workflows).")
2023
+ });
2024
+ bind(server, createUnarchiveWorkflowTool(getClient), {
2025
+ id: z.string().describe("Workflow id to unarchive (from n8n_list_workflows).")
2026
+ });
2027
+ bind(
2028
+ server,
2029
+ createDeleteWorkflowTool({ getClient, backupDir: config.backupDir }),
2030
+ {
2031
+ id: z.string().describe("Workflow id to delete (from n8n_list_workflows)."),
2032
+ confirm: z.boolean().describe(
2033
+ "Must be true to actually delete. A snapshot is written to backupDir before the DELETE; restore is NOT a one-call operation. Prefer n8n_archive_workflow for reversible cleanup."
2034
+ )
2035
+ }
2036
+ );
1673
2037
  }
1674
2038
  const transport = new StdioServerTransport();
1675
2039
  await server.connect(transport);
package/index.ts CHANGED
@@ -15,6 +15,12 @@ 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";
19
+ import {
20
+ createArchiveWorkflowTool,
21
+ createUnarchiveWorkflowTool,
22
+ } from "./src/tools/archive-workflow.ts";
23
+ import { createDeleteWorkflowTool } from "./src/tools/delete-workflow.ts";
18
24
 
19
25
  export default definePluginEntry({
20
26
  id: "n8n",
@@ -55,6 +61,15 @@ export default definePluginEntry({
55
61
  api.registerTool(createCancelExecutionTool(getClient) as AnyAgentTool);
56
62
  api.registerTool(createRetryExecutionTool(getClient) as AnyAgentTool);
57
63
  api.registerTool(createDeleteExecutionTool(getClient) as AnyAgentTool);
64
+ api.registerTool(createDeleteExecutionsTool(getClient) as AnyAgentTool);
65
+ api.registerTool(createArchiveWorkflowTool(getClient) as AnyAgentTool);
66
+ api.registerTool(createUnarchiveWorkflowTool(getClient) as AnyAgentTool);
67
+ api.registerTool(
68
+ createDeleteWorkflowTool({
69
+ getClient,
70
+ backupDir: config.backupDir,
71
+ }) as AnyAgentTool,
72
+ );
58
73
  }
59
74
  },
60
75
  });
@@ -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 the full workflow + execution lifecycle write tools (activate, deactivate, save, archive, unarchive, delete-workflow, cancel-execution, retry-execution, delete-execution, delete-executions). Off by default. Destructive tools (save, delete-workflow, delete-execution, delete-executions) are confirm-gated; save and delete-workflow snapshot to backupDir first."
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 all workflow + execution lifecycle write tools. Workflows: activate, deactivate, save (confirm-gated, auto-backup), archive (reversible soft-delete), unarchive, delete-workflow (confirm-gated, snapshot-before-delete, restore is not one-call). Executions: cancel, retry, delete, delete-executions (batch fan-out, confirm-gated, capped at 50 ids, idempotent on 404, 5xx aborts the batch). Prefer archive over delete-workflow for cleanup."
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.1",
3
+ "version": "0.7.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,
@@ -150,6 +157,33 @@ export class N8nClient {
150
157
  });
151
158
  }
152
159
 
160
+ async archiveWorkflow(id: string): Promise<N8nWorkflow> {
161
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
162
+ throw new Error(`Invalid workflow id: ${id}`);
163
+ }
164
+ return this.request<N8nWorkflow>(`/api/v1/workflows/${id}/archive`, {
165
+ method: "POST",
166
+ });
167
+ }
168
+
169
+ async unarchiveWorkflow(id: string): Promise<N8nWorkflow> {
170
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
171
+ throw new Error(`Invalid workflow id: ${id}`);
172
+ }
173
+ return this.request<N8nWorkflow>(`/api/v1/workflows/${id}/unarchive`, {
174
+ method: "POST",
175
+ });
176
+ }
177
+
178
+ async deleteWorkflow(id: string): Promise<N8nWorkflow> {
179
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
180
+ throw new Error(`Invalid workflow id: ${id}`);
181
+ }
182
+ return this.request<N8nWorkflow>(`/api/v1/workflows/${id}`, {
183
+ method: "DELETE",
184
+ });
185
+ }
186
+
153
187
  async executeWorkflow(
154
188
  id: string,
155
189
  payload?: Record<string, unknown>,
@@ -241,15 +275,73 @@ export class N8nClient {
241
275
  return this.request<N8nExecution>(`/api/v1/executions/${id}/retry`, init);
242
276
  }
243
277
 
244
- async deleteExecution(id: string): Promise<N8nExecution> {
278
+ async deleteExecution(
279
+ id: string,
280
+ opts: { signal?: AbortSignal } = {},
281
+ ): Promise<N8nExecution> {
245
282
  if (!/^[A-Za-z0-9_-]+$/.test(id)) {
246
283
  throw new Error(`Invalid execution id: ${id}`);
247
284
  }
248
285
  return this.request<N8nExecution>(`/api/v1/executions/${id}`, {
249
286
  method: "DELETE",
287
+ signal: opts.signal,
250
288
  });
251
289
  }
252
290
 
291
+ async deleteExecutions(
292
+ ids: string[],
293
+ opts: { concurrency?: number } = {},
294
+ ): Promise<N8nBatchDeleteResult[]> {
295
+ for (const id of ids) {
296
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) {
297
+ throw new Error(`Invalid execution id: ${id}`);
298
+ }
299
+ }
300
+ const concurrency = Math.max(1, Math.floor(opts.concurrency ?? 3));
301
+ const results: N8nBatchDeleteResult[] = [];
302
+ const batchCtrl = new AbortController();
303
+ let cursor = 0;
304
+
305
+ const worker = async (): Promise<void> => {
306
+ while (true) {
307
+ if (batchCtrl.signal.aborted) return;
308
+ const index = cursor++;
309
+ if (index >= ids.length) return;
310
+ if (batchCtrl.signal.aborted) return;
311
+ const id = ids[index];
312
+ try {
313
+ await this.deleteExecution(id, { signal: batchCtrl.signal });
314
+ results.push({ id, ok: true });
315
+ } catch (err) {
316
+ if (err instanceof N8nApiError && err.status === 404) {
317
+ results.push({ id, ok: true, reason: "already_deleted" });
318
+ continue;
319
+ }
320
+ if (isAbortError(err) && batchCtrl.signal.aborted) {
321
+ // In-flight when batch was aborted by a peer's 5xx. Don't record —
322
+ // intentionally absent from results so the tool can surface
323
+ // skipped = requested - attempted.
324
+ return;
325
+ }
326
+ const msg = err instanceof Error ? err.message : String(err);
327
+ const redacted = redactKey(msg, this.apiKey);
328
+ if (err instanceof N8nApiError && err.status >= 500) {
329
+ results.push({ id, ok: false, reason: "server_error", message: redacted });
330
+ batchCtrl.abort();
331
+ return;
332
+ }
333
+ results.push({ id, ok: false, reason: "error", message: redacted });
334
+ }
335
+ }
336
+ };
337
+
338
+ const workerCount = Math.min(concurrency, Math.max(ids.length, 1));
339
+ const workers: Promise<void>[] = [];
340
+ for (let i = 0; i < workerCount; i++) workers.push(worker());
341
+ await Promise.all(workers);
342
+ return results;
343
+ }
344
+
253
345
  async listExecutions(params: {
254
346
  workflowId?: string;
255
347
  status?: string;
@@ -275,9 +367,19 @@ export class N8nClient {
275
367
  const url = `${this.baseUrl}${path}`;
276
368
  const controller = new AbortController();
277
369
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
370
+ const caller = init.signal as AbortSignal | null | undefined;
371
+ let onCallerAbort: (() => void) | undefined;
372
+ if (caller) {
373
+ if (caller.aborted) controller.abort();
374
+ else {
375
+ onCallerAbort = () => controller.abort();
376
+ caller.addEventListener("abort", onCallerAbort, { once: true });
377
+ }
378
+ }
278
379
  try {
380
+ const { signal: _drop, ...rest } = init;
279
381
  const res = await fetch(url, {
280
- ...init,
382
+ ...rest,
281
383
  headers: {
282
384
  "X-N8N-API-KEY": this.apiKey,
283
385
  "Accept": "application/json",
@@ -294,10 +396,18 @@ export class N8nClient {
294
396
  return JSON.parse(text) as T;
295
397
  } catch (err) {
296
398
  if (err instanceof N8nApiError) throw err;
399
+ if (isAbortError(err) && caller?.aborted) {
400
+ const e = new Error(`n8n request to ${path} aborted`);
401
+ e.name = "AbortError";
402
+ throw e;
403
+ }
297
404
  const msg = err instanceof Error ? err.message : String(err);
298
405
  throw new Error(`n8n request to ${path} failed: ${redactKey(msg, this.apiKey)}`);
299
406
  } finally {
300
407
  clearTimeout(timer);
408
+ if (caller && onCallerAbort) {
409
+ caller.removeEventListener("abort", onCallerAbort);
410
+ }
301
411
  }
302
412
  }
303
413
  }
@@ -306,3 +416,7 @@ function redactKey(text: string, apiKey: string): string {
306
416
  if (!apiKey) return text;
307
417
  return text.split(apiKey).join("***REDACTED***");
308
418
  }
419
+
420
+ function isAbortError(err: unknown): boolean {
421
+ return err instanceof Error && err.name === "AbortError";
422
+ }
@@ -0,0 +1,68 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import { N8nApiError, type N8nClient, type N8nWorkflow } from "../client.ts";
3
+ import { jsonToolResult } from "./result.ts";
4
+
5
+ const Schema = Type.Object(
6
+ {
7
+ id: Type.String({ description: "Workflow id (from n8n_list_workflows)." }),
8
+ },
9
+ { additionalProperties: false },
10
+ );
11
+
12
+ type Action = "archive" | "unarchive";
13
+
14
+ export function createArchiveWorkflowTool(getClient: () => N8nClient) {
15
+ return buildTool(getClient, "archive");
16
+ }
17
+
18
+ export function createUnarchiveWorkflowTool(getClient: () => N8nClient) {
19
+ return buildTool(getClient, "unarchive");
20
+ }
21
+
22
+ function buildTool(getClient: () => N8nClient, action: Action) {
23
+ const name = action === "archive" ? "n8n_archive_workflow" : "n8n_unarchive_workflow";
24
+ const label =
25
+ action === "archive" ? "n8n: archive workflow" : "n8n: unarchive workflow";
26
+ const description =
27
+ action === "archive"
28
+ ? "Soft-delete (archive) an n8n workflow via POST /workflows/{id}/archive. Reversible: pair with n8n_unarchive_workflow to restore. Idempotent: archiving an already-archived workflow returns the current state. Side effect: archiving deactivates the workflow, so triggers (webhooks, schedules) stop firing. Prefer this over n8n_delete_workflow for cleanup; it keeps history and definitions intact. Requires enableEdit."
29
+ : "Restore an archived workflow via POST /workflows/{id}/unarchive. Does NOT reactivate: triggers stay off until n8n_activate is called explicitly. Requires enableEdit.";
30
+
31
+ return {
32
+ name,
33
+ label,
34
+ description,
35
+ parameters: Schema,
36
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
37
+ const { id } = rawParams as { id: string };
38
+ const client = getClient();
39
+ try {
40
+ const wf: N8nWorkflow =
41
+ action === "archive"
42
+ ? await client.archiveWorkflow(id)
43
+ : await client.unarchiveWorkflow(id);
44
+ return jsonToolResult({
45
+ ok: true,
46
+ action,
47
+ workflowId: wf.id,
48
+ workflowName: wf.name,
49
+ active: wf.active,
50
+ isArchived: wf.isArchived ?? (action === "archive"),
51
+ updatedAt: wf.updatedAt,
52
+ });
53
+ } catch (err) {
54
+ if (err instanceof N8nApiError && err.status === 404) {
55
+ return jsonToolResult({
56
+ ok: false,
57
+ action,
58
+ workflowId: id,
59
+ reason: "not_found",
60
+ message:
61
+ "Workflow not found. It may have been deleted or never existed.",
62
+ });
63
+ }
64
+ throw err;
65
+ }
66
+ },
67
+ };
68
+ }
@@ -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
+ }
@@ -0,0 +1,130 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import { promises as fs } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { N8nApiError, type N8nClient, type N8nWorkflow } from "../client.ts";
6
+ import { jsonToolResult } from "./result.ts";
7
+
8
+ const Schema = Type.Object(
9
+ {
10
+ id: Type.String({ description: "Workflow id to delete (from n8n_list_workflows)." }),
11
+ confirm: Type.Boolean({
12
+ description:
13
+ "Must be true to actually delete. A snapshot of the workflow is written to backupDir before the DELETE fires. Deletion is irreversible via the Public API; restore is not a one-call operation (see restoreHint). Prefer n8n_archive_workflow for reversible cleanup.",
14
+ }),
15
+ },
16
+ { additionalProperties: false },
17
+ );
18
+
19
+ export interface DeleteWorkflowDeps {
20
+ getClient: () => N8nClient;
21
+ backupDir?: string;
22
+ }
23
+
24
+ export function createDeleteWorkflowTool(deps: DeleteWorkflowDeps) {
25
+ return {
26
+ name: "n8n_delete_workflow",
27
+ label: "n8n: delete workflow",
28
+ description:
29
+ "Permanently delete an n8n workflow via DELETE /workflows/{id}. Irreversible. Snapshots the current workflow (nodes + connections + settings) to backupDir BEFORE firing the DELETE; if the snapshot fails, the delete is aborted. Does NOT cancel running executions first; those become orphans. Use n8n_list_executions(workflowId, status='running') + n8n_cancel_execution first if needed. Prefer n8n_archive_workflow for reversible cleanup. Requires enableEdit and explicit confirm=true.",
30
+ parameters: Schema,
31
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
32
+ const { id, confirm } = rawParams as { id: string; confirm: boolean };
33
+ if (!confirm) {
34
+ return jsonToolResult({
35
+ ok: false,
36
+ action: "delete",
37
+ workflowId: id,
38
+ error: "confirm must be true to delete",
39
+ hint: "Deletion is irreversible. Prefer n8n_archive_workflow for reversible cleanup, or fetch n8n_get_workflow with includeDefinition=true and save the output before calling this with confirm=true.",
40
+ });
41
+ }
42
+
43
+ const client = deps.getClient();
44
+
45
+ let current: N8nWorkflow;
46
+ try {
47
+ current = await client.getWorkflow(id);
48
+ } catch (err) {
49
+ if (err instanceof N8nApiError && err.status === 404) {
50
+ return jsonToolResult({
51
+ ok: false,
52
+ action: "delete",
53
+ workflowId: id,
54
+ reason: "not_found",
55
+ message:
56
+ "Workflow not found. It may have already been deleted or never existed.",
57
+ });
58
+ }
59
+ throw err;
60
+ }
61
+
62
+ let backupPath: string;
63
+ try {
64
+ backupPath = await writeBackup(resolveBackupDir(deps.backupDir), current);
65
+ } catch (err) {
66
+ const msg = err instanceof Error ? err.message : String(err);
67
+ return jsonToolResult({
68
+ ok: false,
69
+ action: "delete",
70
+ workflowId: id,
71
+ error: `backup failed; delete aborted: ${msg}`,
72
+ hint: "The workflow was NOT deleted because the safety snapshot could not be written. Check backupDir permissions and retry.",
73
+ });
74
+ }
75
+
76
+ try {
77
+ const deleted = await client.deleteWorkflow(id);
78
+ return jsonToolResult({
79
+ ok: true,
80
+ action: "delete",
81
+ workflowId: deleted.id ?? id,
82
+ workflowName: deleted.name ?? current.name,
83
+ backupPath,
84
+ restoreHint: `Snapshot saved at ${backupPath}. Restore is NOT a one-call operation: n8n_save_workflow overwrites an existing workflow id, it does not recreate a deleted one. To restore, create a new workflow in the n8n UI (or via a future n8n_create_workflow) and paste the nodes/connections/settings from the snapshot.`,
85
+ });
86
+ } catch (err) {
87
+ if (err instanceof N8nApiError && err.status === 404) {
88
+ return jsonToolResult({
89
+ ok: false,
90
+ action: "delete",
91
+ workflowId: id,
92
+ reason: "not_found",
93
+ message:
94
+ "Workflow disappeared between snapshot and delete (404). A snapshot was still captured.",
95
+ backupPath,
96
+ });
97
+ }
98
+ const msg = err instanceof Error ? err.message : String(err);
99
+ return jsonToolResult({
100
+ ok: false,
101
+ action: "delete",
102
+ workflowId: id,
103
+ error: `delete failed: ${msg}`,
104
+ backupPath,
105
+ hint: `Snapshot preserved at ${backupPath}. Server state may or may not have been mutated; fetch n8n_get_workflow to verify.`,
106
+ });
107
+ }
108
+ },
109
+ };
110
+ }
111
+
112
+ function resolveBackupDir(configured?: string): string {
113
+ const raw = configured?.trim() || "~/.n8n-backups";
114
+ return raw.startsWith("~")
115
+ ? path.join(homedir(), raw.slice(1).replace(/^\/+/, ""))
116
+ : raw;
117
+ }
118
+
119
+ async function writeBackup(dir: string, wf: N8nWorkflow): Promise<string> {
120
+ await fs.mkdir(dir, { recursive: true });
121
+ const stamp = new Date()
122
+ .toISOString()
123
+ .replace(/[:.]/g, "-")
124
+ .replace("T", "_")
125
+ .replace("Z", "");
126
+ const safeName = String(wf.id).replace(/[^A-Za-z0-9_-]/g, "_");
127
+ const file = path.join(dir, `${safeName}-DELETED-${stamp}.json`);
128
+ await fs.writeFile(file, JSON.stringify(wf, null, 2), { mode: 0o600 });
129
+ return file;
130
+ }