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.
@@ -0,0 +1,185 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { N8nClient, N8nWorkflow } from "../client.ts";
3
+ import { jsonToolResult } from "./result.ts";
4
+
5
+ const Schema = Type.Object(
6
+ {
7
+ mode: Type.Union([Type.Literal("workflow"), Type.Literal("webhook")], {
8
+ description:
9
+ "'workflow' triggers by workflow id (manual-style). 'webhook' POSTs to a webhook path.",
10
+ }),
11
+ workflowId: Type.Optional(
12
+ Type.String({
13
+ description: "Required when mode=workflow. Id from n8n_list_workflows.",
14
+ }),
15
+ ),
16
+ webhookPath: Type.Optional(
17
+ Type.String({
18
+ description:
19
+ "Required when mode=webhook. Path portion after the base URL, e.g. /webhook/my-hook.",
20
+ }),
21
+ ),
22
+ payload: Type.Optional(
23
+ Type.Record(Type.String(), Type.Unknown(), {
24
+ description: "Optional JSON body. Sent as request body for either mode.",
25
+ }),
26
+ ),
27
+ method: Type.Optional(
28
+ Type.Union(
29
+ [
30
+ Type.Literal("POST"),
31
+ Type.Literal("GET"),
32
+ Type.Literal("PUT"),
33
+ Type.Literal("DELETE"),
34
+ ],
35
+ {
36
+ description: "HTTP method for webhook mode. Default POST.",
37
+ },
38
+ ),
39
+ ),
40
+ },
41
+ { additionalProperties: false },
42
+ );
43
+
44
+ const TRIGGER_ALLOWLIST = new Set([
45
+ "n8n-nodes-base.webhook",
46
+ "n8n-nodes-base.manualTrigger",
47
+ "n8n-nodes-base.formTrigger",
48
+ "n8n-nodes-base.executeWorkflowTrigger",
49
+ ]);
50
+
51
+ export function createTriggerTool(getClient: () => N8nClient) {
52
+ return {
53
+ name: "n8n_trigger",
54
+ label: "n8n: trigger workflow",
55
+ description:
56
+ "Run an n8n workflow. mode='webhook' POSTs to a webhook path with an optional JSON payload — 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 — prefer mode='webhook' for reliable triggers.",
57
+ parameters: Schema,
58
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
59
+ const params = rawParams as {
60
+ mode: "workflow" | "webhook";
61
+ workflowId?: string;
62
+ webhookPath?: string;
63
+ payload?: Record<string, unknown>;
64
+ method?: "POST" | "GET" | "PUT" | "DELETE";
65
+ };
66
+ const client = getClient();
67
+
68
+ if (params.mode === "workflow") {
69
+ if (!params.workflowId) {
70
+ return jsonToolResult({
71
+ ok: false,
72
+ error: "workflowId is required when mode=workflow",
73
+ });
74
+ }
75
+ const wf = await client.getWorkflow(params.workflowId);
76
+ const gate = checkTriggerable(wf);
77
+ if (!gate.ok) {
78
+ return jsonToolResult({
79
+ ok: false,
80
+ error: gate.reason,
81
+ workflowId: wf.id,
82
+ workflowName: wf.name,
83
+ active: wf.active,
84
+ triggerNodeType: gate.triggerNodeType,
85
+ });
86
+ }
87
+ try {
88
+ const result = await client.executeWorkflow(
89
+ params.workflowId,
90
+ params.payload,
91
+ );
92
+ return jsonToolResult({
93
+ ok: true,
94
+ mode: "workflow",
95
+ workflowId: wf.id,
96
+ workflowName: wf.name,
97
+ triggerNodeType: gate.triggerNodeType,
98
+ response: result,
99
+ });
100
+ } catch (err) {
101
+ const msg = err instanceof Error ? err.message : String(err);
102
+ const hint =
103
+ /\b40[45]\b/.test(msg)
104
+ ? " — this n8n build likely does not expose /api/v1/workflows/:id/execute; use mode='webhook' with the trigger node's webhook path instead"
105
+ : "";
106
+ return jsonToolResult({
107
+ ok: false,
108
+ mode: "workflow",
109
+ workflowId: wf.id,
110
+ workflowName: wf.name,
111
+ triggerNodeType: gate.triggerNodeType,
112
+ error: msg + hint,
113
+ });
114
+ }
115
+ }
116
+
117
+ if (!params.webhookPath) {
118
+ return jsonToolResult({
119
+ ok: false,
120
+ error: "webhookPath is required when mode=webhook",
121
+ });
122
+ }
123
+ const res = await client.postWebhook(params.webhookPath, params.payload, {
124
+ method: params.method,
125
+ });
126
+ return jsonToolResult({
127
+ ok: res.status >= 200 && res.status < 300,
128
+ mode: "webhook",
129
+ webhookPath: params.webhookPath,
130
+ method: params.method ?? "POST",
131
+ status: res.status,
132
+ response: res.body,
133
+ });
134
+ },
135
+ };
136
+ }
137
+
138
+ interface TriggerCheck {
139
+ ok: boolean;
140
+ reason?: string;
141
+ triggerNodeType?: string | null;
142
+ }
143
+
144
+ function checkTriggerable(wf: N8nWorkflow): TriggerCheck {
145
+ const triggerNode = findTriggerNode(wf);
146
+ const triggerNodeType = triggerNode?.type ?? null;
147
+ if (!wf.active) {
148
+ return {
149
+ ok: false,
150
+ reason: `workflow '${wf.name}' is not active; activate it in n8n before triggering`,
151
+ triggerNodeType,
152
+ };
153
+ }
154
+ if (!triggerNode) {
155
+ return {
156
+ ok: false,
157
+ reason: "workflow has no recognizable trigger node",
158
+ triggerNodeType,
159
+ };
160
+ }
161
+ if (!TRIGGER_ALLOWLIST.has(String(triggerNode.type))) {
162
+ return {
163
+ ok: false,
164
+ reason: `trigger node type '${triggerNode.type}' is not supported for external triggering (need webhook, manual, form, or executeWorkflow)`,
165
+ triggerNodeType,
166
+ };
167
+ }
168
+ return { ok: true, triggerNodeType };
169
+ }
170
+
171
+ function findTriggerNode(
172
+ wf: N8nWorkflow,
173
+ ): { type: string; name?: string } | null {
174
+ if (!Array.isArray(wf.nodes)) return null;
175
+ for (const raw of wf.nodes) {
176
+ if (!raw || typeof raw !== "object") continue;
177
+ const n = raw as Record<string, unknown>;
178
+ const type = typeof n.type === "string" ? n.type : "";
179
+ if (!type) continue;
180
+ if (type.toLowerCase().includes("trigger") || type === "n8n-nodes-base.webhook") {
181
+ return { type, name: typeof n.name === "string" ? n.name : undefined };
182
+ }
183
+ }
184
+ return null;
185
+ }
@@ -0,0 +1,214 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { N8nClient, N8nWorkflow } from "../client.ts";
3
+ import { jsonToolResult } from "./result.ts";
4
+
5
+ const Schema = Type.Object(
6
+ {
7
+ id: Type.String({
8
+ description: "Workflow id (from n8n_list_workflows).",
9
+ }),
10
+ },
11
+ { additionalProperties: false },
12
+ );
13
+
14
+ type Severity = "error" | "warning" | "info";
15
+
16
+ interface ValidationIssue {
17
+ severity: Severity;
18
+ code: string;
19
+ message: string;
20
+ nodeName?: string;
21
+ nodeType?: string;
22
+ }
23
+
24
+ const DEPRECATED_NODE_TYPES: Record<string, string> = {
25
+ "n8n-nodes-base.function": "n8n-nodes-base.code",
26
+ "n8n-nodes-base.functionItem": "n8n-nodes-base.code",
27
+ };
28
+
29
+ const TRIGGER_TYPE_MARKERS = [
30
+ "trigger",
31
+ "n8n-nodes-base.webhook",
32
+ "n8n-nodes-base.executeWorkflowTrigger",
33
+ ];
34
+
35
+ export function createValidateWorkflowTool(getClient: () => N8nClient) {
36
+ return {
37
+ name: "n8n_validate_workflow",
38
+ label: "n8n: validate workflow",
39
+ description:
40
+ "Static checks on a workflow: deprecated node types (function → code), old Code-node API usage ($node[], items global, require()), orphan nodes, disabled nodes, and missing trigger. Returns a list of issues with severity.",
41
+ parameters: Schema,
42
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
43
+ const { id } = rawParams as { id: string };
44
+ const wf = await getClient().getWorkflow(id);
45
+ const issues = validateWorkflow(wf);
46
+ const summary = summarize(issues);
47
+ return jsonToolResult({
48
+ workflowId: wf.id,
49
+ workflowName: wf.name,
50
+ active: wf.active,
51
+ nodeCount: Array.isArray(wf.nodes) ? wf.nodes.length : 0,
52
+ summary,
53
+ issues,
54
+ });
55
+ },
56
+ };
57
+ }
58
+
59
+ export function validateWorkflow(wf: N8nWorkflow): ValidationIssue[] {
60
+ const issues: ValidationIssue[] = [];
61
+ const nodes = Array.isArray(wf.nodes) ? wf.nodes : [];
62
+
63
+ const triggerNodes = nodes.filter((n) => isTriggerNode(n));
64
+ if (triggerNodes.length === 0) {
65
+ issues.push({
66
+ severity: "error",
67
+ code: "missing-trigger",
68
+ message: "Workflow has no trigger node and cannot be executed.",
69
+ });
70
+ }
71
+
72
+ const incoming = buildIncomingIndex(wf.connections);
73
+
74
+ for (const raw of nodes) {
75
+ if (!raw || typeof raw !== "object") continue;
76
+ const node = raw as Record<string, unknown>;
77
+ const name = typeof node.name === "string" ? node.name : "<unnamed>";
78
+ const type = typeof node.type === "string" ? node.type : "";
79
+ const disabled = node.disabled === true;
80
+
81
+ const replacement = DEPRECATED_NODE_TYPES[type];
82
+ if (replacement) {
83
+ issues.push({
84
+ severity: "warning",
85
+ code: "deprecated-node-type",
86
+ message: `Node type '${type}' is deprecated. Migrate to '${replacement}'.`,
87
+ nodeName: name,
88
+ nodeType: type,
89
+ });
90
+ }
91
+
92
+ if (type === "n8n-nodes-base.code" || type === "n8n-nodes-base.function") {
93
+ const codeIssues = checkCodeNode(node, name, type);
94
+ issues.push(...codeIssues);
95
+ }
96
+
97
+ if (disabled) {
98
+ issues.push({
99
+ severity: "info",
100
+ code: "disabled-node",
101
+ message: `Node '${name}' is disabled; downstream branches will be skipped.`,
102
+ nodeName: name,
103
+ nodeType: type,
104
+ });
105
+ }
106
+
107
+ if (!isTriggerNode(node) && !incoming.has(name)) {
108
+ issues.push({
109
+ severity: "warning",
110
+ code: "orphan-node",
111
+ message: `Node '${name}' has no incoming connections and is not a trigger. It will never execute.`,
112
+ nodeName: name,
113
+ nodeType: type,
114
+ });
115
+ }
116
+ }
117
+
118
+ return issues;
119
+ }
120
+
121
+ function checkCodeNode(
122
+ node: Record<string, unknown>,
123
+ name: string,
124
+ type: string,
125
+ ): ValidationIssue[] {
126
+ const issues: ValidationIssue[] = [];
127
+ const params = (node.parameters as Record<string, unknown>) ?? {};
128
+ const code = collectCodeStrings(params);
129
+ if (!code) return issues;
130
+
131
+ if (/\brequire\s*\(/.test(code)) {
132
+ issues.push({
133
+ severity: "warning",
134
+ code: "code-node-require",
135
+ message: `Code node '${name}' calls require(); n8n blocks this unless NODE_FUNCTION_ALLOW_EXTERNAL is set on the host.`,
136
+ nodeName: name,
137
+ nodeType: type,
138
+ });
139
+ }
140
+ if (/\$node\s*\[/.test(code)) {
141
+ issues.push({
142
+ severity: "warning",
143
+ code: "code-node-old-node-ref",
144
+ message: `Code node '${name}' uses $node[...] (legacy API). Prefer $('Node Name').`,
145
+ nodeName: name,
146
+ nodeType: type,
147
+ });
148
+ }
149
+ if (/(^|[^.\w$])items(\s*\[|\s*\.|\s*;|\s*\))/m.test(code)) {
150
+ issues.push({
151
+ severity: "warning",
152
+ code: "code-node-items-global",
153
+ message: `Code node '${name}' references the 'items' global (removed in n8n v1). Use $input.all() or $input.first().`,
154
+ nodeName: name,
155
+ nodeType: type,
156
+ });
157
+ }
158
+ return issues;
159
+ }
160
+
161
+ function collectCodeStrings(params: Record<string, unknown>): string {
162
+ const parts: string[] = [];
163
+ for (const key of ["jsCode", "functionCode", "code", "pythonCode"]) {
164
+ const v = params[key];
165
+ if (typeof v === "string") parts.push(v);
166
+ }
167
+ return parts.join("\n");
168
+ }
169
+
170
+ function buildIncomingIndex(connections: unknown): Set<string> {
171
+ const incoming = new Set<string>();
172
+ if (!connections || typeof connections !== "object") return incoming;
173
+ for (const outputs of Object.values(connections as Record<string, unknown>)) {
174
+ if (!outputs || typeof outputs !== "object") continue;
175
+ for (const outputBranches of Object.values(outputs as Record<string, unknown>)) {
176
+ if (!Array.isArray(outputBranches)) continue;
177
+ for (const branch of outputBranches) {
178
+ if (!Array.isArray(branch)) continue;
179
+ for (const edge of branch) {
180
+ if (edge && typeof edge === "object" && "node" in edge) {
181
+ const target = (edge as { node: unknown }).node;
182
+ if (typeof target === "string") incoming.add(target);
183
+ }
184
+ }
185
+ }
186
+ }
187
+ }
188
+ return incoming;
189
+ }
190
+
191
+ function isTriggerNode(raw: unknown): boolean {
192
+ if (!raw || typeof raw !== "object") return false;
193
+ const n = raw as Record<string, unknown>;
194
+ const type = typeof n.type === "string" ? n.type.toLowerCase() : "";
195
+ if (!type) return false;
196
+ return TRIGGER_TYPE_MARKERS.some((marker) => type.includes(marker));
197
+ }
198
+
199
+ function summarize(issues: ValidationIssue[]): {
200
+ errors: number;
201
+ warnings: number;
202
+ info: number;
203
+ ok: boolean;
204
+ } {
205
+ let errors = 0;
206
+ let warnings = 0;
207
+ let info = 0;
208
+ for (const i of issues) {
209
+ if (i.severity === "error") errors++;
210
+ else if (i.severity === "warning") warnings++;
211
+ else info++;
212
+ }
213
+ return { errors, warnings, info, ok: errors === 0 };
214
+ }