n8n-ops-mcp 0.7.0 → 0.8.1

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
@@ -4,15 +4,15 @@
4
4
  [![license](https://img.shields.io/npm/l/n8n-ops-mcp.svg)](./LICENSE)
5
5
  [![MCP](https://img.shields.io/badge/MCP-compatible-blue)](https://modelcontextprotocol.io)
6
6
 
7
- Ops-focused n8n tools for Claude-compatible clients. List, inspect, trigger, validate, and safely edit n8n workflows from any MCP host — with first-class [OpenClaw](https://github.com/openclaw/openclaw) support.
7
+ Ops-focused n8n tools for any MCP-compatible client. List, inspect, trigger, validate, and safely edit n8n workflows - with auto-backup and confirm gates on destructive writes.
8
8
 
9
- Works with Claude Desktop, Claude Code, OpenClaw, Hermes Agent, Codex CLI, and any other MCP-compatible client.
9
+ Built for [OpenClaw](https://github.com/openclaw/openclaw) as a first-class plugin, exposed as an MCP server for everyone else. Works with Claude Desktop, Claude Code, Codex CLI, Hermes Agent, Cursor, Windsurf, or any other MCP host. No hard dependency on a specific model or agent harness.
10
10
 
11
11
  ## Why
12
12
 
13
- Your AI agent has no native awareness of your n8n footprint. With this package, it can answer "what's broken in my n8n?" and trigger workflows from chat without you leaving your client.
13
+ Your agent has no native awareness of your n8n footprint. With this package, it can answer "what's broken in my n8n?", trigger workflows from chat, or clean up old executions without you leaving your client.
14
14
 
15
- For a catalog/docs tool that indexes n8n's node library, see [n8n-mcp](https://www.npmjs.com/package/n8n-mcp). This one is ops-focused — list, trigger, validate, edit.
15
+ For a catalog/docs tool that indexes n8n's node library, see [n8n-mcp](https://www.npmjs.com/package/n8n-mcp). This one is ops-focused - list, trigger, validate, edit.
16
16
 
17
17
  ## Tools
18
18
 
@@ -26,12 +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 | ✓ |
32
- | `n8n_archive_workflow` | Soft-delete a workflow (reversible; prefer over delete) | ✓ |
33
+ | `n8n_archive_workflow` | Soft-delete a workflow (reversible; preserves id) | ✓ |
33
34
  | `n8n_unarchive_workflow` | Restore an archived workflow (does NOT reactivate) | ✓ |
34
- | `n8n_delete_workflow` | Permanently delete a workflow (confirm-gated, snapshot-before-delete) | ✓ |
35
+ | `n8n_delete_workflow` | Permanently delete a workflow (confirm-gated, snapshot-before-delete, restore via `n8n_create_workflow`) | ✓ |
35
36
  | `n8n_cancel_execution` | Stop a running or waiting execution by id | ✓ |
36
37
  | `n8n_retry_execution` | Retry a failed execution by id (returns a new execution) | ✓ |
37
38
  | `n8n_delete_execution` | Permanently delete an execution record (confirm-gated, irreversible) | ✓ |
@@ -42,41 +43,43 @@ Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
42
43
  <details>
43
44
  <summary><b>Detailed tool reference</b></summary>
44
45
 
45
- **`n8n_list_workflows`** — filter by `active`, `tags`, `name` (substring), `limit`. Returns id, name, active state, tags, updatedAt.
46
+ **`n8n_list_workflows`** - filter by `active`, `tags`, `name` (substring), `limit`. Returns id, name, active state, tags, updatedAt.
46
47
 
47
- **`n8n_get_workflow`** — fetch one by id. Returns metadata by default. Pass `includeDefinition: true` for the full node graph + connections.
48
+ **`n8n_get_workflow`** - fetch one by id. Returns metadata by default. Pass `includeDefinition: true` for the full node graph + connections.
48
49
 
49
- **`n8n_list_executions`** — filter by `workflowId`, `status` (success/error/running/waiting/canceled), `limit`. Returns id, workflowId, workflowName, status, mode, startedAt, stoppedAt.
50
+ **`n8n_list_executions`** - filter by `workflowId`, `status` (success/error/running/waiting/canceled), `limit`. Returns id, workflowId, workflowName, status, mode, startedAt, stoppedAt.
50
51
 
51
- **`n8n_get_execution`** — includes per-node run log (truncated to `maxExecutionLogBytes`, default 64 KB) and the raw error object verbatim when status is `error`. Pass `includeRunData: false` to skip the run log.
52
+ **`n8n_get_execution`** - includes per-node run log (truncated to `maxExecutionLogBytes`, default 64 KB) and the raw error object verbatim when status is `error`. Pass `includeRunData: false` to skip the run log.
52
53
 
53
- **`n8n_search_executions`** — defaults to scanning `status=error` executions for a `query` fragment (e.g. `ECONNREFUSED`) and returning matches with workflow context + a snippet around each hit. `scope: "error"` (default) greps the error payload only; `scope: "all"` also greps full per-node run data (slower, may return node outputs — treat snippets as sensitive). Optional `workflowId`, `status`, `limit` (default 50, max 250), `maxMatches` (default 20), `snippetChars` (default 160). Returns `matches` plus a `skipped` array for any execution that failed to fetch.
54
+ **`n8n_search_executions`** - defaults to scanning `status=error` executions for a `query` fragment (e.g. `ECONNREFUSED`) and returning matches with workflow context + a snippet around each hit. `scope: "error"` (default) greps the error payload only; `scope: "all"` also greps full per-node run data (slower, may return node outputs - treat snippets as sensitive). Optional `workflowId`, `status`, `limit` (default 50, max 250), `maxMatches` (default 20), `snippetChars` (default 160). Returns `matches` plus a `skipped` array for any execution that failed to fetch.
54
55
 
55
- **`n8n_list_webhooks`** — scans workflows for webhook and form-trigger nodes and returns their paths + fully-formed `triggerUrl`. Pairs with `n8n_trigger` mode='webhook'. Optional `workflowId`, `activeOnly` (default true), `limit` (default 50).
56
+ **`n8n_list_webhooks`** - scans workflows for webhook and form-trigger nodes and returns their paths + fully-formed `triggerUrl`. Pairs with `n8n_trigger` mode='webhook'. Optional `workflowId`, `activeOnly` (default true), `limit` (default 50).
56
57
 
57
- **`n8n_validate_workflow`** — checks for deprecated node types (function → code), legacy Code-node API (`$node[]`, `items` global, `require()`), orphan nodes, disabled nodes, missing trigger. Returns issues with severity (error/warning/info) plus a summary count.
58
+ **`n8n_validate_workflow`** - checks for deprecated node types (function → code), legacy Code-node API (`$node[]`, `items` global, `require()`), orphan nodes, disabled nodes, missing trigger. Returns issues with severity (error/warning/info) plus a summary count.
58
59
 
59
- **`n8n_trigger`** — two modes:
60
- - `mode: "webhook"` + `webhookPath` — POST (or GET/PUT/DELETE) to the configured base URL + path, with an optional JSON `payload`. This is the reliable path.
61
- - `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.
60
+ **`n8n_trigger`** - two modes:
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.
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.
62
63
 
63
- **`n8n_activate`** / **`n8n_deactivate`** — idempotent. Deactivating does not cancel running executions.
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.
64
65
 
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
+ **`n8n_activate`** / **`n8n_deactivate`** - idempotent. Deactivating does not cancel running executions.
66
67
 
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
+ **`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`.
68
69
 
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
+ **`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.
70
71
 
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.
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.
72
73
 
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).
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.
74
75
 
75
- **`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.
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).
76
77
 
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.
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.
78
79
 
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
+ **`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.
81
+
82
+ **`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
83
 
81
84
  </details>
82
85
 
@@ -92,13 +95,31 @@ Generate an API key in n8n under **Settings → API**, then set these env vars i
92
95
 
93
96
  | Variable | Required | Default | Description |
94
97
  |---|---|---|---|
95
- | `N8N_BASE_URL` | yes | — | n8n base URL, e.g. `http://localhost:5678` |
96
- | `N8N_API_KEY` | yes | — | n8n Public API key (`X-N8N-API-KEY`) |
98
+ | `N8N_BASE_URL` | yes | - | n8n base URL, e.g. `http://localhost:5678` |
99
+ | `N8N_API_KEY` | yes | - | n8n Public API key (`X-N8N-API-KEY`) |
97
100
  | `N8N_ENABLE_EDIT` | no | `false` | Expose write tools |
98
101
  | `N8N_BACKUP_DIR` | no | `~/.n8n-backups` | Where `n8n_save_workflow` writes pre-save snapshots |
99
102
  | `N8N_MAX_EXECUTION_LOG_BYTES` | no | `65536` | Cap on inline execution log bytes |
100
103
  | `N8N_REQUEST_TIMEOUT_MS` | no | `15000` | HTTP timeout for n8n API calls |
101
104
 
105
+ ### Claude Desktop
106
+
107
+ Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
108
+
109
+ ```json
110
+ {
111
+ "mcpServers": {
112
+ "n8n": {
113
+ "command": "n8n-ops-mcp",
114
+ "env": {
115
+ "N8N_BASE_URL": "http://localhost:5678",
116
+ "N8N_API_KEY": "your-api-key-here"
117
+ }
118
+ }
119
+ }
120
+ }
121
+ ```
122
+
102
123
  ### Claude Code
103
124
 
104
125
  ```bash
@@ -110,9 +131,46 @@ claude mcp add n8n \
110
131
 
111
132
  Add `--scope user` to make it available from any directory instead of only the current project.
112
133
 
113
- ### OpenClaw
134
+ ### Codex CLI
135
+
136
+ ```bash
137
+ codex mcp add n8n \
138
+ --env N8N_BASE_URL=http://localhost:5678 \
139
+ --env N8N_API_KEY=your-api-key-here \
140
+ -- n8n-ops-mcp
141
+ ```
142
+
143
+ Writes the entry to `~/.codex/config.toml` under `[mcp_servers.n8n]`. Verify with `codex mcp list`.
144
+
145
+ ### Cursor / Windsurf / other MCP hosts
146
+
147
+ Any MCP-compatible client that accepts a stdio command + env will work. Point it at the `n8n-ops-mcp` binary with `N8N_BASE_URL` and `N8N_API_KEY` in the environment.
114
148
 
115
- n8n-ops-mcp is a first-class OpenClaw plugin — not an MCP bridge — so it shares the gateway's process, auth profiles, and hooks.
149
+ <details>
150
+ <summary><b>Hermes Agent</b></summary>
151
+
152
+ [Hermes Agent](https://github.com/NousResearch/hermes-agent) reads MCP config from `~/.hermes/config.yaml`:
153
+
154
+ ```yaml
155
+ mcp_servers:
156
+ n8n:
157
+ command: "n8n-ops-mcp"
158
+ env:
159
+ N8N_BASE_URL: "http://localhost:5678"
160
+ N8N_API_KEY: "your-api-key-here"
161
+ ```
162
+
163
+ Then reload from inside a session:
164
+
165
+ ```
166
+ /reload-mcp
167
+ ```
168
+
169
+ </details>
170
+
171
+ ### OpenClaw (first-class plugin)
172
+
173
+ n8n-ops-mcp was built for OpenClaw and ships as a first-class plugin - not an MCP bridge - so it shares the gateway's process, auth profiles, and hooks.
116
174
 
117
175
  ```bash
118
176
  openclaw plugins install clawhub:n8n-ops-mcp
@@ -152,57 +210,7 @@ systemctl --user restart openclaw-gateway
152
210
  Config keys: `baseUrl`, `apiKey`, `apiKeyEnv`, `enableEdit`, `maxExecutionLogBytes`, `requestTimeoutMs`, `backupDir`. See [`openclaw.plugin.json`](./openclaw.plugin.json) for the full schema.
153
211
 
154
212
  <details>
155
- <summary><b>Other clients</b> — Claude Desktop, Hermes Agent, Codex CLI, manual OpenClaw install</summary>
156
-
157
- ### Claude Desktop
158
-
159
- Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
160
-
161
- ```json
162
- {
163
- "mcpServers": {
164
- "n8n": {
165
- "command": "n8n-ops-mcp",
166
- "env": {
167
- "N8N_BASE_URL": "http://localhost:5678",
168
- "N8N_API_KEY": "your-api-key-here"
169
- }
170
- }
171
- }
172
- }
173
- ```
174
-
175
- ### Hermes Agent
176
-
177
- [Hermes Agent](https://github.com/NousResearch/hermes-agent) reads MCP config from `~/.hermes/config.yaml`:
178
-
179
- ```yaml
180
- mcp_servers:
181
- n8n:
182
- command: "n8n-ops-mcp"
183
- env:
184
- N8N_BASE_URL: "http://localhost:5678"
185
- N8N_API_KEY: "your-api-key-here"
186
- ```
187
-
188
- Then reload from inside a session:
189
-
190
- ```
191
- /reload-mcp
192
- ```
193
-
194
- ### Codex CLI
195
-
196
- ```bash
197
- codex mcp add n8n \
198
- --env N8N_BASE_URL=http://localhost:5678 \
199
- --env N8N_API_KEY=your-api-key-here \
200
- -- n8n-ops-mcp
201
- ```
202
-
203
- Writes the entry to `~/.codex/config.toml` under `[mcp_servers.n8n]`. Verify with `codex mcp list`.
204
-
205
- ### OpenClaw — manual (non-ClawHub) install
213
+ <summary><b>OpenClaw - manual (non-ClawHub) install</b></summary>
206
214
 
207
215
  If you want to point OpenClaw at a local clone instead of the registry:
208
216
 
@@ -262,13 +270,21 @@ Calls `n8n_search_executions` to find the failed id, then `n8n_retry_execution`
262
270
 
263
271
  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
272
 
265
- > Archive the old "staging-bot" workflow — I might need it back someday *(requires `N8N_ENABLE_EDIT=true`)*
273
+ > Archive the old "staging-bot" workflow - I might need it back someday *(requires `N8N_ENABLE_EDIT=true`)*
266
274
 
267
275
  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
276
 
269
- > Delete the abandoned "poc-scraper" workflow — it's been dead for months *(requires `N8N_ENABLE_EDIT=true`)*
277
+ > Delete the abandoned "poc-scraper" workflow - it's been dead for months *(requires `N8N_ENABLE_EDIT=true`)*
270
278
 
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.
279
+ 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.
280
+
281
+ > 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`)*
282
+
283
+ 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.
284
+
285
+ > Clone workflow "intel-nightly" to "intel-nightly-staging" for testing *(requires `N8N_ENABLE_EDIT=true`)*
286
+
287
+ 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.
272
288
 
273
289
  ## Development
274
290
 
@@ -290,6 +306,10 @@ npm install
290
306
  npm run build
291
307
  ```
292
308
 
309
+ ## Changelog
310
+
311
+ See [CHANGELOG.md](./CHANGELOG.md) for the full version history.
312
+
293
313
  ## License
294
314
 
295
315
  MIT
@@ -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}`);
@@ -1733,7 +1739,7 @@ var Schema17 = Type17.Object(
1733
1739
  {
1734
1740
  id: Type17.String({ description: "Workflow id to delete (from n8n_list_workflows)." }),
1735
1741
  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."
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."
1737
1743
  })
1738
1744
  },
1739
1745
  { additionalProperties: false }
@@ -1792,7 +1798,7 @@ function createDeleteWorkflowTool(deps) {
1792
1798
  workflowId: deleted.id ?? id,
1793
1799
  workflowName: deleted.name ?? current.name,
1794
1800
  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.`
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).`
1796
1802
  });
1797
1803
  } catch (err) {
1798
1804
  if (err instanceof N8nApiError && err.status === 404) {
@@ -1831,8 +1837,149 @@ async function writeBackup2(dir, wf) {
1831
1837
  return file;
1832
1838
  }
1833
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
+
1834
1981
  // mcp-server.ts
1835
- var VERSION = "0.7.0";
1982
+ var VERSION = "0.8.0";
1836
1983
  function readConfigFromEnv() {
1837
1984
  const baseUrl = (process.env.N8N_BASE_URL ?? "").trim();
1838
1985
  if (!baseUrl) {
@@ -2030,10 +2177,22 @@ async function main() {
2030
2177
  {
2031
2178
  id: z.string().describe("Workflow id to delete (from n8n_list_workflows)."),
2032
2179
  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."
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."
2034
2181
  )
2035
2182
  }
2036
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.")
2195
+ });
2037
2196
  }
2038
2197
  const transport = new StdioServerTransport();
2039
2198
  await server.connect(transport);
package/index.ts CHANGED
@@ -21,12 +21,13 @@ import {
21
21
  createUnarchiveWorkflowTool,
22
22
  } from "./src/tools/archive-workflow.ts";
23
23
  import { createDeleteWorkflowTool } from "./src/tools/delete-workflow.ts";
24
+ import { createCreateWorkflowTool } from "./src/tools/create-workflow.ts";
24
25
 
25
26
  export default definePluginEntry({
26
27
  id: "n8n",
27
28
  name: "n8n Ops",
28
29
  description:
29
- "List, inspect, and trigger n8n workflows from OpenClaw agents. Optional edit tools behind a flag with auto-backup and rollback on failure.",
30
+ "Ops-focused n8n tools for OpenClaw agents: list, inspect, trigger, validate, plus full workflow + execution lifecycle (create, save, archive, delete, cancel, retry) behind an edit flag. Auto-backup + confirm gates on destructive writes.",
30
31
  register(api) {
31
32
  if (api.registrationMode !== "full") return;
32
33
 
@@ -70,6 +71,7 @@ export default definePluginEntry({
70
71
  backupDir: config.backupDir,
71
72
  }) as AnyAgentTool,
72
73
  );
74
+ api.registerTool(createCreateWorkflowTool({ getClient }) as AnyAgentTool);
73
75
  }
74
76
  },
75
77
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "n8n",
3
3
  "name": "n8n Ops",
4
- "description": "List, inspect, and trigger n8n workflows from OpenClaw agents. Optional edit tools behind a flag with auto-backup and rollback on failure.",
4
+ "description": "Ops-focused n8n tools for OpenClaw agents: list, inspect, trigger, validate, plus full workflow + execution lifecycle (create, save, archive, delete, cancel, retry) behind an edit flag. Auto-backup + confirm gates on destructive writes.",
5
5
  "configSchema": {
6
6
  "type": "object",
7
7
  "additionalProperties": false,
@@ -10,7 +10,7 @@
10
10
  "baseUrl": {
11
11
  "type": "string",
12
12
  "format": "uri",
13
- "description": "Base URL of the n8n instance, e.g. http://192.168.4.89:5678"
13
+ "description": "Base URL of the n8n instance, e.g. http://n8n.example.internal:5678"
14
14
  },
15
15
  "apiKey": {
16
16
  "type": "string",
@@ -24,7 +24,7 @@
24
24
  "enableEdit": {
25
25
  "type": "boolean",
26
26
  "default": false,
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."
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 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."
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
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "n8n-ops-mcp",
3
- "version": "0.7.0",
4
- "description": "Ops-focused n8n tools (list, inspect, trigger, validate, save) for Claude-compatible clients. MCP server + first-class OpenClaw plugin.",
3
+ "version": "0.8.1",
4
+ "description": "Ops-focused n8n tools for any MCP-compatible client: list, inspect, trigger, validate, plus full workflow + execution lifecycle (create, save, archive, delete, cancel, retry). MCP server + first-class OpenClaw plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Solomon Neas <srneas@gmail.com>",
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>,
@@ -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
+ }
@@ -10,7 +10,7 @@ const Schema = Type.Object(
10
10
  id: Type.String({ description: "Workflow id to delete (from n8n_list_workflows)." }),
11
11
  confirm: Type.Boolean({
12
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.",
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
14
  }),
15
15
  },
16
16
  { additionalProperties: false },
@@ -81,7 +81,7 @@ export function createDeleteWorkflowTool(deps: DeleteWorkflowDeps) {
81
81
  workflowId: deleted.id ?? id,
82
82
  workflowName: deleted.name ?? current.name,
83
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.`,
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
85
  });
86
86
  } catch (err) {
87
87
  if (err instanceof N8nApiError && err.status === 404) {