nodered-mcp 1.0.0 → 1.0.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
@@ -22,3 +22,22 @@ The server uses stdio, so it can be connected to Claude Desktop, Cursor, VS Code
22
22
  ## Limits and privacy
23
23
 
24
24
  This project is intentionally narrow. It should be treated as a practical helper, not a complete certification or security audit. Check the implementation and the returned data before using it with sensitive material. Everything stays on your network.
25
+
26
+ <!-- paywall -->
27
+ ## Premium tools
28
+
29
+ These tools need a license key:
30
+
31
+ * `flow_graph_audit`
32
+ * `wiring_report`
33
+
34
+ Buy a key at https://mcp-marketplace.io/server/io-github-mrfentmen-nodered-mcp and set it in your MCP client config:
35
+
36
+ ```json
37
+ "env": { "MCP_LICENSE_KEY": "mcp_live_..." }
38
+ ```
39
+
40
+ The key is checked against MCP Marketplace, cached for 24 hours, and keeps
41
+ working offline once one check has succeeded. Every other tool on this server
42
+ stays free.
43
+ <!-- /paywall -->
package/dist/api.d.ts CHANGED
@@ -10,4 +10,17 @@ export interface Flow {
10
10
  export declare function listFlows(): Promise<Flow[]>;
11
11
  export declare function getFlow(id: string): Promise<Raw[]>;
12
12
  export declare function formatFlow(id: string, nodes: Raw[]): string;
13
+ /** The shape of a flow: node types, layout extent, disabled nodes, wire volume and how much inline code it carries. */
14
+ export declare function flowGraphAudit(args: {
15
+ flow: string;
16
+ }): Promise<string>;
17
+ /** The wiring topology: sources, sinks, the longest chain through the graph and where the fan-out concentrates. */
18
+ export declare function wiringReport(args: {
19
+ flow: string;
20
+ limit?: number;
21
+ }): Promise<string>;
22
+ /** Static lint over a flow before it is deployed: the problems Node-RED will complain about at import time. */
23
+ export declare function flowLint(args: {
24
+ flow: string;
25
+ }): Promise<string>;
13
26
  export {};
package/dist/api.js CHANGED
@@ -53,3 +53,211 @@ export function formatFlow(id, nodes) {
53
53
  const top = Object.entries(kinds).sort((a, b) => b[1] - a[1]).slice(0, 8);
54
54
  return [`Flow ${id} (${nodes.length} nodes):`, ...top.map(([k, v]) => `- ${k} x${v}`)].join("\n");
55
55
  }
56
+ function parseFlow(text) {
57
+ const clean = (text ?? '').trim();
58
+ if (!clean)
59
+ throw new NodeRedError('Provide a flow as the JSON array Node-RED exports, for example [{"id":"a1b2","type":"inject","z":"tab1","x":100,"y":100,"wires":[["c3d4"]]}].');
60
+ if (clean.length > 4 * 1024 * 1024)
61
+ throw new NodeRedError('That flow is larger than this server will parse.');
62
+ let value;
63
+ try {
64
+ value = JSON.parse(clean);
65
+ }
66
+ catch {
67
+ throw new NodeRedError('The flow is not valid JSON.');
68
+ }
69
+ if (!Array.isArray(value))
70
+ throw new NodeRedError('A Node-RED flow is a JSON array of node objects, not an object.');
71
+ return value;
72
+ }
73
+ function nodesOf(flow) {
74
+ return flow.filter((n) => typeof n.type === 'string' && n.type !== 'tab' && n.type !== 'comment');
75
+ }
76
+ function countBy(map, cap) {
77
+ if (!map.size)
78
+ return 'not reported';
79
+ return [...map.entries()]
80
+ .sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])))
81
+ .slice(0, cap)
82
+ .map(([k, n]) => `${k} x${n}`)
83
+ .join(', ');
84
+ }
85
+ /** The shape of a flow: node types, layout extent, disabled nodes, wire volume and how much inline code it carries. */
86
+ export async function flowGraphAudit(args) {
87
+ const flow = parseFlow(args.flow);
88
+ const nodes = nodesOf(flow);
89
+ const tabs = flow.filter((n) => n.type === 'tab');
90
+ if (!nodes.length)
91
+ return `That flow holds ${tabs.length} tab(s) and no nodes, so there is no graph to audit.`;
92
+ const kinds = new Map();
93
+ const tabsUsed = new Map();
94
+ let disabled = 0;
95
+ let wires = 0;
96
+ let functions = 0;
97
+ let funcChars = 0;
98
+ let withInfo = 0;
99
+ for (const n of nodes) {
100
+ const type = String(n.type);
101
+ kinds.set(type, (kinds.get(type) ?? 0) + 1);
102
+ tabsUsed.set(String(n.z ?? 'no tab'), (tabsUsed.get(String(n.z ?? 'no tab')) ?? 0) + 1);
103
+ if (n.d)
104
+ disabled += 1;
105
+ for (const group of n.wires ?? [])
106
+ wires += group.length;
107
+ if (type === 'function' || type === 'subflow' || type === 'template') {
108
+ functions += 1;
109
+ funcChars += String(n.func ?? '').length;
110
+ }
111
+ if (String(n.info ?? '').trim())
112
+ withInfo += 1;
113
+ }
114
+ const xs = nodes.map((n) => Number(n.x)).filter((n) => Number.isFinite(n));
115
+ const ys = nodes.map((n) => Number(n.y)).filter((n) => Number.isFinite(n));
116
+ return [
117
+ `Flow graph audit of a flow holding ${nodes.length} node(s) and ${tabs.length} tab(s)`,
118
+ `Node types: ${countBy(kinds, 12)}`,
119
+ `Nodes per tab: ${countBy(tabsUsed, 10)}${tabs.length ? ` (tabs: ${tabs.map((t) => String(t.label ?? t.id ?? 'id not reported')).slice(0, 6).join(', ')})` : ''}`,
120
+ `Disabled nodes: ${disabled} of ${nodes.length} (${((disabled / nodes.length) * 100).toFixed(1)}%)`,
121
+ `Wires: ${wires}, so ${(wires / nodes.length).toFixed(2)} per node`,
122
+ `Nodes carrying inline code (function, subflow, template): ${functions}, holding ${funcChars.toLocaleString()} character(s) of code in total`,
123
+ `Nodes carrying an info/comment field: ${withInfo} of ${nodes.length}`,
124
+ xs.length && ys.length
125
+ ? `Layout: x from ${Math.min(...xs)} to ${Math.max(...xs)} (${(Math.max(...xs) - Math.min(...xs)).toLocaleString()} wide), y from ${Math.min(...ys)} to ${Math.max(...ys)} (${(Math.max(...ys) - Math.min(...ys)).toLocaleString()} tall)`
126
+ : 'Layout: not reported, most nodes carry no x/y coordinates',
127
+ 'Inline code is measured by length only. Nothing here prints a function body, a credential or a config value.',
128
+ ].join('\n');
129
+ }
130
+ /** The wiring topology: sources, sinks, the longest chain through the graph and where the fan-out concentrates. */
131
+ export async function wiringReport(args) {
132
+ const flow = parseFlow(args.flow);
133
+ const nodes = nodesOf(flow);
134
+ const limit = Math.max(1, Math.min(Math.floor(args.limit ?? 6), 25));
135
+ if (!nodes.length)
136
+ return 'That flow holds no nodes, so there is nothing to trace.';
137
+ const byId = new Map(nodes.map((n) => [String(n.id), n]));
138
+ const outbound = new Map();
139
+ const inbound = new Map();
140
+ for (const n of nodes) {
141
+ for (const group of n.wires ?? []) {
142
+ for (const target of group) {
143
+ if (!outbound.has(String(n.id)))
144
+ outbound.set(String(n.id), []);
145
+ outbound.get(String(n.id))?.push(String(target));
146
+ if (!inbound.has(String(target)))
147
+ inbound.set(String(target), []);
148
+ inbound.get(String(target))?.push(String(n.id));
149
+ }
150
+ }
151
+ }
152
+ const sources = nodes.filter((n) => !(inbound.get(String(n.id)) ?? []).length);
153
+ const sinks = nodes.filter((n) => !(outbound.get(String(n.id)) ?? []).length);
154
+ const fanOut = [...outbound.entries()].sort((a, b) => b[1].length - a[1].length).slice(0, limit);
155
+ const fanIn = [...inbound.entries()].sort((a, b) => b[1].length - a[1].length).slice(0, limit).map(([id, from]) => [String(id), from.length]);
156
+ // Breadth first with a visited set: a Node-RED flow can hold a cycle, so
157
+ // depth here is the shortest distance from a source, which stays defined.
158
+ const depth = new Map();
159
+ const seen = new Set();
160
+ const queue = sources.map((n) => String(n.id));
161
+ for (const id of queue) {
162
+ depth.set(id, 1);
163
+ seen.add(id);
164
+ }
165
+ let guard = 0;
166
+ while (queue.length && guard < nodes.length + 1) {
167
+ guard += 1;
168
+ const id = queue.shift();
169
+ const d = depth.get(id) ?? 1;
170
+ for (const next of outbound.get(id) ?? []) {
171
+ if (seen.has(next))
172
+ continue;
173
+ seen.add(next);
174
+ depth.set(next, d + 1);
175
+ queue.push(next);
176
+ }
177
+ }
178
+ const deepest = Math.max(0, ...depth.values());
179
+ const cycles = [...outbound.entries()].filter(([id, targets]) => targets.some((t) => t === id || (outbound.get(t) ?? []).includes(id))).length;
180
+ const dangling = [...outbound.entries()]
181
+ .flatMap(([id, targets]) => targets.map((t) => ({ from: id, to: t })))
182
+ .filter((w) => !byId.has(w.to));
183
+ return [
184
+ `Wiring report for a flow of ${nodes.length} node(s)`,
185
+ `Wires: ${[...outbound.values()].reduce((sum, list) => sum + list.length, 0)}`,
186
+ `Nodes with no inbound wire (sources): ${sources.length}${sources.length ? ` (${sources.slice(0, limit).map((n) => `${n.type} ${n.name ?? n.id}`).join('; ')})` : ''}`,
187
+ `Nodes with no outbound wire (sinks): ${sinks.length}${sinks.length ? ` (${sinks.slice(0, limit).map((n) => `${n.type} ${n.name ?? n.id}`).join('; ')})` : ''}`,
188
+ `Longest shortest path from a source: ${deepest} node(s) deep, over ${seen.size} node(s) reachable from a source`,
189
+ `Node pairs that wire into each other: ${cycles}`,
190
+ `Widest fan-out: ${fanOut.length ? fanOut.map(([id, list]) => `${byId.get(id)?.type ?? id} ${byId.get(id)?.name ?? id} -> ${list.length}`).join('; ') : 'none'}`,
191
+ `Widest fan-in: ${fanIn.length ? fanIn.map(([id, n]) => `${byId.get(id)?.type ?? id} ${byId.get(id)?.name ?? id} <- ${n}`).join('; ') : 'none'}`,
192
+ `Wires pointing at an id that is not in this flow: ${dangling.length}${dangling.length ? ` (${dangling.slice(0, 5).map((w) => `${w.from} -> ${w.to}`).join('; ')})` : ''}`,
193
+ dangling.length ? 'A dangling wire is usually a node that was deleted without updating the wire, which Node-RED will reject on deploy.' : 'Every wire resolves to a node in this flow.',
194
+ ].join('\n');
195
+ }
196
+ /** Static lint over a flow before it is deployed: the problems Node-RED will complain about at import time. */
197
+ export async function flowLint(args) {
198
+ const flow = parseFlow(args.flow);
199
+ const findings = [];
200
+ const seen = new Map();
201
+ for (const n of flow) {
202
+ const id = String(n.id ?? '');
203
+ if (!id) {
204
+ findings.push(`A ${n.type ?? 'node of unknown type'} carries no id.`);
205
+ continue;
206
+ }
207
+ seen.set(id, (seen.get(id) ?? 0) + 1);
208
+ }
209
+ const duplicates = [...seen.entries()].filter(([, n]) => n > 1);
210
+ for (const [id, n] of duplicates)
211
+ findings.push(`Node id ${id} appears ${n} times, which is a duplicate.`);
212
+ const ids = new Set(seen.keys());
213
+ const nodes = nodesOf(flow);
214
+ let missingType = 0;
215
+ let emptyFunc = 0;
216
+ let emptyWires = 0;
217
+ let orphan = 0;
218
+ let dangling = 0;
219
+ for (const n of nodes) {
220
+ if (!String(n.type ?? '').trim())
221
+ missingType += 1;
222
+ const id = String(n.id);
223
+ const wiredOut = (n.wires ?? []).some((g) => g.length);
224
+ if (!String(n.name ?? '').trim() && String(n.type ?? '') === 'function')
225
+ findings.push(`A function node (${id}) has no name.`);
226
+ if (String(n.type ?? '') === 'function' && !String(n.func ?? '').trim())
227
+ emptyFunc += 1;
228
+ for (const group of n.wires ?? []) {
229
+ if (!group.length)
230
+ emptyWires += 1;
231
+ for (const t of group)
232
+ if (!ids.has(String(t)))
233
+ dangling += 1;
234
+ }
235
+ if (!wiredOut) {
236
+ const hasInbound = flow.some((other) => (other.wires ?? []).some((g) => g.includes(id)));
237
+ if (!hasInbound)
238
+ orphan += 1;
239
+ }
240
+ }
241
+ if (missingType)
242
+ findings.push(`${missingType} node(s) carry no type.`);
243
+ if (emptyFunc)
244
+ findings.push(`${emptyFunc} function node(s) have an empty body.`);
245
+ if (emptyWires)
246
+ findings.push(`${emptyWires} wires array(s) are present but empty.`);
247
+ if (dangling)
248
+ findings.push(`${dangling} wire target(s) name a node id that is not in the flow.`);
249
+ if (orphan)
250
+ findings.push(`${orphan} node(s) are wired to nothing in either direction.`);
251
+ const comments = flow.filter((n) => n.type === 'comment');
252
+ const commentsWithoutInfo = comments.filter((c) => !String(c.info ?? '').trim()).length;
253
+ if (commentsWithoutInfo)
254
+ findings.push(`${commentsWithoutInfo} comment node(s) carry no info text.`);
255
+ return [
256
+ `Lint of a flow holding ${flow.length} object(s), ${nodes.length} of them nodes and ${comments.length} comments`,
257
+ `Distinct node ids: ${seen.size}`,
258
+ findings.length
259
+ ? `Findings (${findings.length}): ${findings.slice(0, 12).join('; ')}${findings.length > 12 ? `; and ${findings.length - 12} more` : ''}`
260
+ : 'No findings: every node has an id and a type, every wire resolves, and no function body is empty.',
261
+ 'This is a structural lint of the JSON you supplied. It is not Node-RED own validator and it does not check whether a node type is installed.',
262
+ ].join('\n');
263
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Returns null when the caller may run the tool, or a short message telling
3
+ * them how to get a key.
4
+ *
5
+ * A good key is remembered for an hour, so a busy session does not hit the
6
+ * license server on every call and keeps working through a brief outage.
7
+ */
8
+ export declare function premiumRequired(tool: string): Promise<string | null>;
@@ -0,0 +1,79 @@
1
+ // Premium tools on this server need a license key bought from MCP Marketplace.
2
+ // Buyers put the key in their MCP client config as MCP_LICENSE_KEY. Every tool
3
+ // that is not listed in PREMIUM keeps working without a key.
4
+ const SLUG = "nodered-mcp";
5
+ // Tools that need a key. Everything else is free.
6
+ const PREMIUM = new Set([
7
+ "flow_graph_audit",
8
+ "wiring_report",
9
+ ]);
10
+ const BUY_URL = `https://mcp-marketplace.io/server/io-github-mrfentmen-${SLUG}`;
11
+ // The license check calls the marketplace's verify endpoint directly instead of
12
+ // using @mcp_marketplace/license. That SDK sends no `apikey` header, so every
13
+ // check it makes is rejected by Supabase before it reaches the function. The
14
+ // publishable key below is public by design - it ships in mcp-marketplace.io's
15
+ // own JavaScript and only ever reaches their licence check.
16
+ const DEFAULT_VERIFY_URL = "https://virupvwhtkpkjsiskckg.supabase.co/functions/v1/verify-key";
17
+ const PUBLISHABLE_KEY = "sb_publishable_BuqlW96Ke8C_zzJG-LQv1Q_YHi_r_4h";
18
+ const OK_CACHE_MS = 60 * 60 * 1000;
19
+ const BAD_CACHE_MS = 60 * 1000;
20
+ const seen = new Map();
21
+ const REASONS = {
22
+ missing_key: "no key is set",
23
+ invalid_format: "that key is not a valid MCP Marketplace key",
24
+ not_found: "that key was not found",
25
+ revoked: "that key has been revoked",
26
+ rotated: "that key was rotated, use your new one",
27
+ expired: "that key has expired, renew it",
28
+ rate_limited: "there were too many checks just now, try again shortly",
29
+ network_error: "the license server could not be reached",
30
+ };
31
+ function blocked(tool, reason) {
32
+ const why = REASONS[reason] ?? `the license server answered "${reason}"`;
33
+ return `"${tool}" needs a license key, but ${why}. ` +
34
+ `Set MCP_LICENSE_KEY in your MCP client config. Get a key: ${BUY_URL}`;
35
+ }
36
+ async function verify(key) {
37
+ const res = await fetch(process.env.MCP_LICENSE_VERIFY_URL || DEFAULT_VERIFY_URL, {
38
+ method: "POST",
39
+ headers: {
40
+ apikey: PUBLISHABLE_KEY,
41
+ Authorization: `Bearer ${PUBLISHABLE_KEY}`,
42
+ "Content-Type": "application/json",
43
+ },
44
+ body: JSON.stringify({ key, slug: SLUG }),
45
+ // an unusable key answers 400 with a JSON body, so read the body either way
46
+ signal: AbortSignal.timeout(15000),
47
+ });
48
+ const data = (await res.json());
49
+ if (typeof data?.valid !== "boolean")
50
+ return { valid: false, reason: "unexpected_response" };
51
+ return data;
52
+ }
53
+ /**
54
+ * Returns null when the caller may run the tool, or a short message telling
55
+ * them how to get a key.
56
+ *
57
+ * A good key is remembered for an hour, so a busy session does not hit the
58
+ * license server on every call and keeps working through a brief outage.
59
+ */
60
+ export async function premiumRequired(tool) {
61
+ if (!PREMIUM.has(tool))
62
+ return null;
63
+ const key = process.env.MCP_LICENSE_KEY;
64
+ if (!key)
65
+ return blocked(tool, "missing_key");
66
+ const hit = seen.get(key);
67
+ if (hit && Date.now() - hit.at < (hit.valid ? OK_CACHE_MS : BAD_CACHE_MS)) {
68
+ return hit.valid ? null : blocked(tool, hit.reason ?? "invalid");
69
+ }
70
+ let result;
71
+ try {
72
+ result = await verify(key);
73
+ }
74
+ catch {
75
+ result = { valid: false, reason: "network_error" };
76
+ }
77
+ seen.set(key, { ...result, at: Date.now() });
78
+ return result.valid ? null : blocked(tool, result.reason ?? "invalid");
79
+ }
package/dist/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
- import { formatFlow, getFlow, listFlows, NodeRedError } from "./api.js";
3
+ import { formatFlow, getFlow, listFlows, NodeRedError, flowGraphAudit, wiringReport, flowLint } from "./api.js";
4
+ import { premiumRequired } from "./license.js";
4
5
  const text = (t) => ({ content: [{ type: "text", text: t }] });
5
6
  const textError = (t) => ({ content: [{ type: "text", text: t }], isError: true });
6
7
  const READ_ONLY = { readOnlyHint: true, openWorldHint: true };
@@ -40,6 +41,55 @@ export function createServer() {
40
41
  return textError(errorMessage(e));
41
42
  }
42
43
  });
