n8n-ops-mcp 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +225 -0
- package/dist/mcp-server.js +1241 -0
- package/index.ts +60 -0
- package/openclaw.plugin.json +74 -0
- package/package.json +61 -0
- package/src/client.ts +272 -0
- package/src/config.ts +54 -0
- package/src/tools/activate.ts +32 -0
- package/src/tools/deactivate.ts +32 -0
- package/src/tools/get-execution.ts +86 -0
- package/src/tools/get-workflow.ts +67 -0
- package/src/tools/list-executions.ts +100 -0
- package/src/tools/list-webhooks.ts +145 -0
- package/src/tools/list-workflows.ts +68 -0
- package/src/tools/result.ts +9 -0
- package/src/tools/save-workflow.ts +159 -0
- package/src/tools/trigger.ts +185 -0
- package/src/tools/validate-workflow.ts +214 -0
|
@@ -0,0 +1,1241 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// mcp-server.ts
|
|
4
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
|
|
8
|
+
// src/client.ts
|
|
9
|
+
var N8nApiError = class extends Error {
|
|
10
|
+
constructor(status, path2, message) {
|
|
11
|
+
super(`n8n ${status} on ${path2}: ${message}`);
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.path = path2;
|
|
14
|
+
this.name = "N8nApiError";
|
|
15
|
+
}
|
|
16
|
+
status;
|
|
17
|
+
path;
|
|
18
|
+
};
|
|
19
|
+
var N8nClient = class {
|
|
20
|
+
baseUrl;
|
|
21
|
+
apiKey;
|
|
22
|
+
timeoutMs;
|
|
23
|
+
constructor(opts) {
|
|
24
|
+
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
25
|
+
this.apiKey = opts.apiKey;
|
|
26
|
+
this.timeoutMs = opts.timeoutMs ?? 15e3;
|
|
27
|
+
}
|
|
28
|
+
async listWorkflows(params = {}) {
|
|
29
|
+
const qs = new URLSearchParams();
|
|
30
|
+
if (params.active !== void 0) qs.set("active", String(params.active));
|
|
31
|
+
if (params.tags) qs.set("tags", params.tags);
|
|
32
|
+
if (params.name) qs.set("name", params.name);
|
|
33
|
+
if (params.limit) qs.set("limit", String(params.limit));
|
|
34
|
+
if (params.cursor) qs.set("cursor", params.cursor);
|
|
35
|
+
return this.request(
|
|
36
|
+
`/api/v1/workflows${qs.toString() ? `?${qs}` : ""}`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
async getWorkflow(id) {
|
|
40
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
41
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
42
|
+
}
|
|
43
|
+
return this.request(`/api/v1/workflows/${id}`);
|
|
44
|
+
}
|
|
45
|
+
async saveWorkflow(id, body) {
|
|
46
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
47
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
48
|
+
}
|
|
49
|
+
return this.request(`/api/v1/workflows/${id}`, {
|
|
50
|
+
method: "PUT",
|
|
51
|
+
body: JSON.stringify(body)
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
async activateWorkflow(id) {
|
|
55
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
56
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
57
|
+
}
|
|
58
|
+
return this.request(`/api/v1/workflows/${id}/activate`, {
|
|
59
|
+
method: "POST"
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
async deactivateWorkflow(id) {
|
|
63
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
64
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
65
|
+
}
|
|
66
|
+
return this.request(`/api/v1/workflows/${id}/deactivate`, {
|
|
67
|
+
method: "POST"
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
async executeWorkflow(id, payload) {
|
|
71
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
72
|
+
throw new Error(`Invalid workflow id: ${id}`);
|
|
73
|
+
}
|
|
74
|
+
return this.request(`/api/v1/workflows/${id}/execute`, {
|
|
75
|
+
method: "POST",
|
|
76
|
+
body: JSON.stringify(payload ?? {})
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
async postWebhook(webhookPath, payload, opts = {}) {
|
|
80
|
+
const path2 = webhookPath.startsWith("/") ? webhookPath : `/${webhookPath}`;
|
|
81
|
+
const url = `${this.baseUrl}${path2}`;
|
|
82
|
+
const method = (opts.method ?? "POST").toUpperCase();
|
|
83
|
+
const controller = new AbortController();
|
|
84
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
85
|
+
try {
|
|
86
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
87
|
+
const res = await fetch(url, {
|
|
88
|
+
method,
|
|
89
|
+
headers: {
|
|
90
|
+
Accept: "application/json",
|
|
91
|
+
...hasBody ? { "Content-Type": "application/json" } : {}
|
|
92
|
+
},
|
|
93
|
+
body: hasBody ? JSON.stringify(payload ?? {}) : void 0,
|
|
94
|
+
signal: controller.signal
|
|
95
|
+
});
|
|
96
|
+
const text = await res.text();
|
|
97
|
+
let body = text;
|
|
98
|
+
if (text) {
|
|
99
|
+
try {
|
|
100
|
+
body = JSON.parse(text);
|
|
101
|
+
} catch {
|
|
102
|
+
body = text;
|
|
103
|
+
}
|
|
104
|
+
} else {
|
|
105
|
+
body = null;
|
|
106
|
+
}
|
|
107
|
+
return { status: res.status, body };
|
|
108
|
+
} catch (err) {
|
|
109
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
110
|
+
throw new Error(`n8n webhook to ${path2} failed: ${redactKey(msg, this.apiKey)}`);
|
|
111
|
+
} finally {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async getExecution(id, opts = {}) {
|
|
116
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
|
117
|
+
throw new Error(`Invalid execution id: ${id}`);
|
|
118
|
+
}
|
|
119
|
+
const qs = new URLSearchParams();
|
|
120
|
+
if (opts.includeData) qs.set("includeData", "true");
|
|
121
|
+
return this.request(
|
|
122
|
+
`/api/v1/executions/${id}${qs.toString() ? `?${qs}` : ""}`
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
async listExecutions(params = {}) {
|
|
126
|
+
const qs = new URLSearchParams();
|
|
127
|
+
if (params.workflowId) qs.set("workflowId", params.workflowId);
|
|
128
|
+
if (params.status) qs.set("status", params.status);
|
|
129
|
+
if (params.limit) qs.set("limit", String(params.limit));
|
|
130
|
+
if (params.cursor) qs.set("cursor", params.cursor);
|
|
131
|
+
if (params.includeData) qs.set("includeData", "true");
|
|
132
|
+
return this.request(
|
|
133
|
+
`/api/v1/executions${qs.toString() ? `?${qs}` : ""}`
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
async request(path2, init = {}) {
|
|
137
|
+
const url = `${this.baseUrl}${path2}`;
|
|
138
|
+
const controller = new AbortController();
|
|
139
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
140
|
+
try {
|
|
141
|
+
const res = await fetch(url, {
|
|
142
|
+
...init,
|
|
143
|
+
headers: {
|
|
144
|
+
"X-N8N-API-KEY": this.apiKey,
|
|
145
|
+
"Accept": "application/json",
|
|
146
|
+
...init.body ? { "Content-Type": "application/json" } : {},
|
|
147
|
+
...init.headers ?? {}
|
|
148
|
+
},
|
|
149
|
+
signal: controller.signal
|
|
150
|
+
});
|
|
151
|
+
const text = await res.text();
|
|
152
|
+
if (!res.ok) {
|
|
153
|
+
throw new N8nApiError(res.status, path2, redactKey(text, this.apiKey));
|
|
154
|
+
}
|
|
155
|
+
if (!text) return {};
|
|
156
|
+
return JSON.parse(text);
|
|
157
|
+
} catch (err) {
|
|
158
|
+
if (err instanceof N8nApiError) throw err;
|
|
159
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
160
|
+
throw new Error(`n8n request to ${path2} failed: ${redactKey(msg, this.apiKey)}`);
|
|
161
|
+
} finally {
|
|
162
|
+
clearTimeout(timer);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
function redactKey(text, apiKey) {
|
|
167
|
+
if (!apiKey) return text;
|
|
168
|
+
return text.split(apiKey).join("***REDACTED***");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/config.ts
|
|
172
|
+
function resolveApiKey(config) {
|
|
173
|
+
if (config.apiKeyInline) return config.apiKeyInline;
|
|
174
|
+
const fromEnv = (process.env[config.apiKeyEnv] ?? "").trim();
|
|
175
|
+
if (!fromEnv) {
|
|
176
|
+
throw new Error(
|
|
177
|
+
`openclaw-n8n: apiKey is empty and env var ${config.apiKeyEnv} is not set`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return fromEnv;
|
|
181
|
+
}
|
|
182
|
+
function makeClient(config) {
|
|
183
|
+
return new N8nClient({
|
|
184
|
+
baseUrl: config.baseUrl,
|
|
185
|
+
apiKey: resolveApiKey(config),
|
|
186
|
+
timeoutMs: config.requestTimeoutMs
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/tools/list-workflows.ts
|
|
191
|
+
import { Type } from "@sinclair/typebox";
|
|
192
|
+
|
|
193
|
+
// src/tools/result.ts
|
|
194
|
+
function jsonToolResult(details) {
|
|
195
|
+
return {
|
|
196
|
+
content: [{ type: "text", text: JSON.stringify(details, null, 2) }],
|
|
197
|
+
details
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// src/tools/list-workflows.ts
|
|
202
|
+
var Schema = Type.Object(
|
|
203
|
+
{
|
|
204
|
+
active: Type.Optional(
|
|
205
|
+
Type.Boolean({ description: "Filter by active state. Omit for all." })
|
|
206
|
+
),
|
|
207
|
+
tags: Type.Optional(
|
|
208
|
+
Type.String({ description: "Comma-separated tag names to filter by." })
|
|
209
|
+
),
|
|
210
|
+
name: Type.Optional(
|
|
211
|
+
Type.String({ description: "Case-insensitive substring match on workflow name." })
|
|
212
|
+
),
|
|
213
|
+
limit: Type.Optional(
|
|
214
|
+
Type.Number({ minimum: 1, maximum: 250, description: "Max rows (default 100)." })
|
|
215
|
+
)
|
|
216
|
+
},
|
|
217
|
+
{ additionalProperties: false }
|
|
218
|
+
);
|
|
219
|
+
function createListWorkflowsTool(getClient) {
|
|
220
|
+
return {
|
|
221
|
+
name: "n8n_list_workflows",
|
|
222
|
+
label: "n8n: list workflows",
|
|
223
|
+
description: "List n8n workflows with optional filters. Returns id, name, active state, tags, updatedAt. Use n8n_get_workflow to pull the full definition.",
|
|
224
|
+
parameters: Schema,
|
|
225
|
+
execute: async (_toolCallId, rawParams) => {
|
|
226
|
+
const params = rawParams;
|
|
227
|
+
const res = await getClient().listWorkflows({
|
|
228
|
+
active: params.active,
|
|
229
|
+
tags: params.tags,
|
|
230
|
+
limit: params.limit ?? 100
|
|
231
|
+
});
|
|
232
|
+
const rows = res.data.filter((w) => matchName(w, params.name)).map(summaryRow);
|
|
233
|
+
return jsonToolResult({
|
|
234
|
+
count: rows.length,
|
|
235
|
+
workflows: rows,
|
|
236
|
+
nextCursor: res.nextCursor ?? null
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function matchName(w, q) {
|
|
242
|
+
if (!q) return true;
|
|
243
|
+
return w.name.toLowerCase().includes(q.toLowerCase());
|
|
244
|
+
}
|
|
245
|
+
function summaryRow(w) {
|
|
246
|
+
return {
|
|
247
|
+
id: w.id,
|
|
248
|
+
name: w.name,
|
|
249
|
+
active: w.active,
|
|
250
|
+
archived: w.isArchived === true,
|
|
251
|
+
tags: (w.tags ?? []).map((t) => t.name),
|
|
252
|
+
updatedAt: w.updatedAt
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// src/tools/get-workflow.ts
|
|
257
|
+
import { Type as Type2 } from "@sinclair/typebox";
|
|
258
|
+
var Schema2 = Type2.Object(
|
|
259
|
+
{
|
|
260
|
+
id: Type2.String({ description: "Workflow id (from n8n_list_workflows)." }),
|
|
261
|
+
includeDefinition: Type2.Optional(
|
|
262
|
+
Type2.Boolean({
|
|
263
|
+
description: "Include full nodes+connections JSON. Off by default to keep responses small. Turn on when you need to inspect or edit the workflow."
|
|
264
|
+
})
|
|
265
|
+
)
|
|
266
|
+
},
|
|
267
|
+
{ additionalProperties: false }
|
|
268
|
+
);
|
|
269
|
+
function createGetWorkflowTool(getClient) {
|
|
270
|
+
return {
|
|
271
|
+
name: "n8n_get_workflow",
|
|
272
|
+
label: "n8n: get workflow",
|
|
273
|
+
description: "Fetch a single n8n workflow by id. Returns metadata and optionally the full node graph. Resolves against the live workflow, not the workflow_entity row directly.",
|
|
274
|
+
parameters: Schema2,
|
|
275
|
+
execute: async (_toolCallId, rawParams) => {
|
|
276
|
+
const params = rawParams;
|
|
277
|
+
const wf = await getClient().getWorkflow(params.id);
|
|
278
|
+
const base = {
|
|
279
|
+
id: wf.id,
|
|
280
|
+
name: wf.name,
|
|
281
|
+
active: wf.active,
|
|
282
|
+
archived: wf.isArchived === true,
|
|
283
|
+
tags: (wf.tags ?? []).map((t) => t.name),
|
|
284
|
+
versionId: wf.versionId ?? null,
|
|
285
|
+
nodeCount: Array.isArray(wf.nodes) ? wf.nodes.length : 0,
|
|
286
|
+
nodeTypes: summarizeNodeTypes(wf.nodes),
|
|
287
|
+
createdAt: wf.createdAt,
|
|
288
|
+
updatedAt: wf.updatedAt
|
|
289
|
+
};
|
|
290
|
+
if (!params.includeDefinition) {
|
|
291
|
+
return jsonToolResult(base);
|
|
292
|
+
}
|
|
293
|
+
return jsonToolResult({
|
|
294
|
+
...base,
|
|
295
|
+
definition: {
|
|
296
|
+
nodes: wf.nodes,
|
|
297
|
+
connections: wf.connections,
|
|
298
|
+
settings: wf.settings ?? null,
|
|
299
|
+
staticData: wf.staticData ?? null,
|
|
300
|
+
pinData: wf.pinData ?? null
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function summarizeNodeTypes(nodes) {
|
|
307
|
+
if (!Array.isArray(nodes)) return {};
|
|
308
|
+
const counts = {};
|
|
309
|
+
for (const n of nodes) {
|
|
310
|
+
if (n && typeof n === "object" && "type" in n) {
|
|
311
|
+
const t = String(n.type);
|
|
312
|
+
counts[t] = (counts[t] ?? 0) + 1;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return counts;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// src/tools/list-executions.ts
|
|
319
|
+
import { Type as Type3 } from "@sinclair/typebox";
|
|
320
|
+
var Schema3 = Type3.Object(
|
|
321
|
+
{
|
|
322
|
+
workflowId: Type3.Optional(
|
|
323
|
+
Type3.String({
|
|
324
|
+
description: "Filter to a single workflow id. Omit for all workflows."
|
|
325
|
+
})
|
|
326
|
+
),
|
|
327
|
+
status: Type3.Optional(
|
|
328
|
+
Type3.Union(
|
|
329
|
+
[
|
|
330
|
+
Type3.Literal("success"),
|
|
331
|
+
Type3.Literal("error"),
|
|
332
|
+
Type3.Literal("running"),
|
|
333
|
+
Type3.Literal("waiting"),
|
|
334
|
+
Type3.Literal("canceled")
|
|
335
|
+
],
|
|
336
|
+
{ description: "Filter by execution status." }
|
|
337
|
+
)
|
|
338
|
+
),
|
|
339
|
+
limit: Type3.Optional(
|
|
340
|
+
Type3.Number({
|
|
341
|
+
minimum: 1,
|
|
342
|
+
maximum: 250,
|
|
343
|
+
description: "Max rows (default 50)."
|
|
344
|
+
})
|
|
345
|
+
)
|
|
346
|
+
},
|
|
347
|
+
{ additionalProperties: false }
|
|
348
|
+
);
|
|
349
|
+
function createListExecutionsTool(getClient) {
|
|
350
|
+
return {
|
|
351
|
+
name: "n8n_list_executions",
|
|
352
|
+
label: "n8n: list executions",
|
|
353
|
+
description: "List recent n8n executions with optional filters. Returns id, workflowId, workflowName, status, mode, startedAt, stoppedAt. Use n8n_get_execution for the full run log.",
|
|
354
|
+
parameters: Schema3,
|
|
355
|
+
execute: async (_toolCallId, rawParams) => {
|
|
356
|
+
const params = rawParams;
|
|
357
|
+
const client = getClient();
|
|
358
|
+
const [executions, workflowIndex] = await Promise.all([
|
|
359
|
+
client.listExecutions({
|
|
360
|
+
workflowId: params.workflowId,
|
|
361
|
+
status: params.status,
|
|
362
|
+
limit: params.limit ?? 50
|
|
363
|
+
}),
|
|
364
|
+
loadWorkflowNames(client)
|
|
365
|
+
]);
|
|
366
|
+
const rows = executions.data.map(
|
|
367
|
+
(ex) => summaryRow2(ex, workflowIndex)
|
|
368
|
+
);
|
|
369
|
+
return jsonToolResult({
|
|
370
|
+
count: rows.length,
|
|
371
|
+
executions: rows,
|
|
372
|
+
nextCursor: executions.nextCursor ?? null
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
async function loadWorkflowNames(client) {
|
|
378
|
+
const index = /* @__PURE__ */ new Map();
|
|
379
|
+
try {
|
|
380
|
+
const res = await client.listWorkflows({ limit: 250 });
|
|
381
|
+
for (const w of res.data) {
|
|
382
|
+
index.set(String(w.id), w.name);
|
|
383
|
+
}
|
|
384
|
+
} catch {
|
|
385
|
+
}
|
|
386
|
+
return index;
|
|
387
|
+
}
|
|
388
|
+
function summaryRow2(ex, workflowIndex) {
|
|
389
|
+
const workflowId = String(ex.workflowId ?? "");
|
|
390
|
+
return {
|
|
391
|
+
id: String(ex.id),
|
|
392
|
+
workflowId,
|
|
393
|
+
workflowName: workflowIndex.get(workflowId) ?? null,
|
|
394
|
+
status: ex.status ?? (ex.finished ? "success" : "running"),
|
|
395
|
+
mode: ex.mode,
|
|
396
|
+
startedAt: ex.startedAt ?? null,
|
|
397
|
+
stoppedAt: ex.stoppedAt ?? null,
|
|
398
|
+
finished: ex.finished
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/tools/get-execution.ts
|
|
403
|
+
import { Type as Type4 } from "@sinclair/typebox";
|
|
404
|
+
var Schema4 = Type4.Object(
|
|
405
|
+
{
|
|
406
|
+
id: Type4.String({
|
|
407
|
+
description: "Execution id (from n8n_list_executions)."
|
|
408
|
+
}),
|
|
409
|
+
includeRunData: Type4.Optional(
|
|
410
|
+
Type4.Boolean({
|
|
411
|
+
description: "Include the per-node run log. Default true. Turn off to get just status + error summary."
|
|
412
|
+
})
|
|
413
|
+
)
|
|
414
|
+
},
|
|
415
|
+
{ additionalProperties: false }
|
|
416
|
+
);
|
|
417
|
+
function createGetExecutionTool(deps) {
|
|
418
|
+
return {
|
|
419
|
+
name: "n8n_get_execution",
|
|
420
|
+
label: "n8n: get execution",
|
|
421
|
+
description: "Fetch a single n8n execution by id. Returns status, mode, timing, and per-node run data. Large run logs are truncated with a tail hint. Error executions include the raw error verbatim.",
|
|
422
|
+
parameters: Schema4,
|
|
423
|
+
execute: async (_toolCallId, rawParams) => {
|
|
424
|
+
const params = rawParams;
|
|
425
|
+
const includeRunData = params.includeRunData !== false;
|
|
426
|
+
const ex = await deps.getClient().getExecution(params.id, {
|
|
427
|
+
includeData: includeRunData
|
|
428
|
+
});
|
|
429
|
+
const status = ex.status ?? (ex.finished ? "success" : "running");
|
|
430
|
+
const base = {
|
|
431
|
+
id: String(ex.id),
|
|
432
|
+
workflowId: String(ex.workflowId ?? ""),
|
|
433
|
+
workflowName: ex.workflowData?.name ?? null,
|
|
434
|
+
status,
|
|
435
|
+
mode: ex.mode,
|
|
436
|
+
finished: ex.finished,
|
|
437
|
+
startedAt: ex.startedAt ?? null,
|
|
438
|
+
stoppedAt: ex.stoppedAt ?? null,
|
|
439
|
+
waitTill: ex.waitTill ?? null,
|
|
440
|
+
retryOf: ex.retryOf ?? null,
|
|
441
|
+
retrySuccessId: ex.retrySuccessId ?? null,
|
|
442
|
+
lastNodeExecuted: ex.data?.resultData?.lastNodeExecuted ?? null
|
|
443
|
+
};
|
|
444
|
+
const error = ex.data?.resultData?.error;
|
|
445
|
+
const runData = ex.data?.resultData?.runData;
|
|
446
|
+
const body = { ...base };
|
|
447
|
+
if (error !== void 0) {
|
|
448
|
+
body.error = error;
|
|
449
|
+
}
|
|
450
|
+
if (includeRunData && runData !== void 0) {
|
|
451
|
+
body.runData = truncateRunData(runData, deps.maxLogBytes);
|
|
452
|
+
}
|
|
453
|
+
return jsonToolResult(body);
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
function truncateRunData(runData, maxBytes) {
|
|
458
|
+
const serialized = JSON.stringify(runData);
|
|
459
|
+
const size = Buffer.byteLength(serialized, "utf8");
|
|
460
|
+
if (size <= maxBytes) {
|
|
461
|
+
return runData;
|
|
462
|
+
}
|
|
463
|
+
const tail = serialized.slice(-maxBytes);
|
|
464
|
+
return {
|
|
465
|
+
_truncated: true,
|
|
466
|
+
_hint: `log exceeded ${maxBytes} bytes (actual ${size}), showing tail`,
|
|
467
|
+
_tail: tail
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// src/tools/trigger.ts
|
|
472
|
+
import { Type as Type5 } from "@sinclair/typebox";
|
|
473
|
+
var Schema5 = Type5.Object(
|
|
474
|
+
{
|
|
475
|
+
mode: Type5.Union([Type5.Literal("workflow"), Type5.Literal("webhook")], {
|
|
476
|
+
description: "'workflow' triggers by workflow id (manual-style). 'webhook' POSTs to a webhook path."
|
|
477
|
+
}),
|
|
478
|
+
workflowId: Type5.Optional(
|
|
479
|
+
Type5.String({
|
|
480
|
+
description: "Required when mode=workflow. Id from n8n_list_workflows."
|
|
481
|
+
})
|
|
482
|
+
),
|
|
483
|
+
webhookPath: Type5.Optional(
|
|
484
|
+
Type5.String({
|
|
485
|
+
description: "Required when mode=webhook. Path portion after the base URL, e.g. /webhook/my-hook."
|
|
486
|
+
})
|
|
487
|
+
),
|
|
488
|
+
payload: Type5.Optional(
|
|
489
|
+
Type5.Record(Type5.String(), Type5.Unknown(), {
|
|
490
|
+
description: "Optional JSON body. Sent as request body for either mode."
|
|
491
|
+
})
|
|
492
|
+
),
|
|
493
|
+
method: Type5.Optional(
|
|
494
|
+
Type5.Union(
|
|
495
|
+
[
|
|
496
|
+
Type5.Literal("POST"),
|
|
497
|
+
Type5.Literal("GET"),
|
|
498
|
+
Type5.Literal("PUT"),
|
|
499
|
+
Type5.Literal("DELETE")
|
|
500
|
+
],
|
|
501
|
+
{
|
|
502
|
+
description: "HTTP method for webhook mode. Default POST."
|
|
503
|
+
}
|
|
504
|
+
)
|
|
505
|
+
)
|
|
506
|
+
},
|
|
507
|
+
{ additionalProperties: false }
|
|
508
|
+
);
|
|
509
|
+
var TRIGGER_ALLOWLIST = /* @__PURE__ */ new Set([
|
|
510
|
+
"n8n-nodes-base.webhook",
|
|
511
|
+
"n8n-nodes-base.manualTrigger",
|
|
512
|
+
"n8n-nodes-base.formTrigger",
|
|
513
|
+
"n8n-nodes-base.executeWorkflowTrigger"
|
|
514
|
+
]);
|
|
515
|
+
function createTriggerTool(getClient) {
|
|
516
|
+
return {
|
|
517
|
+
name: "n8n_trigger",
|
|
518
|
+
label: "n8n: trigger workflow",
|
|
519
|
+
description: "Run an n8n workflow. mode='webhook' POSTs to a webhook path with an optional JSON payload \u2014 this is the supported path on n8n's Public API. mode='workflow' tries POST /api/v1/workflows/:id/execute with an active/manual/webhook/form pre-check; most n8n builds do NOT expose this endpoint and return 405 \u2014 prefer mode='webhook' for reliable triggers.",
|
|
520
|
+
parameters: Schema5,
|
|
521
|
+
execute: async (_toolCallId, rawParams) => {
|
|
522
|
+
const params = rawParams;
|
|
523
|
+
const client = getClient();
|
|
524
|
+
if (params.mode === "workflow") {
|
|
525
|
+
if (!params.workflowId) {
|
|
526
|
+
return jsonToolResult({
|
|
527
|
+
ok: false,
|
|
528
|
+
error: "workflowId is required when mode=workflow"
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
const wf = await client.getWorkflow(params.workflowId);
|
|
532
|
+
const gate = checkTriggerable(wf);
|
|
533
|
+
if (!gate.ok) {
|
|
534
|
+
return jsonToolResult({
|
|
535
|
+
ok: false,
|
|
536
|
+
error: gate.reason,
|
|
537
|
+
workflowId: wf.id,
|
|
538
|
+
workflowName: wf.name,
|
|
539
|
+
active: wf.active,
|
|
540
|
+
triggerNodeType: gate.triggerNodeType
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
try {
|
|
544
|
+
const result = await client.executeWorkflow(
|
|
545
|
+
params.workflowId,
|
|
546
|
+
params.payload
|
|
547
|
+
);
|
|
548
|
+
return jsonToolResult({
|
|
549
|
+
ok: true,
|
|
550
|
+
mode: "workflow",
|
|
551
|
+
workflowId: wf.id,
|
|
552
|
+
workflowName: wf.name,
|
|
553
|
+
triggerNodeType: gate.triggerNodeType,
|
|
554
|
+
response: result
|
|
555
|
+
});
|
|
556
|
+
} catch (err) {
|
|
557
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
558
|
+
const hint = /\b40[45]\b/.test(msg) ? " \u2014 this n8n build likely does not expose /api/v1/workflows/:id/execute; use mode='webhook' with the trigger node's webhook path instead" : "";
|
|
559
|
+
return jsonToolResult({
|
|
560
|
+
ok: false,
|
|
561
|
+
mode: "workflow",
|
|
562
|
+
workflowId: wf.id,
|
|
563
|
+
workflowName: wf.name,
|
|
564
|
+
triggerNodeType: gate.triggerNodeType,
|
|
565
|
+
error: msg + hint
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (!params.webhookPath) {
|
|
570
|
+
return jsonToolResult({
|
|
571
|
+
ok: false,
|
|
572
|
+
error: "webhookPath is required when mode=webhook"
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
const res = await client.postWebhook(params.webhookPath, params.payload, {
|
|
576
|
+
method: params.method
|
|
577
|
+
});
|
|
578
|
+
return jsonToolResult({
|
|
579
|
+
ok: res.status >= 200 && res.status < 300,
|
|
580
|
+
mode: "webhook",
|
|
581
|
+
webhookPath: params.webhookPath,
|
|
582
|
+
method: params.method ?? "POST",
|
|
583
|
+
status: res.status,
|
|
584
|
+
response: res.body
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function checkTriggerable(wf) {
|
|
590
|
+
const triggerNode = findTriggerNode(wf);
|
|
591
|
+
const triggerNodeType = triggerNode?.type ?? null;
|
|
592
|
+
if (!wf.active) {
|
|
593
|
+
return {
|
|
594
|
+
ok: false,
|
|
595
|
+
reason: `workflow '${wf.name}' is not active; activate it in n8n before triggering`,
|
|
596
|
+
triggerNodeType
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
if (!triggerNode) {
|
|
600
|
+
return {
|
|
601
|
+
ok: false,
|
|
602
|
+
reason: "workflow has no recognizable trigger node",
|
|
603
|
+
triggerNodeType
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
if (!TRIGGER_ALLOWLIST.has(String(triggerNode.type))) {
|
|
607
|
+
return {
|
|
608
|
+
ok: false,
|
|
609
|
+
reason: `trigger node type '${triggerNode.type}' is not supported for external triggering (need webhook, manual, form, or executeWorkflow)`,
|
|
610
|
+
triggerNodeType
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
return { ok: true, triggerNodeType };
|
|
614
|
+
}
|
|
615
|
+
function findTriggerNode(wf) {
|
|
616
|
+
if (!Array.isArray(wf.nodes)) return null;
|
|
617
|
+
for (const raw of wf.nodes) {
|
|
618
|
+
if (!raw || typeof raw !== "object") continue;
|
|
619
|
+
const n = raw;
|
|
620
|
+
const type = typeof n.type === "string" ? n.type : "";
|
|
621
|
+
if (!type) continue;
|
|
622
|
+
if (type.toLowerCase().includes("trigger") || type === "n8n-nodes-base.webhook") {
|
|
623
|
+
return { type, name: typeof n.name === "string" ? n.name : void 0 };
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return null;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// src/tools/list-webhooks.ts
|
|
630
|
+
import { Type as Type6 } from "@sinclair/typebox";
|
|
631
|
+
var Schema6 = Type6.Object(
|
|
632
|
+
{
|
|
633
|
+
workflowId: Type6.Optional(
|
|
634
|
+
Type6.String({
|
|
635
|
+
description: "Restrict to a single workflow. Omit to scan recent workflows."
|
|
636
|
+
})
|
|
637
|
+
),
|
|
638
|
+
activeOnly: Type6.Optional(
|
|
639
|
+
Type6.Boolean({
|
|
640
|
+
description: "Only include active workflows. Default true."
|
|
641
|
+
})
|
|
642
|
+
),
|
|
643
|
+
limit: Type6.Optional(
|
|
644
|
+
Type6.Number({
|
|
645
|
+
minimum: 1,
|
|
646
|
+
maximum: 100,
|
|
647
|
+
description: "When workflowId is omitted, max workflows to fetch and scan (default 50)."
|
|
648
|
+
})
|
|
649
|
+
)
|
|
650
|
+
},
|
|
651
|
+
{ additionalProperties: false }
|
|
652
|
+
);
|
|
653
|
+
function createListWebhooksTool(deps) {
|
|
654
|
+
return {
|
|
655
|
+
name: "n8n_list_webhooks",
|
|
656
|
+
label: "n8n: list webhooks",
|
|
657
|
+
description: "Surface webhook and form-trigger paths from n8n workflows so agents can call n8n_trigger with mode='webhook' without opening the n8n UI. Returns workflowId, workflowName, nodeName, method, path, and a fully-formed triggerUrl.",
|
|
658
|
+
parameters: Schema6,
|
|
659
|
+
execute: async (_toolCallId, rawParams) => {
|
|
660
|
+
const params = rawParams;
|
|
661
|
+
const activeOnly = params.activeOnly !== false;
|
|
662
|
+
const client = deps.getClient();
|
|
663
|
+
const workflows = [];
|
|
664
|
+
if (params.workflowId) {
|
|
665
|
+
workflows.push(await client.getWorkflow(params.workflowId));
|
|
666
|
+
} else {
|
|
667
|
+
const list = await client.listWorkflows({
|
|
668
|
+
active: activeOnly ? true : void 0,
|
|
669
|
+
limit: params.limit ?? 50
|
|
670
|
+
});
|
|
671
|
+
const defs = await Promise.all(
|
|
672
|
+
list.data.map((w) => client.getWorkflow(w.id))
|
|
673
|
+
);
|
|
674
|
+
workflows.push(...defs);
|
|
675
|
+
}
|
|
676
|
+
const webhooks = [];
|
|
677
|
+
for (const wf of workflows) {
|
|
678
|
+
if (activeOnly && !wf.active) continue;
|
|
679
|
+
if (!Array.isArray(wf.nodes)) continue;
|
|
680
|
+
for (const node of wf.nodes) {
|
|
681
|
+
const hook = extractWebhook(node, wf, deps.baseUrl);
|
|
682
|
+
if (hook) webhooks.push(hook);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return jsonToolResult({
|
|
686
|
+
count: webhooks.length,
|
|
687
|
+
scannedWorkflows: workflows.length,
|
|
688
|
+
activeOnly,
|
|
689
|
+
webhooks
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
function extractWebhook(rawNode, wf, baseUrl) {
|
|
695
|
+
if (!rawNode || typeof rawNode !== "object") return null;
|
|
696
|
+
const n = rawNode;
|
|
697
|
+
const type = String(n.type ?? "");
|
|
698
|
+
const name = typeof n.name === "string" ? n.name : "";
|
|
699
|
+
const params = n.parameters ?? {};
|
|
700
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
701
|
+
if (type === "n8n-nodes-base.webhook") {
|
|
702
|
+
const pathRaw = typeof params.path === "string" && params.path.trim() ? params.path.trim() : typeof n.webhookId === "string" ? String(n.webhookId) : "";
|
|
703
|
+
if (!pathRaw) return null;
|
|
704
|
+
const path2 = pathRaw.replace(/^\/+/, "");
|
|
705
|
+
const method = typeof params.httpMethod === "string" && params.httpMethod.trim() ? params.httpMethod.toUpperCase() : "POST";
|
|
706
|
+
return {
|
|
707
|
+
workflowId: wf.id,
|
|
708
|
+
workflowName: wf.name,
|
|
709
|
+
active: wf.active,
|
|
710
|
+
nodeName: name,
|
|
711
|
+
nodeType: type,
|
|
712
|
+
method,
|
|
713
|
+
path: `/webhook/${path2}`,
|
|
714
|
+
triggerUrl: `${base}/webhook/${path2}`,
|
|
715
|
+
testTriggerUrl: `${base}/webhook-test/${path2}`
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
if (type === "n8n-nodes-base.formTrigger") {
|
|
719
|
+
const pathRaw = typeof params.path === "string" && params.path.trim() ? params.path.trim() : typeof n.webhookId === "string" ? String(n.webhookId) : "";
|
|
720
|
+
if (!pathRaw) return null;
|
|
721
|
+
const path2 = pathRaw.replace(/^\/+/, "");
|
|
722
|
+
return {
|
|
723
|
+
workflowId: wf.id,
|
|
724
|
+
workflowName: wf.name,
|
|
725
|
+
active: wf.active,
|
|
726
|
+
nodeName: name,
|
|
727
|
+
nodeType: type,
|
|
728
|
+
method: "POST",
|
|
729
|
+
path: `/form/${path2}`,
|
|
730
|
+
triggerUrl: `${base}/form/${path2}`
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
return null;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// src/tools/validate-workflow.ts
|
|
737
|
+
import { Type as Type7 } from "@sinclair/typebox";
|
|
738
|
+
var Schema7 = Type7.Object(
|
|
739
|
+
{
|
|
740
|
+
id: Type7.String({
|
|
741
|
+
description: "Workflow id (from n8n_list_workflows)."
|
|
742
|
+
})
|
|
743
|
+
},
|
|
744
|
+
{ additionalProperties: false }
|
|
745
|
+
);
|
|
746
|
+
var DEPRECATED_NODE_TYPES = {
|
|
747
|
+
"n8n-nodes-base.function": "n8n-nodes-base.code",
|
|
748
|
+
"n8n-nodes-base.functionItem": "n8n-nodes-base.code"
|
|
749
|
+
};
|
|
750
|
+
var TRIGGER_TYPE_MARKERS = [
|
|
751
|
+
"trigger",
|
|
752
|
+
"n8n-nodes-base.webhook",
|
|
753
|
+
"n8n-nodes-base.executeWorkflowTrigger"
|
|
754
|
+
];
|
|
755
|
+
function createValidateWorkflowTool(getClient) {
|
|
756
|
+
return {
|
|
757
|
+
name: "n8n_validate_workflow",
|
|
758
|
+
label: "n8n: validate workflow",
|
|
759
|
+
description: "Static checks on a workflow: deprecated node types (function \u2192 code), old Code-node API usage ($node[], items global, require()), orphan nodes, disabled nodes, and missing trigger. Returns a list of issues with severity.",
|
|
760
|
+
parameters: Schema7,
|
|
761
|
+
execute: async (_toolCallId, rawParams) => {
|
|
762
|
+
const { id } = rawParams;
|
|
763
|
+
const wf = await getClient().getWorkflow(id);
|
|
764
|
+
const issues = validateWorkflow(wf);
|
|
765
|
+
const summary = summarize(issues);
|
|
766
|
+
return jsonToolResult({
|
|
767
|
+
workflowId: wf.id,
|
|
768
|
+
workflowName: wf.name,
|
|
769
|
+
active: wf.active,
|
|
770
|
+
nodeCount: Array.isArray(wf.nodes) ? wf.nodes.length : 0,
|
|
771
|
+
summary,
|
|
772
|
+
issues
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
function validateWorkflow(wf) {
|
|
778
|
+
const issues = [];
|
|
779
|
+
const nodes = Array.isArray(wf.nodes) ? wf.nodes : [];
|
|
780
|
+
const triggerNodes = nodes.filter((n) => isTriggerNode(n));
|
|
781
|
+
if (triggerNodes.length === 0) {
|
|
782
|
+
issues.push({
|
|
783
|
+
severity: "error",
|
|
784
|
+
code: "missing-trigger",
|
|
785
|
+
message: "Workflow has no trigger node and cannot be executed."
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
const incoming = buildIncomingIndex(wf.connections);
|
|
789
|
+
for (const raw of nodes) {
|
|
790
|
+
if (!raw || typeof raw !== "object") continue;
|
|
791
|
+
const node = raw;
|
|
792
|
+
const name = typeof node.name === "string" ? node.name : "<unnamed>";
|
|
793
|
+
const type = typeof node.type === "string" ? node.type : "";
|
|
794
|
+
const disabled = node.disabled === true;
|
|
795
|
+
const replacement = DEPRECATED_NODE_TYPES[type];
|
|
796
|
+
if (replacement) {
|
|
797
|
+
issues.push({
|
|
798
|
+
severity: "warning",
|
|
799
|
+
code: "deprecated-node-type",
|
|
800
|
+
message: `Node type '${type}' is deprecated. Migrate to '${replacement}'.`,
|
|
801
|
+
nodeName: name,
|
|
802
|
+
nodeType: type
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
if (type === "n8n-nodes-base.code" || type === "n8n-nodes-base.function") {
|
|
806
|
+
const codeIssues = checkCodeNode(node, name, type);
|
|
807
|
+
issues.push(...codeIssues);
|
|
808
|
+
}
|
|
809
|
+
if (disabled) {
|
|
810
|
+
issues.push({
|
|
811
|
+
severity: "info",
|
|
812
|
+
code: "disabled-node",
|
|
813
|
+
message: `Node '${name}' is disabled; downstream branches will be skipped.`,
|
|
814
|
+
nodeName: name,
|
|
815
|
+
nodeType: type
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
if (!isTriggerNode(node) && !incoming.has(name)) {
|
|
819
|
+
issues.push({
|
|
820
|
+
severity: "warning",
|
|
821
|
+
code: "orphan-node",
|
|
822
|
+
message: `Node '${name}' has no incoming connections and is not a trigger. It will never execute.`,
|
|
823
|
+
nodeName: name,
|
|
824
|
+
nodeType: type
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
return issues;
|
|
829
|
+
}
|
|
830
|
+
function checkCodeNode(node, name, type) {
|
|
831
|
+
const issues = [];
|
|
832
|
+
const params = node.parameters ?? {};
|
|
833
|
+
const code = collectCodeStrings(params);
|
|
834
|
+
if (!code) return issues;
|
|
835
|
+
if (/\brequire\s*\(/.test(code)) {
|
|
836
|
+
issues.push({
|
|
837
|
+
severity: "warning",
|
|
838
|
+
code: "code-node-require",
|
|
839
|
+
message: `Code node '${name}' calls require(); n8n blocks this unless NODE_FUNCTION_ALLOW_EXTERNAL is set on the host.`,
|
|
840
|
+
nodeName: name,
|
|
841
|
+
nodeType: type
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
if (/\$node\s*\[/.test(code)) {
|
|
845
|
+
issues.push({
|
|
846
|
+
severity: "warning",
|
|
847
|
+
code: "code-node-old-node-ref",
|
|
848
|
+
message: `Code node '${name}' uses $node[...] (legacy API). Prefer $('Node Name').`,
|
|
849
|
+
nodeName: name,
|
|
850
|
+
nodeType: type
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
if (/(^|[^.\w$])items(\s*\[|\s*\.|\s*;|\s*\))/m.test(code)) {
|
|
854
|
+
issues.push({
|
|
855
|
+
severity: "warning",
|
|
856
|
+
code: "code-node-items-global",
|
|
857
|
+
message: `Code node '${name}' references the 'items' global (removed in n8n v1). Use $input.all() or $input.first().`,
|
|
858
|
+
nodeName: name,
|
|
859
|
+
nodeType: type
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
return issues;
|
|
863
|
+
}
|
|
864
|
+
function collectCodeStrings(params) {
|
|
865
|
+
const parts = [];
|
|
866
|
+
for (const key of ["jsCode", "functionCode", "code", "pythonCode"]) {
|
|
867
|
+
const v = params[key];
|
|
868
|
+
if (typeof v === "string") parts.push(v);
|
|
869
|
+
}
|
|
870
|
+
return parts.join("\n");
|
|
871
|
+
}
|
|
872
|
+
function buildIncomingIndex(connections) {
|
|
873
|
+
const incoming = /* @__PURE__ */ new Set();
|
|
874
|
+
if (!connections || typeof connections !== "object") return incoming;
|
|
875
|
+
for (const outputs of Object.values(connections)) {
|
|
876
|
+
if (!outputs || typeof outputs !== "object") continue;
|
|
877
|
+
for (const outputBranches of Object.values(outputs)) {
|
|
878
|
+
if (!Array.isArray(outputBranches)) continue;
|
|
879
|
+
for (const branch of outputBranches) {
|
|
880
|
+
if (!Array.isArray(branch)) continue;
|
|
881
|
+
for (const edge of branch) {
|
|
882
|
+
if (edge && typeof edge === "object" && "node" in edge) {
|
|
883
|
+
const target = edge.node;
|
|
884
|
+
if (typeof target === "string") incoming.add(target);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
return incoming;
|
|
891
|
+
}
|
|
892
|
+
function isTriggerNode(raw) {
|
|
893
|
+
if (!raw || typeof raw !== "object") return false;
|
|
894
|
+
const n = raw;
|
|
895
|
+
const type = typeof n.type === "string" ? n.type.toLowerCase() : "";
|
|
896
|
+
if (!type) return false;
|
|
897
|
+
return TRIGGER_TYPE_MARKERS.some((marker) => type.includes(marker));
|
|
898
|
+
}
|
|
899
|
+
function summarize(issues) {
|
|
900
|
+
let errors = 0;
|
|
901
|
+
let warnings = 0;
|
|
902
|
+
let info = 0;
|
|
903
|
+
for (const i of issues) {
|
|
904
|
+
if (i.severity === "error") errors++;
|
|
905
|
+
else if (i.severity === "warning") warnings++;
|
|
906
|
+
else info++;
|
|
907
|
+
}
|
|
908
|
+
return { errors, warnings, info, ok: errors === 0 };
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// src/tools/activate.ts
|
|
912
|
+
import { Type as Type8 } from "@sinclair/typebox";
|
|
913
|
+
var Schema8 = Type8.Object(
|
|
914
|
+
{
|
|
915
|
+
id: Type8.String({ description: "Workflow id to activate." })
|
|
916
|
+
},
|
|
917
|
+
{ additionalProperties: false }
|
|
918
|
+
);
|
|
919
|
+
function createActivateTool(getClient) {
|
|
920
|
+
return {
|
|
921
|
+
name: "n8n_activate",
|
|
922
|
+
label: "n8n: activate workflow",
|
|
923
|
+
description: "Activate an n8n workflow so its triggers (webhooks, schedules, polling) start running. Idempotent - activating an already-active workflow returns the current state. Requires enableEdit.",
|
|
924
|
+
parameters: Schema8,
|
|
925
|
+
execute: async (_toolCallId, rawParams) => {
|
|
926
|
+
const { id } = rawParams;
|
|
927
|
+
const wf = await getClient().activateWorkflow(id);
|
|
928
|
+
return jsonToolResult({
|
|
929
|
+
ok: true,
|
|
930
|
+
action: "activate",
|
|
931
|
+
workflowId: wf.id,
|
|
932
|
+
workflowName: wf.name,
|
|
933
|
+
active: wf.active,
|
|
934
|
+
updatedAt: wf.updatedAt
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// src/tools/deactivate.ts
|
|
941
|
+
import { Type as Type9 } from "@sinclair/typebox";
|
|
942
|
+
var Schema9 = Type9.Object(
|
|
943
|
+
{
|
|
944
|
+
id: Type9.String({ description: "Workflow id to deactivate." })
|
|
945
|
+
},
|
|
946
|
+
{ additionalProperties: false }
|
|
947
|
+
);
|
|
948
|
+
function createDeactivateTool(getClient) {
|
|
949
|
+
return {
|
|
950
|
+
name: "n8n_deactivate",
|
|
951
|
+
label: "n8n: deactivate workflow",
|
|
952
|
+
description: "Deactivate an n8n workflow so its triggers stop firing. Running executions are not cancelled. Idempotent. Requires enableEdit.",
|
|
953
|
+
parameters: Schema9,
|
|
954
|
+
execute: async (_toolCallId, rawParams) => {
|
|
955
|
+
const { id } = rawParams;
|
|
956
|
+
const wf = await getClient().deactivateWorkflow(id);
|
|
957
|
+
return jsonToolResult({
|
|
958
|
+
ok: true,
|
|
959
|
+
action: "deactivate",
|
|
960
|
+
workflowId: wf.id,
|
|
961
|
+
workflowName: wf.name,
|
|
962
|
+
active: wf.active,
|
|
963
|
+
updatedAt: wf.updatedAt
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
// src/tools/save-workflow.ts
|
|
970
|
+
import { Type as Type10 } from "@sinclair/typebox";
|
|
971
|
+
import { promises as fs } from "fs";
|
|
972
|
+
import { homedir } from "os";
|
|
973
|
+
import path from "path";
|
|
974
|
+
var Schema10 = Type10.Object(
|
|
975
|
+
{
|
|
976
|
+
id: Type10.String({ description: "Workflow id to overwrite." }),
|
|
977
|
+
definition: Type10.Object(
|
|
978
|
+
{
|
|
979
|
+
name: Type10.Optional(Type10.String()),
|
|
980
|
+
nodes: Type10.Array(Type10.Record(Type10.String(), Type10.Unknown())),
|
|
981
|
+
connections: Type10.Record(Type10.String(), Type10.Unknown()),
|
|
982
|
+
settings: Type10.Optional(Type10.Record(Type10.String(), Type10.Unknown())),
|
|
983
|
+
staticData: Type10.Optional(Type10.Unknown())
|
|
984
|
+
},
|
|
985
|
+
{
|
|
986
|
+
additionalProperties: true,
|
|
987
|
+
description: "Full new workflow body. Copy from n8n_get_workflow with includeDefinition=true, modify, then pass the nodes + connections (+ optional settings/staticData/name) here."
|
|
988
|
+
}
|
|
989
|
+
),
|
|
990
|
+
skipValidation: Type10.Optional(
|
|
991
|
+
Type10.Boolean({
|
|
992
|
+
description: "Skip the n8n_validate_workflow pre-check. Default false. Validation errors (not warnings) block the save by default."
|
|
993
|
+
})
|
|
994
|
+
),
|
|
995
|
+
confirm: Type10.Boolean({
|
|
996
|
+
description: "Must be true to actually write. A snapshot of the current workflow is saved to backupDir regardless."
|
|
997
|
+
})
|
|
998
|
+
},
|
|
999
|
+
{ additionalProperties: false }
|
|
1000
|
+
);
|
|
1001
|
+
function createSaveWorkflowTool(deps) {
|
|
1002
|
+
return {
|
|
1003
|
+
name: "n8n_save_workflow",
|
|
1004
|
+
label: "n8n: save workflow",
|
|
1005
|
+
description: "Overwrite an n8n workflow. Snapshots the current version to backupDir first, runs n8n_validate_workflow on the proposed new state (errors block, warnings pass through), then PUTs the new body. Requires enableEdit and explicit confirm=true.",
|
|
1006
|
+
parameters: Schema10,
|
|
1007
|
+
execute: async (_toolCallId, rawParams) => {
|
|
1008
|
+
const params = rawParams;
|
|
1009
|
+
if (!params.confirm) {
|
|
1010
|
+
return jsonToolResult({
|
|
1011
|
+
ok: false,
|
|
1012
|
+
error: "confirm must be true to save"
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
const client = deps.getClient();
|
|
1016
|
+
const current = await client.getWorkflow(params.id);
|
|
1017
|
+
const backupPath = await writeBackup(
|
|
1018
|
+
resolveBackupDir(deps.backupDir),
|
|
1019
|
+
current
|
|
1020
|
+
);
|
|
1021
|
+
if (!params.skipValidation) {
|
|
1022
|
+
const proposed = {
|
|
1023
|
+
...current,
|
|
1024
|
+
...params.definition,
|
|
1025
|
+
id: current.id
|
|
1026
|
+
};
|
|
1027
|
+
const issues = validateWorkflow(proposed);
|
|
1028
|
+
const errors = issues.filter((i) => i.severity === "error");
|
|
1029
|
+
if (errors.length > 0) {
|
|
1030
|
+
return jsonToolResult({
|
|
1031
|
+
ok: false,
|
|
1032
|
+
error: "validation failed; save aborted",
|
|
1033
|
+
backupPath,
|
|
1034
|
+
issues
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
const body = buildSaveBody(current, params.definition);
|
|
1039
|
+
try {
|
|
1040
|
+
const saved = await client.saveWorkflow(params.id, body);
|
|
1041
|
+
return jsonToolResult({
|
|
1042
|
+
ok: true,
|
|
1043
|
+
action: "save",
|
|
1044
|
+
workflowId: saved.id,
|
|
1045
|
+
workflowName: saved.name,
|
|
1046
|
+
active: saved.active,
|
|
1047
|
+
versionId: saved.versionId ?? null,
|
|
1048
|
+
updatedAt: saved.updatedAt,
|
|
1049
|
+
backupPath,
|
|
1050
|
+
restoreHint: `To restore: n8n_save_workflow with id=${saved.id}, confirm=true, definition=<contents of ${backupPath}>.`
|
|
1051
|
+
});
|
|
1052
|
+
} catch (err) {
|
|
1053
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1054
|
+
return jsonToolResult({
|
|
1055
|
+
ok: false,
|
|
1056
|
+
error: `save failed: ${msg}`,
|
|
1057
|
+
backupPath,
|
|
1058
|
+
restoreHint: `Snapshot preserved at ${backupPath}. Server state may or may not have been mutated; fetch n8n_get_workflow to verify.`
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
function buildSaveBody(current, proposed) {
|
|
1065
|
+
const body = {
|
|
1066
|
+
name: proposed.name ?? current.name,
|
|
1067
|
+
nodes: proposed.nodes ?? current.nodes,
|
|
1068
|
+
connections: proposed.connections ?? current.connections,
|
|
1069
|
+
settings: proposed.settings ?? current.settings ?? {}
|
|
1070
|
+
};
|
|
1071
|
+
if (proposed.staticData !== void 0) {
|
|
1072
|
+
body.staticData = proposed.staticData;
|
|
1073
|
+
} else if (current.staticData !== void 0) {
|
|
1074
|
+
body.staticData = current.staticData;
|
|
1075
|
+
}
|
|
1076
|
+
return body;
|
|
1077
|
+
}
|
|
1078
|
+
function resolveBackupDir(configured) {
|
|
1079
|
+
const raw = configured?.trim() || "~/.n8n-backups";
|
|
1080
|
+
return raw.startsWith("~") ? path.join(homedir(), raw.slice(1).replace(/^\/+/, "")) : raw;
|
|
1081
|
+
}
|
|
1082
|
+
async function writeBackup(dir, wf) {
|
|
1083
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1084
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").replace("T", "_").replace("Z", "");
|
|
1085
|
+
const safeName = String(wf.id).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
1086
|
+
const file = path.join(dir, `${safeName}-${stamp}.json`);
|
|
1087
|
+
await fs.writeFile(file, JSON.stringify(wf, null, 2), { mode: 384 });
|
|
1088
|
+
return file;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// mcp-server.ts
|
|
1092
|
+
var VERSION = "0.1.0";
|
|
1093
|
+
function readConfigFromEnv() {
|
|
1094
|
+
const baseUrl = (process.env.N8N_BASE_URL ?? "").trim();
|
|
1095
|
+
if (!baseUrl) {
|
|
1096
|
+
throw new Error(
|
|
1097
|
+
"N8N_BASE_URL is required (e.g. http://localhost:5678). Set it in your MCP client env config."
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
const apiKeyEnv = (process.env.N8N_API_KEY_ENV ?? "N8N_API_KEY").trim() || "N8N_API_KEY";
|
|
1101
|
+
const apiKey = (process.env[apiKeyEnv] ?? "").trim();
|
|
1102
|
+
if (!apiKey) {
|
|
1103
|
+
throw new Error(
|
|
1104
|
+
`${apiKeyEnv} is required. Set it in your MCP client env config (generate an API key in n8n under Settings -> API).`
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
return {
|
|
1108
|
+
baseUrl,
|
|
1109
|
+
apiKeyInline: apiKey,
|
|
1110
|
+
apiKeyEnv,
|
|
1111
|
+
enableEdit: parseBool(process.env.N8N_ENABLE_EDIT) ?? false,
|
|
1112
|
+
maxExecutionLogBytes: parsePosInt("N8N_MAX_EXECUTION_LOG_BYTES", 65536, 1024),
|
|
1113
|
+
requestTimeoutMs: parsePosInt("N8N_REQUEST_TIMEOUT_MS", 15e3, 1e3),
|
|
1114
|
+
backupDir: (process.env.N8N_BACKUP_DIR ?? "").trim() || void 0
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
function parseBool(raw) {
|
|
1118
|
+
if (raw === void 0) return void 0;
|
|
1119
|
+
const v = raw.trim().toLowerCase();
|
|
1120
|
+
if (v === "1" || v === "true" || v === "yes") return true;
|
|
1121
|
+
if (v === "0" || v === "false" || v === "no") return false;
|
|
1122
|
+
return void 0;
|
|
1123
|
+
}
|
|
1124
|
+
function parsePosInt(envName, fallback, min) {
|
|
1125
|
+
const raw = process.env[envName];
|
|
1126
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
1127
|
+
const n = Number(raw);
|
|
1128
|
+
if (!Number.isFinite(n) || !Number.isInteger(n) || n < min) {
|
|
1129
|
+
throw new Error(
|
|
1130
|
+
`${envName} must be an integer >= ${min} (got ${JSON.stringify(raw)}).`
|
|
1131
|
+
);
|
|
1132
|
+
}
|
|
1133
|
+
return n;
|
|
1134
|
+
}
|
|
1135
|
+
function lazyClient(config) {
|
|
1136
|
+
let cached;
|
|
1137
|
+
return () => {
|
|
1138
|
+
if (!cached) cached = makeClient(config);
|
|
1139
|
+
return cached;
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
function bind(server, tool, shape) {
|
|
1143
|
+
const handler = async (args) => {
|
|
1144
|
+
const res = await tool.execute("mcp", args);
|
|
1145
|
+
return { content: res.content };
|
|
1146
|
+
};
|
|
1147
|
+
server.tool(tool.name, tool.description, shape, handler);
|
|
1148
|
+
}
|
|
1149
|
+
async function main() {
|
|
1150
|
+
const config = readConfigFromEnv();
|
|
1151
|
+
const getClient = lazyClient(config);
|
|
1152
|
+
const server = new McpServer({
|
|
1153
|
+
name: "n8n-ops-mcp",
|
|
1154
|
+
version: VERSION,
|
|
1155
|
+
description: "Ops-focused n8n tools: list, inspect, trigger, validate, and safely edit workflows via the n8n Public API."
|
|
1156
|
+
});
|
|
1157
|
+
bind(server, createListWorkflowsTool(getClient), {
|
|
1158
|
+
active: z.boolean().optional().describe("Filter by active state. Omit for all."),
|
|
1159
|
+
tags: z.string().optional().describe("Comma-separated tag names to filter by."),
|
|
1160
|
+
name: z.string().optional().describe("Case-insensitive substring match on workflow name."),
|
|
1161
|
+
limit: z.number().int().min(1).max(250).optional().describe("Max rows (default 100).")
|
|
1162
|
+
});
|
|
1163
|
+
bind(server, createGetWorkflowTool(getClient), {
|
|
1164
|
+
id: z.string().describe("Workflow id (from n8n_list_workflows)."),
|
|
1165
|
+
includeDefinition: z.boolean().optional().describe(
|
|
1166
|
+
"Include full nodes+connections JSON. Off by default. Turn on when you need to inspect or edit."
|
|
1167
|
+
)
|
|
1168
|
+
});
|
|
1169
|
+
bind(server, createListExecutionsTool(getClient), {
|
|
1170
|
+
workflowId: z.string().optional().describe("Filter to a single workflow id. Omit for all."),
|
|
1171
|
+
status: z.enum(["success", "error", "running", "waiting", "canceled"]).optional().describe("Filter by execution status."),
|
|
1172
|
+
limit: z.number().int().min(1).max(250).optional().describe("Max rows (default 50).")
|
|
1173
|
+
});
|
|
1174
|
+
bind(
|
|
1175
|
+
server,
|
|
1176
|
+
createGetExecutionTool({
|
|
1177
|
+
getClient,
|
|
1178
|
+
maxLogBytes: config.maxExecutionLogBytes
|
|
1179
|
+
}),
|
|
1180
|
+
{
|
|
1181
|
+
id: z.string().describe("Execution id (from n8n_list_executions)."),
|
|
1182
|
+
includeRunData: z.boolean().optional().describe(
|
|
1183
|
+
"Include per-node run log. Default true. Turn off for just status + error summary."
|
|
1184
|
+
)
|
|
1185
|
+
}
|
|
1186
|
+
);
|
|
1187
|
+
bind(server, createTriggerTool(getClient), {
|
|
1188
|
+
mode: z.enum(["workflow", "webhook"]).describe(
|
|
1189
|
+
"'workflow' triggers by workflow id (manual-style; most builds 405). 'webhook' POSTs to a webhook path."
|
|
1190
|
+
),
|
|
1191
|
+
workflowId: z.string().optional().describe("Required when mode=workflow. Id from n8n_list_workflows."),
|
|
1192
|
+
webhookPath: z.string().optional().describe("Required when mode=webhook. Path after the base URL, e.g. /webhook/my-hook."),
|
|
1193
|
+
payload: z.record(z.string(), z.unknown()).optional().describe("Optional JSON body."),
|
|
1194
|
+
method: z.enum(["POST", "GET", "PUT", "DELETE"]).optional().describe("HTTP method for webhook mode. Default POST.")
|
|
1195
|
+
});
|
|
1196
|
+
bind(
|
|
1197
|
+
server,
|
|
1198
|
+
createListWebhooksTool({ getClient, baseUrl: config.baseUrl }),
|
|
1199
|
+
{
|
|
1200
|
+
workflowId: z.string().optional().describe("Restrict to a single workflow."),
|
|
1201
|
+
activeOnly: z.boolean().optional().describe("Only include active workflows. Default true."),
|
|
1202
|
+
limit: z.number().int().min(1).max(100).optional().describe("Max workflows to scan when workflowId is omitted (default 50).")
|
|
1203
|
+
}
|
|
1204
|
+
);
|
|
1205
|
+
bind(server, createValidateWorkflowTool(getClient), {
|
|
1206
|
+
id: z.string().describe("Workflow id (from n8n_list_workflows).")
|
|
1207
|
+
});
|
|
1208
|
+
if (config.enableEdit) {
|
|
1209
|
+
bind(server, createActivateTool(getClient), {
|
|
1210
|
+
id: z.string().describe("Workflow id to activate.")
|
|
1211
|
+
});
|
|
1212
|
+
bind(server, createDeactivateTool(getClient), {
|
|
1213
|
+
id: z.string().describe("Workflow id to deactivate.")
|
|
1214
|
+
});
|
|
1215
|
+
bind(
|
|
1216
|
+
server,
|
|
1217
|
+
createSaveWorkflowTool({ getClient, backupDir: config.backupDir }),
|
|
1218
|
+
{
|
|
1219
|
+
id: z.string().describe("Workflow id to overwrite."),
|
|
1220
|
+
definition: z.object({
|
|
1221
|
+
name: z.string().optional(),
|
|
1222
|
+
nodes: z.array(z.record(z.string(), z.unknown())),
|
|
1223
|
+
connections: z.record(z.string(), z.unknown()),
|
|
1224
|
+
settings: z.record(z.string(), z.unknown()).optional(),
|
|
1225
|
+
staticData: z.unknown().optional()
|
|
1226
|
+
}).loose().describe(
|
|
1227
|
+
"Full new workflow body. Copy from n8n_get_workflow with includeDefinition=true, modify, then pass back."
|
|
1228
|
+
),
|
|
1229
|
+
skipValidation: z.boolean().optional().describe("Skip the validate-workflow pre-check. Default false."),
|
|
1230
|
+
confirm: z.boolean().describe("Must be true to actually write. Snapshot to backupDir happens regardless.")
|
|
1231
|
+
}
|
|
1232
|
+
);
|
|
1233
|
+
}
|
|
1234
|
+
const transport = new StdioServerTransport();
|
|
1235
|
+
await server.connect(transport);
|
|
1236
|
+
}
|
|
1237
|
+
main().catch((err) => {
|
|
1238
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1239
|
+
console.error(`n8n-ops-mcp fatal: ${msg}`);
|
|
1240
|
+
process.exit(1);
|
|
1241
|
+
});
|