n8n-ops-mcp 0.6.0 → 0.8.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 +28 -0
- package/dist/mcp-server.js +379 -20
- package/index.ts +15 -0
- package/openclaw.plugin.json +2 -2
- package/package.json +1 -1
- package/src/client.ts +34 -0
- package/src/tools/archive-workflow.ts +68 -0
- package/src/tools/create-workflow.ts +176 -0
- package/src/tools/delete-workflow.ts +130 -0
package/README.md
CHANGED
|
@@ -26,9 +26,13 @@ For a catalog/docs tool that indexes n8n's node library, see [n8n-mcp](https://w
|
|
|
26
26
|
| `n8n_list_webhooks` | Enumerate webhook + form-trigger URLs | |
|
|
27
27
|
| `n8n_validate_workflow` | Static checks: deprecated nodes, legacy Code-node API, orphans | |
|
|
28
28
|
| `n8n_trigger` | Run a workflow via webhook (reliable) or workflow-id | |
|
|
29
|
+
| `n8n_create_workflow` | Create a workflow (accepts `n8n_get_workflow` output directly; primary restore path) | ✓ |
|
|
29
30
|
| `n8n_activate` | Enable a workflow's triggers | ✓ |
|
|
30
31
|
| `n8n_deactivate` | Disable a workflow's triggers | ✓ |
|
|
31
32
|
| `n8n_save_workflow` | Overwrite a workflow with auto-backup + validation + confirm gate | ✓ |
|
|
33
|
+
| `n8n_archive_workflow` | Soft-delete a workflow (reversible; preserves id) | ✓ |
|
|
34
|
+
| `n8n_unarchive_workflow` | Restore an archived workflow (does NOT reactivate) | ✓ |
|
|
35
|
+
| `n8n_delete_workflow` | Permanently delete a workflow (confirm-gated, snapshot-before-delete, restore via `n8n_create_workflow`) | ✓ |
|
|
32
36
|
| `n8n_cancel_execution` | Stop a running or waiting execution by id | ✓ |
|
|
33
37
|
| `n8n_retry_execution` | Retry a failed execution by id (returns a new execution) | ✓ |
|
|
34
38
|
| `n8n_delete_execution` | Permanently delete an execution record (confirm-gated, irreversible) | ✓ |
|
|
@@ -57,10 +61,18 @@ Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
|
|
|
57
61
|
- `mode: "webhook"` + `webhookPath` — POST (or GET/PUT/DELETE) to the configured base URL + path, with an optional JSON `payload`. This is the reliable path.
|
|
58
62
|
- `mode: "workflow"` + `workflowId` — attempts `POST /api/v1/workflows/:id/execute`. Pre-checks that the workflow is active and has a webhook/manual/form trigger. Most n8n builds don't expose this endpoint on the Public API and will 405; the tool surfaces a hint to switch to webhook mode.
|
|
59
63
|
|
|
64
|
+
**`n8n_create_workflow`** — `POST /workflows`. Accepts the full output of `n8n_get_workflow` (with `includeDefinition=true`) directly. Strips read-only fields (`id`, `active`, `createdAt`, `updatedAt`, `isArchived`, `versionId`, `triggerCount`, `tags`, `shared`, `meta`, `pinData`) before POSTing — n8n enforces `additionalProperties: false` on the workflow schema and will 400 on any readOnly field. Runs `n8n_validate_workflow` on the proposed state as a pre-check; errors block, warnings pass through (pass `skipValidation: true` to bypass). No confirm gate — creation is non-destructive. The new workflow is created INACTIVE; call `n8n_activate` afterwards if you want triggers running. This is the primary restore path for `n8n_delete_workflow` snapshots: read the backup file into `definition` and call this tool. The restored workflow gets a new id.
|
|
65
|
+
|
|
60
66
|
**`n8n_activate`** / **`n8n_deactivate`** — idempotent. Deactivating does not cancel running executions.
|
|
61
67
|
|
|
62
68
|
**`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`.
|
|
63
69
|
|
|
70
|
+
**`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.
|
|
71
|
+
|
|
72
|
+
**`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.
|
|
73
|
+
|
|
74
|
+
**`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 one-call via `n8n_create_workflow`** with the snapshot contents; the restored workflow gets a new id and is created inactive. 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** if you want to preserve the original id.
|
|
75
|
+
|
|
64
76
|
**`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).
|
|
65
77
|
|
|
66
78
|
**`n8n_retry_execution`** — `POST /executions/{id}/retry`. Creates a NEW execution — the response surfaces both `originalExecutionId` and `newExecutionId` so agents can follow up with `n8n_get_execution` on the retry. Optional `loadWorkflow: true` retries against the currently saved workflow instead of the version captured at original execution time. Returns `ok: false` with `reason: "not_found"` on 404 or `reason: "not_retryable"` on 409 (e.g. still running); all other API errors rethrow.
|
|
@@ -253,6 +265,22 @@ Calls `n8n_search_executions` to find the failed id, then `n8n_retry_execution`
|
|
|
253
265
|
|
|
254
266
|
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.
|
|
255
267
|
|
|
268
|
+
> Archive the old "staging-bot" workflow — I might need it back someday *(requires `N8N_ENABLE_EDIT=true`)*
|
|
269
|
+
|
|
270
|
+
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).
|
|
271
|
+
|
|
272
|
+
> Delete the abandoned "poc-scraper" workflow — it's been dead for months *(requires `N8N_ENABLE_EDIT=true`)*
|
|
273
|
+
|
|
274
|
+
Calls `n8n_list_workflows` to find the id, then `n8n_delete_workflow` with `confirm: true`. A snapshot lands in `backupDir` first; restore is one-call via `n8n_create_workflow` with the snapshot. Prefer `n8n_archive_workflow` if you want to preserve the original id.
|
|
275
|
+
|
|
276
|
+
> Restore the workflow I accidentally deleted yesterday — backup is at `~/.n8n-backups/wf-42-DELETED-2026-04-22_15-00-00.json` *(requires `N8N_ENABLE_EDIT=true`)*
|
|
277
|
+
|
|
278
|
+
Reads the backup file, calls `n8n_create_workflow` with `definition=<backup contents>`. Read-only fields are stripped automatically; the restored workflow gets a new id and starts inactive. Call `n8n_activate` on the new id to re-enable triggers.
|
|
279
|
+
|
|
280
|
+
> Clone workflow "intel-nightly" to "intel-nightly-staging" for testing *(requires `N8N_ENABLE_EDIT=true`)*
|
|
281
|
+
|
|
282
|
+
Calls `n8n_get_workflow` with `includeDefinition=true`, changes `name` to "intel-nightly-staging" in the definition, then `n8n_create_workflow`. The new workflow is a full copy, inactive, with a fresh id.
|
|
283
|
+
|
|
256
284
|
## Development
|
|
257
285
|
|
|
258
286
|
```bash
|
package/dist/mcp-server.js
CHANGED
|
@@ -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,
|
|
11
|
-
super(`n8n ${status} on ${
|
|
10
|
+
constructor(status, path3, message) {
|
|
11
|
+
super(`n8n ${status} on ${path3}: ${message}`);
|
|
12
12
|
this.status = status;
|
|
13
|
-
this.path =
|
|
13
|
+
this.path = path3;
|
|
14
14
|
this.name = "N8nApiError";
|
|
15
15
|
}
|
|
16
16
|
status;
|
|
@@ -45,6 +45,12 @@ var N8nClient = class {
|
|
|
45
45
|
}
|
|
46
46
|
return this.request(`/api/v1/workflows/${id}`);
|
|
47
47
|
}
|
|
48
|
+
async createWorkflow(body) {
|
|
49
|
+
return this.request(`/api/v1/workflows`, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
body: JSON.stringify(body)
|
|
52
|
+
});
|
|
53
|
+
}
|
|
48
54
|
async saveWorkflow(id, body) {
|
|
49
55
|
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
50
56
|
throw new Error(`Invalid workflow id: ${id}`);
|
|
@@ -70,6 +76,30 @@ var N8nClient = class {
|
|
|
70
76
|
method: "POST"
|
|
71
77
|
});
|
|
72
78
|
}
|
|
79
|
+
async archiveWorkflow(id) {
|
|
80
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
81
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
82
|
+
}
|
|
83
|
+
return this.request(`/api/v1/workflows/${id}/archive`, {
|
|
84
|
+
method: "POST"
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async unarchiveWorkflow(id) {
|
|
88
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
89
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
90
|
+
}
|
|
91
|
+
return this.request(`/api/v1/workflows/${id}/unarchive`, {
|
|
92
|
+
method: "POST"
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
async deleteWorkflow(id) {
|
|
96
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
97
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
98
|
+
}
|
|
99
|
+
return this.request(`/api/v1/workflows/${id}`, {
|
|
100
|
+
method: "DELETE"
|
|
101
|
+
});
|
|
102
|
+
}
|
|
73
103
|
async executeWorkflow(id, payload) {
|
|
74
104
|
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
75
105
|
throw new Error(`Invalid workflow id: ${id}`);
|
|
@@ -80,8 +110,8 @@ var N8nClient = class {
|
|
|
80
110
|
});
|
|
81
111
|
}
|
|
82
112
|
async postWebhook(webhookPath, payload, opts = {}) {
|
|
83
|
-
const
|
|
84
|
-
const url = `${this.baseUrl}${
|
|
113
|
+
const path3 = webhookPath.startsWith("/") ? webhookPath : `/${webhookPath}`;
|
|
114
|
+
const url = `${this.baseUrl}${path3}`;
|
|
85
115
|
const method = (opts.method ?? "POST").toUpperCase();
|
|
86
116
|
const controller = new AbortController();
|
|
87
117
|
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
@@ -110,7 +140,7 @@ var N8nClient = class {
|
|
|
110
140
|
return { status: res.status, body };
|
|
111
141
|
} catch (err) {
|
|
112
142
|
const msg = err instanceof Error ? err.message : String(err);
|
|
113
|
-
throw new Error(`n8n webhook to ${
|
|
143
|
+
throw new Error(`n8n webhook to ${path3} failed: ${redactKey(msg, this.apiKey)}`);
|
|
114
144
|
} finally {
|
|
115
145
|
clearTimeout(timer);
|
|
116
146
|
}
|
|
@@ -208,8 +238,8 @@ var N8nClient = class {
|
|
|
208
238
|
`/api/v1/executions${qs.toString() ? `?${qs}` : ""}`
|
|
209
239
|
);
|
|
210
240
|
}
|
|
211
|
-
async request(
|
|
212
|
-
const url = `${this.baseUrl}${
|
|
241
|
+
async request(path3, init = {}) {
|
|
242
|
+
const url = `${this.baseUrl}${path3}`;
|
|
213
243
|
const controller = new AbortController();
|
|
214
244
|
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
215
245
|
const caller = init.signal;
|
|
@@ -235,19 +265,19 @@ var N8nClient = class {
|
|
|
235
265
|
});
|
|
236
266
|
const text = await res.text();
|
|
237
267
|
if (!res.ok) {
|
|
238
|
-
throw new N8nApiError(res.status,
|
|
268
|
+
throw new N8nApiError(res.status, path3, redactKey(text, this.apiKey));
|
|
239
269
|
}
|
|
240
270
|
if (!text) return {};
|
|
241
271
|
return JSON.parse(text);
|
|
242
272
|
} catch (err) {
|
|
243
273
|
if (err instanceof N8nApiError) throw err;
|
|
244
274
|
if (isAbortError(err) && caller?.aborted) {
|
|
245
|
-
const e = new Error(`n8n request to ${
|
|
275
|
+
const e = new Error(`n8n request to ${path3} aborted`);
|
|
246
276
|
e.name = "AbortError";
|
|
247
277
|
throw e;
|
|
248
278
|
}
|
|
249
279
|
const msg = err instanceof Error ? err.message : String(err);
|
|
250
|
-
throw new Error(`n8n request to ${
|
|
280
|
+
throw new Error(`n8n request to ${path3} failed: ${redactKey(msg, this.apiKey)}`);
|
|
251
281
|
} finally {
|
|
252
282
|
clearTimeout(timer);
|
|
253
283
|
if (caller && onCallerAbort) {
|
|
@@ -996,7 +1026,7 @@ function extractWebhook(rawNode, wf, baseUrl) {
|
|
|
996
1026
|
if (type === "n8n-nodes-base.webhook") {
|
|
997
1027
|
const pathRaw = typeof params.path === "string" && params.path.trim() ? params.path.trim() : typeof n.webhookId === "string" ? String(n.webhookId) : "";
|
|
998
1028
|
if (!pathRaw) return null;
|
|
999
|
-
const
|
|
1029
|
+
const path3 = pathRaw.replace(/^\/+/, "");
|
|
1000
1030
|
const method = typeof params.httpMethod === "string" && params.httpMethod.trim() ? params.httpMethod.toUpperCase() : "POST";
|
|
1001
1031
|
return {
|
|
1002
1032
|
workflowId: wf.id,
|
|
@@ -1005,15 +1035,15 @@ function extractWebhook(rawNode, wf, baseUrl) {
|
|
|
1005
1035
|
nodeName: name,
|
|
1006
1036
|
nodeType: type,
|
|
1007
1037
|
method,
|
|
1008
|
-
path: `/webhook/${
|
|
1009
|
-
triggerUrl: `${base}/webhook/${
|
|
1010
|
-
testTriggerUrl: `${base}/webhook-test/${
|
|
1038
|
+
path: `/webhook/${path3}`,
|
|
1039
|
+
triggerUrl: `${base}/webhook/${path3}`,
|
|
1040
|
+
testTriggerUrl: `${base}/webhook-test/${path3}`
|
|
1011
1041
|
};
|
|
1012
1042
|
}
|
|
1013
1043
|
if (type === "n8n-nodes-base.formTrigger") {
|
|
1014
1044
|
const pathRaw = typeof params.path === "string" && params.path.trim() ? params.path.trim() : typeof n.webhookId === "string" ? String(n.webhookId) : "";
|
|
1015
1045
|
if (!pathRaw) return null;
|
|
1016
|
-
const
|
|
1046
|
+
const path3 = pathRaw.replace(/^\/+/, "");
|
|
1017
1047
|
return {
|
|
1018
1048
|
workflowId: wf.id,
|
|
1019
1049
|
workflowName: wf.name,
|
|
@@ -1021,8 +1051,8 @@ function extractWebhook(rawNode, wf, baseUrl) {
|
|
|
1021
1051
|
nodeName: name,
|
|
1022
1052
|
nodeType: type,
|
|
1023
1053
|
method: "POST",
|
|
1024
|
-
path: `/form/${
|
|
1025
|
-
triggerUrl: `${base}/form/${
|
|
1054
|
+
path: `/form/${path3}`,
|
|
1055
|
+
triggerUrl: `${base}/form/${path3}`
|
|
1026
1056
|
};
|
|
1027
1057
|
}
|
|
1028
1058
|
return null;
|
|
@@ -1647,8 +1677,309 @@ function createDeleteExecutionsTool(getClient) {
|
|
|
1647
1677
|
};
|
|
1648
1678
|
}
|
|
1649
1679
|
|
|
1680
|
+
// src/tools/archive-workflow.ts
|
|
1681
|
+
import { Type as Type16 } from "@sinclair/typebox";
|
|
1682
|
+
var Schema16 = Type16.Object(
|
|
1683
|
+
{
|
|
1684
|
+
id: Type16.String({ description: "Workflow id (from n8n_list_workflows)." })
|
|
1685
|
+
},
|
|
1686
|
+
{ additionalProperties: false }
|
|
1687
|
+
);
|
|
1688
|
+
function createArchiveWorkflowTool(getClient) {
|
|
1689
|
+
return buildTool(getClient, "archive");
|
|
1690
|
+
}
|
|
1691
|
+
function createUnarchiveWorkflowTool(getClient) {
|
|
1692
|
+
return buildTool(getClient, "unarchive");
|
|
1693
|
+
}
|
|
1694
|
+
function buildTool(getClient, action) {
|
|
1695
|
+
const name = action === "archive" ? "n8n_archive_workflow" : "n8n_unarchive_workflow";
|
|
1696
|
+
const label = action === "archive" ? "n8n: archive workflow" : "n8n: unarchive workflow";
|
|
1697
|
+
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.";
|
|
1698
|
+
return {
|
|
1699
|
+
name,
|
|
1700
|
+
label,
|
|
1701
|
+
description,
|
|
1702
|
+
parameters: Schema16,
|
|
1703
|
+
execute: async (_toolCallId, rawParams) => {
|
|
1704
|
+
const { id } = rawParams;
|
|
1705
|
+
const client = getClient();
|
|
1706
|
+
try {
|
|
1707
|
+
const wf = action === "archive" ? await client.archiveWorkflow(id) : await client.unarchiveWorkflow(id);
|
|
1708
|
+
return jsonToolResult({
|
|
1709
|
+
ok: true,
|
|
1710
|
+
action,
|
|
1711
|
+
workflowId: wf.id,
|
|
1712
|
+
workflowName: wf.name,
|
|
1713
|
+
active: wf.active,
|
|
1714
|
+
isArchived: wf.isArchived ?? action === "archive",
|
|
1715
|
+
updatedAt: wf.updatedAt
|
|
1716
|
+
});
|
|
1717
|
+
} catch (err) {
|
|
1718
|
+
if (err instanceof N8nApiError && err.status === 404) {
|
|
1719
|
+
return jsonToolResult({
|
|
1720
|
+
ok: false,
|
|
1721
|
+
action,
|
|
1722
|
+
workflowId: id,
|
|
1723
|
+
reason: "not_found",
|
|
1724
|
+
message: "Workflow not found. It may have been deleted or never existed."
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
throw err;
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
// src/tools/delete-workflow.ts
|
|
1734
|
+
import { Type as Type17 } from "@sinclair/typebox";
|
|
1735
|
+
import { promises as fs2 } from "fs";
|
|
1736
|
+
import { homedir as homedir2 } from "os";
|
|
1737
|
+
import path2 from "path";
|
|
1738
|
+
var Schema17 = Type17.Object(
|
|
1739
|
+
{
|
|
1740
|
+
id: Type17.String({ description: "Workflow id to delete (from n8n_list_workflows)." }),
|
|
1741
|
+
confirm: Type17.Boolean({
|
|
1742
|
+
description: "Must be true to actually delete. A snapshot is written to backupDir before the DELETE fires. The deleted workflow is gone from n8n; restore by calling n8n_create_workflow with the snapshot (see restoreHint). The restored workflow gets a new id. Prefer n8n_archive_workflow for reversible cleanup that preserves the id."
|
|
1743
|
+
})
|
|
1744
|
+
},
|
|
1745
|
+
{ additionalProperties: false }
|
|
1746
|
+
);
|
|
1747
|
+
function createDeleteWorkflowTool(deps) {
|
|
1748
|
+
return {
|
|
1749
|
+
name: "n8n_delete_workflow",
|
|
1750
|
+
label: "n8n: delete workflow",
|
|
1751
|
+
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.",
|
|
1752
|
+
parameters: Schema17,
|
|
1753
|
+
execute: async (_toolCallId, rawParams) => {
|
|
1754
|
+
const { id, confirm } = rawParams;
|
|
1755
|
+
if (!confirm) {
|
|
1756
|
+
return jsonToolResult({
|
|
1757
|
+
ok: false,
|
|
1758
|
+
action: "delete",
|
|
1759
|
+
workflowId: id,
|
|
1760
|
+
error: "confirm must be true to delete",
|
|
1761
|
+
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."
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
const client = deps.getClient();
|
|
1765
|
+
let current;
|
|
1766
|
+
try {
|
|
1767
|
+
current = await client.getWorkflow(id);
|
|
1768
|
+
} catch (err) {
|
|
1769
|
+
if (err instanceof N8nApiError && err.status === 404) {
|
|
1770
|
+
return jsonToolResult({
|
|
1771
|
+
ok: false,
|
|
1772
|
+
action: "delete",
|
|
1773
|
+
workflowId: id,
|
|
1774
|
+
reason: "not_found",
|
|
1775
|
+
message: "Workflow not found. It may have already been deleted or never existed."
|
|
1776
|
+
});
|
|
1777
|
+
}
|
|
1778
|
+
throw err;
|
|
1779
|
+
}
|
|
1780
|
+
let backupPath;
|
|
1781
|
+
try {
|
|
1782
|
+
backupPath = await writeBackup2(resolveBackupDir2(deps.backupDir), current);
|
|
1783
|
+
} catch (err) {
|
|
1784
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1785
|
+
return jsonToolResult({
|
|
1786
|
+
ok: false,
|
|
1787
|
+
action: "delete",
|
|
1788
|
+
workflowId: id,
|
|
1789
|
+
error: `backup failed; delete aborted: ${msg}`,
|
|
1790
|
+
hint: "The workflow was NOT deleted because the safety snapshot could not be written. Check backupDir permissions and retry."
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
try {
|
|
1794
|
+
const deleted = await client.deleteWorkflow(id);
|
|
1795
|
+
return jsonToolResult({
|
|
1796
|
+
ok: true,
|
|
1797
|
+
action: "delete",
|
|
1798
|
+
workflowId: deleted.id ?? id,
|
|
1799
|
+
workflowName: deleted.name ?? current.name,
|
|
1800
|
+
backupPath,
|
|
1801
|
+
restoreHint: `Snapshot saved at ${backupPath}. To restore: call n8n_create_workflow with definition=<contents of ${backupPath}>. Read-only fields are stripped server-side; the restored workflow gets a new id and starts inactive (call n8n_activate to re-enable triggers).`
|
|
1802
|
+
});
|
|
1803
|
+
} catch (err) {
|
|
1804
|
+
if (err instanceof N8nApiError && err.status === 404) {
|
|
1805
|
+
return jsonToolResult({
|
|
1806
|
+
ok: false,
|
|
1807
|
+
action: "delete",
|
|
1808
|
+
workflowId: id,
|
|
1809
|
+
reason: "not_found",
|
|
1810
|
+
message: "Workflow disappeared between snapshot and delete (404). A snapshot was still captured.",
|
|
1811
|
+
backupPath
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1815
|
+
return jsonToolResult({
|
|
1816
|
+
ok: false,
|
|
1817
|
+
action: "delete",
|
|
1818
|
+
workflowId: id,
|
|
1819
|
+
error: `delete failed: ${msg}`,
|
|
1820
|
+
backupPath,
|
|
1821
|
+
hint: `Snapshot preserved at ${backupPath}. Server state may or may not have been mutated; fetch n8n_get_workflow to verify.`
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
function resolveBackupDir2(configured) {
|
|
1828
|
+
const raw = configured?.trim() || "~/.n8n-backups";
|
|
1829
|
+
return raw.startsWith("~") ? path2.join(homedir2(), raw.slice(1).replace(/^\/+/, "")) : raw;
|
|
1830
|
+
}
|
|
1831
|
+
async function writeBackup2(dir, wf) {
|
|
1832
|
+
await fs2.mkdir(dir, { recursive: true });
|
|
1833
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").replace("T", "_").replace("Z", "");
|
|
1834
|
+
const safeName = String(wf.id).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
1835
|
+
const file = path2.join(dir, `${safeName}-DELETED-${stamp}.json`);
|
|
1836
|
+
await fs2.writeFile(file, JSON.stringify(wf, null, 2), { mode: 384 });
|
|
1837
|
+
return file;
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
// src/tools/create-workflow.ts
|
|
1841
|
+
import { Type as Type18 } from "@sinclair/typebox";
|
|
1842
|
+
var Schema18 = Type18.Object(
|
|
1843
|
+
{
|
|
1844
|
+
definition: Type18.Object(
|
|
1845
|
+
{
|
|
1846
|
+
name: Type18.String({
|
|
1847
|
+
description: "Workflow name (required). Not enforced unique by n8n."
|
|
1848
|
+
}),
|
|
1849
|
+
// nodes/connections may live at the top level (flat snapshot) OR nested
|
|
1850
|
+
// under `definition` (n8n_get_workflow shape) - optional at both levels.
|
|
1851
|
+
nodes: Type18.Optional(Type18.Array(Type18.Record(Type18.String(), Type18.Unknown()))),
|
|
1852
|
+
connections: Type18.Optional(Type18.Record(Type18.String(), Type18.Unknown())),
|
|
1853
|
+
// n8n_get_workflow emits null for empty settings/staticData; accept
|
|
1854
|
+
// null here and coerce at runtime. Rejecting null would block the
|
|
1855
|
+
// documented direct-forward path before normalization runs.
|
|
1856
|
+
settings: Type18.Optional(
|
|
1857
|
+
Type18.Union([Type18.Record(Type18.String(), Type18.Unknown()), Type18.Null()])
|
|
1858
|
+
),
|
|
1859
|
+
staticData: Type18.Optional(Type18.Unknown()),
|
|
1860
|
+
definition: Type18.Optional(
|
|
1861
|
+
Type18.Object(
|
|
1862
|
+
{
|
|
1863
|
+
nodes: Type18.Optional(
|
|
1864
|
+
Type18.Array(Type18.Record(Type18.String(), Type18.Unknown()))
|
|
1865
|
+
),
|
|
1866
|
+
connections: Type18.Optional(Type18.Record(Type18.String(), Type18.Unknown())),
|
|
1867
|
+
settings: Type18.Optional(
|
|
1868
|
+
Type18.Union([
|
|
1869
|
+
Type18.Record(Type18.String(), Type18.Unknown()),
|
|
1870
|
+
Type18.Null()
|
|
1871
|
+
])
|
|
1872
|
+
),
|
|
1873
|
+
staticData: Type18.Optional(Type18.Unknown())
|
|
1874
|
+
},
|
|
1875
|
+
{ additionalProperties: true }
|
|
1876
|
+
)
|
|
1877
|
+
)
|
|
1878
|
+
},
|
|
1879
|
+
{
|
|
1880
|
+
additionalProperties: true,
|
|
1881
|
+
description: "Workflow body to create. Accepts two shapes: (1) a flat snapshot from n8n_delete_workflow or n8n_save_workflow (nodes/connections at the top level), or (2) the output of n8n_get_workflow with includeDefinition=true (graph data nested under `definition`, empty settings/staticData may arrive as null). Read-only fields (id, active, createdAt, updatedAt, isArchived, versionId, triggerCount, tags, shared, meta, pinData) are stripped before POST; null settings/staticData are normalized."
|
|
1882
|
+
}
|
|
1883
|
+
),
|
|
1884
|
+
skipValidation: Type18.Optional(
|
|
1885
|
+
Type18.Boolean({
|
|
1886
|
+
description: "Skip the n8n_validate_workflow pre-check. Default false. Validation errors (not warnings) block the create by default."
|
|
1887
|
+
})
|
|
1888
|
+
)
|
|
1889
|
+
},
|
|
1890
|
+
{ additionalProperties: false }
|
|
1891
|
+
);
|
|
1892
|
+
var READ_ONLY_FIELDS = [
|
|
1893
|
+
"id",
|
|
1894
|
+
"active",
|
|
1895
|
+
"createdAt",
|
|
1896
|
+
"updatedAt",
|
|
1897
|
+
"isArchived",
|
|
1898
|
+
"versionId",
|
|
1899
|
+
"triggerCount",
|
|
1900
|
+
"tags",
|
|
1901
|
+
"shared",
|
|
1902
|
+
"meta",
|
|
1903
|
+
"pinData"
|
|
1904
|
+
];
|
|
1905
|
+
function createCreateWorkflowTool(deps) {
|
|
1906
|
+
return {
|
|
1907
|
+
name: "n8n_create_workflow",
|
|
1908
|
+
label: "n8n: create workflow",
|
|
1909
|
+
description: "Create a new n8n workflow via POST /workflows. Accepts the output of n8n_get_workflow (includeDefinition=true) directly: read-only fields (id, active, createdAt, etc.) are stripped before POST. The new workflow is created INACTIVE; call n8n_activate afterwards if you want triggers running. Runs n8n_validate_workflow as a pre-check by default (errors block, warnings pass through); pass skipValidation:true to bypass. Primary restore path for n8n_delete_workflow snapshots. Requires enableEdit.",
|
|
1910
|
+
parameters: Schema18,
|
|
1911
|
+
execute: async (_toolCallId, rawParams) => {
|
|
1912
|
+
const params = rawParams;
|
|
1913
|
+
const client = deps.getClient();
|
|
1914
|
+
const body = buildCreateBody(params.definition);
|
|
1915
|
+
if (!params.skipValidation) {
|
|
1916
|
+
const proposed = {
|
|
1917
|
+
id: "__pending__",
|
|
1918
|
+
name: String(body.name ?? ""),
|
|
1919
|
+
active: false,
|
|
1920
|
+
createdAt: "",
|
|
1921
|
+
updatedAt: "",
|
|
1922
|
+
nodes: body.nodes ?? [],
|
|
1923
|
+
connections: body.connections ?? {},
|
|
1924
|
+
settings: body.settings ?? {}
|
|
1925
|
+
};
|
|
1926
|
+
const issues = validateWorkflow(proposed);
|
|
1927
|
+
const errors = issues.filter((i) => i.severity === "error");
|
|
1928
|
+
if (errors.length > 0) {
|
|
1929
|
+
return jsonToolResult({
|
|
1930
|
+
ok: false,
|
|
1931
|
+
error: "validation failed; create aborted",
|
|
1932
|
+
issues
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
try {
|
|
1937
|
+
const created = await client.createWorkflow(body);
|
|
1938
|
+
return jsonToolResult({
|
|
1939
|
+
ok: true,
|
|
1940
|
+
action: "create",
|
|
1941
|
+
workflowId: created.id,
|
|
1942
|
+
workflowName: created.name,
|
|
1943
|
+
active: created.active ?? false,
|
|
1944
|
+
createdAt: created.createdAt ?? null,
|
|
1945
|
+
updatedAt: created.updatedAt ?? null,
|
|
1946
|
+
hint: "Workflow is created inactive. Call n8n_activate to start its triggers."
|
|
1947
|
+
});
|
|
1948
|
+
} catch (err) {
|
|
1949
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1950
|
+
return jsonToolResult({
|
|
1951
|
+
ok: false,
|
|
1952
|
+
error: `create failed: ${msg}`
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
function buildCreateBody(proposed) {
|
|
1959
|
+
const flat = { ...proposed };
|
|
1960
|
+
const def = flat.definition;
|
|
1961
|
+
if (def && typeof def === "object" && !Array.isArray(def)) {
|
|
1962
|
+
Object.assign(flat, def);
|
|
1963
|
+
}
|
|
1964
|
+
delete flat.definition;
|
|
1965
|
+
for (const field of READ_ONLY_FIELDS) {
|
|
1966
|
+
delete flat[field];
|
|
1967
|
+
}
|
|
1968
|
+
const settings = flat.settings === null || flat.settings === void 0 ? {} : flat.settings;
|
|
1969
|
+
const body = {
|
|
1970
|
+
name: flat.name,
|
|
1971
|
+
nodes: flat.nodes ?? [],
|
|
1972
|
+
connections: flat.connections ?? {},
|
|
1973
|
+
settings
|
|
1974
|
+
};
|
|
1975
|
+
if (flat.staticData !== void 0 && flat.staticData !== null) {
|
|
1976
|
+
body.staticData = flat.staticData;
|
|
1977
|
+
}
|
|
1978
|
+
return body;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1650
1981
|
// mcp-server.ts
|
|
1651
|
-
var VERSION = "0.
|
|
1982
|
+
var VERSION = "0.8.0";
|
|
1652
1983
|
function readConfigFromEnv() {
|
|
1653
1984
|
const baseUrl = (process.env.N8N_BASE_URL ?? "").trim();
|
|
1654
1985
|
if (!baseUrl) {
|
|
@@ -1832,7 +2163,35 @@ async function main() {
|
|
|
1832
2163
|
confirm: z.boolean().describe(
|
|
1833
2164
|
"Must be true to actually delete. Deletion is irreversible: execution logs, per-node run data, and error payloads are erased."
|
|
1834
2165
|
),
|
|
1835
|
-
concurrency: z.number().int().min(1).max(10).optional().describe("Parallel DELETE requests. Default 3. Keep low
|
|
2166
|
+
concurrency: z.number().int().min(1).max(10).optional().describe("Parallel DELETE requests. Default 3. Keep low - n8n shares a database.")
|
|
2167
|
+
});
|
|
2168
|
+
bind(server, createArchiveWorkflowTool(getClient), {
|
|
2169
|
+
id: z.string().describe("Workflow id to archive (from n8n_list_workflows).")
|
|
2170
|
+
});
|
|
2171
|
+
bind(server, createUnarchiveWorkflowTool(getClient), {
|
|
2172
|
+
id: z.string().describe("Workflow id to unarchive (from n8n_list_workflows).")
|
|
2173
|
+
});
|
|
2174
|
+
bind(
|
|
2175
|
+
server,
|
|
2176
|
+
createDeleteWorkflowTool({ getClient, backupDir: config.backupDir }),
|
|
2177
|
+
{
|
|
2178
|
+
id: z.string().describe("Workflow id to delete (from n8n_list_workflows)."),
|
|
2179
|
+
confirm: z.boolean().describe(
|
|
2180
|
+
"Must be true to actually delete. A snapshot is written to backupDir before the DELETE; restore via n8n_create_workflow with the snapshot. Prefer n8n_archive_workflow for reversible cleanup that preserves the id."
|
|
2181
|
+
)
|
|
2182
|
+
}
|
|
2183
|
+
);
|
|
2184
|
+
bind(server, createCreateWorkflowTool({ getClient }), {
|
|
2185
|
+
definition: z.object({
|
|
2186
|
+
name: z.string(),
|
|
2187
|
+
nodes: z.array(z.record(z.string(), z.unknown())).optional(),
|
|
2188
|
+
connections: z.record(z.string(), z.unknown()).optional(),
|
|
2189
|
+
settings: z.record(z.string(), z.unknown()).nullable().optional(),
|
|
2190
|
+
staticData: z.unknown().optional()
|
|
2191
|
+
}).loose().describe(
|
|
2192
|
+
"Workflow body to create. Accepts either a flat snapshot (n8n_delete_workflow backup file, nodes at top level) or the nested n8n_get_workflow(includeDefinition=true) shape (graph data under `definition`, null settings/staticData allowed). Read-only fields are stripped. Primary restore path for n8n_delete_workflow snapshots."
|
|
2193
|
+
),
|
|
2194
|
+
skipValidation: z.boolean().optional().describe("Skip the validate-workflow pre-check. Default false.")
|
|
1836
2195
|
});
|
|
1837
2196
|
}
|
|
1838
2197
|
const transport = new StdioServerTransport();
|
package/index.ts
CHANGED
|
@@ -16,6 +16,12 @@ 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
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";
|
|
24
|
+
import { createCreateWorkflowTool } from "./src/tools/create-workflow.ts";
|
|
19
25
|
|
|
20
26
|
export default definePluginEntry({
|
|
21
27
|
id: "n8n",
|
|
@@ -57,6 +63,15 @@ export default definePluginEntry({
|
|
|
57
63
|
api.registerTool(createRetryExecutionTool(getClient) as AnyAgentTool);
|
|
58
64
|
api.registerTool(createDeleteExecutionTool(getClient) as AnyAgentTool);
|
|
59
65
|
api.registerTool(createDeleteExecutionsTool(getClient) as AnyAgentTool);
|
|
66
|
+
api.registerTool(createArchiveWorkflowTool(getClient) as AnyAgentTool);
|
|
67
|
+
api.registerTool(createUnarchiveWorkflowTool(getClient) as AnyAgentTool);
|
|
68
|
+
api.registerTool(
|
|
69
|
+
createDeleteWorkflowTool({
|
|
70
|
+
getClient,
|
|
71
|
+
backupDir: config.backupDir,
|
|
72
|
+
}) as AnyAgentTool,
|
|
73
|
+
);
|
|
74
|
+
api.registerTool(createCreateWorkflowTool({ getClient }) as AnyAgentTool);
|
|
60
75
|
}
|
|
61
76
|
},
|
|
62
77
|
});
|
package/openclaw.plugin.json
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"enableEdit": {
|
|
25
25
|
"type": "boolean",
|
|
26
26
|
"default": false,
|
|
27
|
-
"description": "Enable write tools (
|
|
27
|
+
"description": "Enable the full workflow + execution lifecycle write tools (create, 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. create accepts n8n_get_workflow output directly and is the restore path for delete-workflow snapshots."
|
|
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
|
|
58
|
+
"help": "Exposes all workflow + execution lifecycle write tools. Workflows: create (accepts get-workflow output directly, strips read-only fields; primary restore path), activate, deactivate, save (confirm-gated, auto-backup), archive (reversible soft-delete; preserves id), unarchive, delete-workflow (confirm-gated, snapshot-before-delete; restore via create-workflow gets a new id). 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 that preserves the id."
|
|
59
59
|
},
|
|
60
60
|
"maxExecutionLogBytes": {
|
|
61
61
|
"label": "Max Log Bytes",
|
package/package.json
CHANGED
package/src/client.ts
CHANGED
|
@@ -126,6 +126,13 @@ export class N8nClient {
|
|
|
126
126
|
return this.request<N8nWorkflow>(`/api/v1/workflows/${id}`);
|
|
127
127
|
}
|
|
128
128
|
|
|
129
|
+
async createWorkflow(body: Record<string, unknown>): Promise<N8nWorkflow> {
|
|
130
|
+
return this.request<N8nWorkflow>(`/api/v1/workflows`, {
|
|
131
|
+
method: "POST",
|
|
132
|
+
body: JSON.stringify(body),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
129
136
|
async saveWorkflow(
|
|
130
137
|
id: string,
|
|
131
138
|
body: Record<string, unknown>,
|
|
@@ -157,6 +164,33 @@ export class N8nClient {
|
|
|
157
164
|
});
|
|
158
165
|
}
|
|
159
166
|
|
|
167
|
+
async archiveWorkflow(id: string): Promise<N8nWorkflow> {
|
|
168
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
169
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
170
|
+
}
|
|
171
|
+
return this.request<N8nWorkflow>(`/api/v1/workflows/${id}/archive`, {
|
|
172
|
+
method: "POST",
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async unarchiveWorkflow(id: string): Promise<N8nWorkflow> {
|
|
177
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
178
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
179
|
+
}
|
|
180
|
+
return this.request<N8nWorkflow>(`/api/v1/workflows/${id}/unarchive`, {
|
|
181
|
+
method: "POST",
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async deleteWorkflow(id: string): Promise<N8nWorkflow> {
|
|
186
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
187
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
188
|
+
}
|
|
189
|
+
return this.request<N8nWorkflow>(`/api/v1/workflows/${id}`, {
|
|
190
|
+
method: "DELETE",
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
160
194
|
async executeWorkflow(
|
|
161
195
|
id: string,
|
|
162
196
|
payload?: Record<string, unknown>,
|
|
@@ -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,176 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import type { N8nClient, N8nWorkflow } from "../client.ts";
|
|
3
|
+
import { jsonToolResult } from "./result.ts";
|
|
4
|
+
import { validateWorkflow } from "./validate-workflow.ts";
|
|
5
|
+
|
|
6
|
+
const Schema = Type.Object(
|
|
7
|
+
{
|
|
8
|
+
definition: Type.Object(
|
|
9
|
+
{
|
|
10
|
+
name: Type.String({
|
|
11
|
+
description: "Workflow name (required). Not enforced unique by n8n.",
|
|
12
|
+
}),
|
|
13
|
+
// nodes/connections may live at the top level (flat snapshot) OR nested
|
|
14
|
+
// under `definition` (n8n_get_workflow shape) - optional at both levels.
|
|
15
|
+
nodes: Type.Optional(Type.Array(Type.Record(Type.String(), Type.Unknown()))),
|
|
16
|
+
connections: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
17
|
+
// n8n_get_workflow emits null for empty settings/staticData; accept
|
|
18
|
+
// null here and coerce at runtime. Rejecting null would block the
|
|
19
|
+
// documented direct-forward path before normalization runs.
|
|
20
|
+
settings: Type.Optional(
|
|
21
|
+
Type.Union([Type.Record(Type.String(), Type.Unknown()), Type.Null()]),
|
|
22
|
+
),
|
|
23
|
+
staticData: Type.Optional(Type.Unknown()),
|
|
24
|
+
definition: Type.Optional(
|
|
25
|
+
Type.Object(
|
|
26
|
+
{
|
|
27
|
+
nodes: Type.Optional(
|
|
28
|
+
Type.Array(Type.Record(Type.String(), Type.Unknown())),
|
|
29
|
+
),
|
|
30
|
+
connections: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
31
|
+
settings: Type.Optional(
|
|
32
|
+
Type.Union([
|
|
33
|
+
Type.Record(Type.String(), Type.Unknown()),
|
|
34
|
+
Type.Null(),
|
|
35
|
+
]),
|
|
36
|
+
),
|
|
37
|
+
staticData: Type.Optional(Type.Unknown()),
|
|
38
|
+
},
|
|
39
|
+
{ additionalProperties: true },
|
|
40
|
+
),
|
|
41
|
+
),
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
additionalProperties: true,
|
|
45
|
+
description:
|
|
46
|
+
"Workflow body to create. Accepts two shapes: (1) a flat snapshot from n8n_delete_workflow or n8n_save_workflow (nodes/connections at the top level), or (2) the output of n8n_get_workflow with includeDefinition=true (graph data nested under `definition`, empty settings/staticData may arrive as null). Read-only fields (id, active, createdAt, updatedAt, isArchived, versionId, triggerCount, tags, shared, meta, pinData) are stripped before POST; null settings/staticData are normalized.",
|
|
47
|
+
},
|
|
48
|
+
),
|
|
49
|
+
skipValidation: Type.Optional(
|
|
50
|
+
Type.Boolean({
|
|
51
|
+
description:
|
|
52
|
+
"Skip the n8n_validate_workflow pre-check. Default false. Validation errors (not warnings) block the create by default.",
|
|
53
|
+
}),
|
|
54
|
+
),
|
|
55
|
+
},
|
|
56
|
+
{ additionalProperties: false },
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
export interface CreateWorkflowDeps {
|
|
60
|
+
getClient: () => N8nClient;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const READ_ONLY_FIELDS = [
|
|
64
|
+
"id",
|
|
65
|
+
"active",
|
|
66
|
+
"createdAt",
|
|
67
|
+
"updatedAt",
|
|
68
|
+
"isArchived",
|
|
69
|
+
"versionId",
|
|
70
|
+
"triggerCount",
|
|
71
|
+
"tags",
|
|
72
|
+
"shared",
|
|
73
|
+
"meta",
|
|
74
|
+
"pinData",
|
|
75
|
+
] as const;
|
|
76
|
+
|
|
77
|
+
export function createCreateWorkflowTool(deps: CreateWorkflowDeps) {
|
|
78
|
+
return {
|
|
79
|
+
name: "n8n_create_workflow",
|
|
80
|
+
label: "n8n: create workflow",
|
|
81
|
+
description:
|
|
82
|
+
"Create a new n8n workflow via POST /workflows. Accepts the output of n8n_get_workflow (includeDefinition=true) directly: read-only fields (id, active, createdAt, etc.) are stripped before POST. The new workflow is created INACTIVE; call n8n_activate afterwards if you want triggers running. Runs n8n_validate_workflow as a pre-check by default (errors block, warnings pass through); pass skipValidation:true to bypass. Primary restore path for n8n_delete_workflow snapshots. Requires enableEdit.",
|
|
83
|
+
parameters: Schema,
|
|
84
|
+
execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
|
|
85
|
+
const params = rawParams as {
|
|
86
|
+
definition: Record<string, unknown>;
|
|
87
|
+
skipValidation?: boolean;
|
|
88
|
+
};
|
|
89
|
+
const client = deps.getClient();
|
|
90
|
+
|
|
91
|
+
const body = buildCreateBody(params.definition);
|
|
92
|
+
|
|
93
|
+
if (!params.skipValidation) {
|
|
94
|
+
const proposed: N8nWorkflow = {
|
|
95
|
+
id: "__pending__",
|
|
96
|
+
name: String(body.name ?? ""),
|
|
97
|
+
active: false,
|
|
98
|
+
createdAt: "",
|
|
99
|
+
updatedAt: "",
|
|
100
|
+
nodes: (body.nodes as unknown[]) ?? [],
|
|
101
|
+
connections: (body.connections as Record<string, unknown>) ?? {},
|
|
102
|
+
settings: (body.settings as Record<string, unknown>) ?? {},
|
|
103
|
+
};
|
|
104
|
+
const issues = validateWorkflow(proposed);
|
|
105
|
+
const errors = issues.filter((i) => i.severity === "error");
|
|
106
|
+
if (errors.length > 0) {
|
|
107
|
+
return jsonToolResult({
|
|
108
|
+
ok: false,
|
|
109
|
+
error: "validation failed; create aborted",
|
|
110
|
+
issues,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
const created = await client.createWorkflow(body);
|
|
117
|
+
return jsonToolResult({
|
|
118
|
+
ok: true,
|
|
119
|
+
action: "create",
|
|
120
|
+
workflowId: created.id,
|
|
121
|
+
workflowName: created.name,
|
|
122
|
+
active: created.active ?? false,
|
|
123
|
+
createdAt: created.createdAt ?? null,
|
|
124
|
+
updatedAt: created.updatedAt ?? null,
|
|
125
|
+
hint: "Workflow is created inactive. Call n8n_activate to start its triggers.",
|
|
126
|
+
});
|
|
127
|
+
} catch (err) {
|
|
128
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
129
|
+
return jsonToolResult({
|
|
130
|
+
ok: false,
|
|
131
|
+
error: `create failed: ${msg}`,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function buildCreateBody(
|
|
139
|
+
proposed: Record<string, unknown>,
|
|
140
|
+
): Record<string, unknown> {
|
|
141
|
+
// Accept two input shapes:
|
|
142
|
+
// 1. Flat N8nWorkflow (from n8n_delete_workflow / save_workflow backup files,
|
|
143
|
+
// or client.getWorkflow raw). Fields at top level.
|
|
144
|
+
// 2. n8n_get_workflow(includeDefinition=true) output, where graph data is
|
|
145
|
+
// nested under `definition`. Flatten it by merging definition fields.
|
|
146
|
+
const flat: Record<string, unknown> = { ...proposed };
|
|
147
|
+
const def = flat.definition;
|
|
148
|
+
if (def && typeof def === "object" && !Array.isArray(def)) {
|
|
149
|
+
Object.assign(flat, def as Record<string, unknown>);
|
|
150
|
+
}
|
|
151
|
+
delete flat.definition;
|
|
152
|
+
|
|
153
|
+
// n8n's Public API enforces additionalProperties:false on the workflow
|
|
154
|
+
// schema; any read-only or unknown field triggers a 400.
|
|
155
|
+
for (const field of READ_ONLY_FIELDS) {
|
|
156
|
+
delete flat[field];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// settings is required server-side; n8n_get_workflow emits null for empty
|
|
160
|
+
// settings, so normalize null → {}.
|
|
161
|
+
const settings =
|
|
162
|
+
flat.settings === null || flat.settings === undefined
|
|
163
|
+
? {}
|
|
164
|
+
: (flat.settings as Record<string, unknown>);
|
|
165
|
+
|
|
166
|
+
const body: Record<string, unknown> = {
|
|
167
|
+
name: flat.name,
|
|
168
|
+
nodes: flat.nodes ?? [],
|
|
169
|
+
connections: flat.connections ?? {},
|
|
170
|
+
settings,
|
|
171
|
+
};
|
|
172
|
+
if (flat.staticData !== undefined && flat.staticData !== null) {
|
|
173
|
+
body.staticData = flat.staticData;
|
|
174
|
+
}
|
|
175
|
+
return body;
|
|
176
|
+
}
|
|
@@ -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 is written to backupDir before the DELETE fires. The deleted workflow is gone from n8n; restore by calling n8n_create_workflow with the snapshot (see restoreHint). The restored workflow gets a new id. Prefer n8n_archive_workflow for reversible cleanup that preserves the id.",
|
|
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}. To restore: call n8n_create_workflow with definition=<contents of ${backupPath}>. Read-only fields are stripped server-side; the restored workflow gets a new id and starts inactive (call n8n_activate to re-enable triggers).`,
|
|
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
|
+
}
|