44
+ server.registerTool("flow_graph_audit", {
45
+ title: "Flow graph audit",
46
+ description: "Audit the shape of a Node-RED flow you supply as JSON: node type breakdown, nodes per tab, how many are disabled, wire volume per node, how much inline function, subflow and template code it carries, how many nodes have an info comment, and the layout bounding box. Code is measured by length only, never printed.",
47
+ inputSchema: z.object({ flow: z.string().describe("The flow as the JSON array Node-RED exports, up to 4 MB.") }),
48
+ annotations: READ_ONLY,
49
+ }, async (args) => {
50
+ // ---- paywall: flow_graph_audit ----
51
+ const paywallMessage = await premiumRequired("flow_graph_audit");
52
+ if (paywallMessage)
53
+ return { content: [{ type: "text", text: paywallMessage }], isError: true };
54
+ // ---- paywall: end ----
55
+ try {
56
+ return text(await flowGraphAudit(args));
57
+ }
58
+ catch (e) {
59
+ return textError(errorMessage(e));
60
+ }
61
+ });
62
+ server.registerTool("wiring_report", {
63
+ title: "Wiring report",
64
+ description: "Trace the wiring topology of a Node-RED flow you supply as JSON: the wire count, the nodes with no inbound wire and the nodes with no outbound wire, the longest chain from a source to a sink, where fan-out and fan-in concentrate, and any wire pointing at a node id the flow does not contain.",
65
+ inputSchema: z.object({ flow: z.string().describe("The flow as the JSON array Node-RED exports."), limit: z.number().describe("Entries to list per section, 1-25.").optional() }),
66
+ annotations: READ_ONLY,
67
+ }, async (args) => {
68
+ // ---- paywall: wiring_report ----
69
+ const paywallMessage = await premiumRequired("wiring_report");
70
+ if (paywallMessage)
71
+ return { content: [{ type: "text", text: paywallMessage }], isError: true };
72
+ // ---- paywall: end ----
73
+ try {
74
+ return text(await wiringReport(args));
75
+ }
76
+ catch (e) {
77
+ return textError(errorMessage(e));
78
+ }
79
+ });
80
+ server.registerTool("flow_lint", {
81
+ title: "Flow lint",
82
+ description: "Static lint of a Node-RED flow before deploy: duplicate node ids, nodes with no type, function nodes with an empty body, wires naming an id the flow does not contain, nodes wired to nothing in either direction, unnamed function nodes, and comments with no text.",
83
+ inputSchema: z.object({ flow: z.string().describe("The flow as the JSON array Node-RED exports.") }),
84
+ annotations: READ_ONLY,
85
+ }, async (args) => {
86
+ try {
87
+ return text(await flowLint(args));
88
+ }
89
+ catch (e) {
90
+ return textError(errorMessage(e));
91
+ }
92
+ });
43
93
  return server;
44
94
  }
45
95
  function errorMessage(e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nodered-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "MCP server for Node-RED: flows, nodes. Works with any instance.",
5
5
  "type": "module",
6
6
  "mcpName": "io.github.mrfentmen/nodered-mcp",