nodered-mcp-full 0.2.0 → 0.4.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.
Files changed (4) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +13 -5
  3. package/index.js +611 -36
  4. package/package.json +3 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1 (2026-11-17)
4
+ - get_errors: include_last_status:true adds nodes_in_error_now (nodes whose latest status is red) and last_status_seen (latest status per node seen by the monitor). Verified against real Node-RED: the comms channel has NO status replay on subscribe, so silent nodes appear only after they emit again.
5
+
6
+ ## 0.4.0 (2026-11-17)
7
+ - get_errors: live runtime error monitor via the editor /comms websocket (auth-packet login, status + notification subscriptions, auto-reconnect, heartbeat echo). Rolling 500-event buffer of red/yellow node statuses and error notifications with node name/type/tab resolved; filters: limit, tab_id, include_warnings, clear. No more SSH/docker to read why a node is in error.
8
+
9
+ ## 0.3.0 (2026-11-17)
10
+ - AI-first comprehension layer: get_flow_map (outline / mermaid / json, wiring resolved to node names), list_flows detail:true (type histogram, entry points, config refs, subflow instances), search_nodes (fields + function code), list_config_nodes (usage counts)
11
+ - Surgical writes: patch_batch (one deploy for many patches), upsert_node (auto id/position, optional wire_from), delete_node (+splice bypass) - the model sends only diffs, the server merges and deploys the full array
12
+ - Safety: dry_run with before/after diffs on every write tool, validate_flows standalone (duplicate ids, dangling wires, legacy HA v3 fields on v6 nodes, flow.get 'file' trap), get_flow compact/pagination, get_node resolve_refs
13
+ - 17 tools total; all v0.2 tools and behaviors preserved
14
+
3
15
  ## 0.1.0 (2026-11-06)
4
16
  - 10 tools: get_settings, list_flows, get_flow, get_node, patch_node, deploy_flows, call_endpoint, list_backups, restore_backup, list_node_types
5
17
  - Safe writes: confirm flag + automatic pre-deploy backups with rotation + one-command restore
package/README.md CHANGED
@@ -19,12 +19,20 @@ Built for real-world setups:
19
19
  | Tool | Description |
20
20
  |------|-------------|
21
21
  | `get_settings` | Runtime settings: version, palette editability, contextStorage — check limits first |
22
- | `list_flows` | All tabs with node counts and disabled flags |
23
- | `get_flow` | Nodes of one tab (by id), or the whole flow document |
24
- | `get_node` | Single node by id (full config, function code, wiring) |
25
- | `patch_node` | Merge fields into one node (func, wires, x/y, ...) — auto backup, needs `confirm:true` |
26
- | `deploy_flows` | Deploy a complete flow array — auto backup, needs `confirm:true` |
22
+ | `list_flows` | All tabs with node counts; `detail:true` adds type histogram, entry points (injects, mqtt topics, http endpoints, HA entities), config refs, subflow instances |
23
+ | `get_flow_map` | **AI-readable map of one tab/subflow**: `outline` (indented execution order, wiring resolved to names, config nodes inlined), `mermaid` (flowchart), `json` |
24
+ | `get_flow` | Nodes of one tab (by id), or the whole flow document; `compact:true` strips coordinates, `offset`/`limit` paginate |
25
+ | `get_node` | Single node by id (full config, function code, wiring); `resolve_refs:true` inlines referenced config nodes |
26
+ | `search_nodes` | Find nodes by text across name/type/topic/entity/url **and function code** (code matches with snippet) |
27
+ | `list_config_nodes` | Config nodes (brokers, HA servers, ui config) with usage counts |
28
+ | `patch_node` | Merge fields into one node (func, wires, x/y, ...) — `dry_run` preview, auto backup, needs `confirm:true` |
29
+ | `patch_batch` | Many node patches in ONE deploy — server merges + validates + backs up; you send only diffs |
30
+ | `upsert_node` | Create a node (auto id/position, optional `wire_from`) or update by id — needs `confirm:true` |
31
+ | `delete_node` | Delete a node and clean its wires; `splice:true` rewires inputs to outputs — needs `confirm:true` |
32
+ | `validate_flows` | Validate a candidate flow array without deploying (dup ids, dangling wires, legacy HA v3 fields, `flow.get(...,'file')` traps) |
33
+ | `deploy_flows` | Deploy a complete flow array — `dry_run` validation, auto backup, needs `confirm:true` |
27
34
  | `call_endpoint` | GET any HTTP endpoint served by your flows (custom diagnostics, APIs) |
35
+ | `get_errors` | **Live runtime errors/warnings**: red/yellow node statuses + error notifications from the editor comms channel, node and tab resolved - no SSH needed |
28
36
  | `list_backups` | List automatic pre-deploy backups |
29
37
  | `restore_backup` | Restore a backup in one command — needs `confirm:true` |
30
38
  | `list_node_types` | Installed palette modules and node types |
package/index.js CHANGED
@@ -1,6 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * nodered-mcp — MCP server for the Node-RED Admin API
3
+ * nodered-mcp-full - MCP server for the Node-RED Admin API
4
+ *
5
+ * v0.4.0 - get_errors: live runtime error monitor via the editor /comms websocket
6
+ * (red/yellow node statuses + error notifications, node/tab resolved)
7
+ * v0.3.0 - AI-first flow comprehension layer:
8
+ * - get_flow_map: tab/subflow rendered as outline or Mermaid, wiring resolved to names
9
+ * - list_flows detail, search_nodes, list_config_nodes
10
+ * - surgical writes: patch_batch, upsert_node, delete_node (+splice) - the model
11
+ * sends only diffs, the server merges and deploys the full array
12
+ * - validation + dry_run diffs on every write tool
4
13
  *
5
14
  * Generic, environment-driven. Works with:
6
15
  * - direct Node-RED (http/https)
@@ -18,6 +27,8 @@ import https from "node:https";
18
27
  import fs from "node:fs";
19
28
  import path from "node:path";
20
29
  import os from "node:os";
30
+ import crypto from "node:crypto";
31
+ import WebSocket from "ws";
21
32
 
22
33
  // ---------------- environment ----------------
23
34
  const URL_BASE = (process.env.NODE_RED_URL || "http://localhost:1880").replace(/\/+$/, "");
@@ -66,6 +77,114 @@ async function getToken(force) {
66
77
  });
67
78
  }
68
79
 
80
+ // ---------------- runtime error monitor (editor comms websocket) ----------------
81
+ // Connects to the same /comms websocket the Node-RED editor uses, authenticates
82
+ // with the admin token (auth packet), subscribes to status + notification and
83
+ // keeps a rolling buffer of red/yellow node statuses and error notifications.
84
+ const MONITOR_MAX = 500;
85
+ const monitor = { ws: null, state: "idle", since: null, buffer: [], lastFill: new Map(), lastStatus: new Map(), reconnectMs: 4000, reconnectTimer: null, closedByUs: false };
86
+ let nodeNames = null; let nodeNamesAt = 0;
87
+
88
+ function monitorRecord(kind, entry) {
89
+ monitor.buffer.push(Object.assign({ ts: Date.now(), kind }, entry));
90
+ if (monitor.buffer.length > MONITOR_MAX) monitor.buffer.splice(0, monitor.buffer.length - MONITOR_MAX);
91
+ }
92
+
93
+ async function nodeNameMap() {
94
+ if (nodeNames && Date.now() - nodeNamesAt < 60000) return nodeNames;
95
+ try {
96
+ const flows = await apiGetJson("/flows");
97
+ const tabs = new Map();
98
+ flows.forEach(function (f) { if (f.type === "tab") tabs.set(f.id, f.label || f.id); });
99
+ const map = new Map();
100
+ flows.forEach(function (f) {
101
+ if (f.type === "tab" || f.type === "subflow") return;
102
+ map.set(f.id, { name: f.name || f.type || f.id, type: f.type, tab_id: f.z || null, tab_label: f.z ? (tabs.get(f.z) || f.z) : "(config)" });
103
+ });
104
+ nodeNames = { map: map }; nodeNamesAt = Date.now();
105
+ return nodeNames;
106
+ } catch (e) { return nodeNames || { map: new Map() }; }
107
+ }
108
+
109
+ function monitorConnect() {
110
+ if (monitor.ws && (monitor.ws.readyState === 0 || monitor.ws.readyState === 1)) return;
111
+ monitor.closedByUs = false;
112
+ monitor.state = "connecting";
113
+ const wsUrl = URL_BASE.replace(/^http/, "ws") + "/comms";
114
+ let ws;
115
+ try { ws = new WebSocket(wsUrl, { headers: Object.assign({}, EXTRA_HEADERS), ca: ca || undefined, rejectUnauthorized: !INSECURE_TLS }); }
116
+ catch (e) { monitor.state = "error: " + e.message; scheduleReconnect(); return; }
117
+ ws.on("open", async function () {
118
+ monitor.ws = ws;
119
+ monitor.state = "authorizing";
120
+ try {
121
+ const t = AUTH_USER ? await getToken() : (TOKEN || "");
122
+ ws.send(JSON.stringify({ auth: t || "" }));
123
+ } catch (e) { monitor.state = "auth-error"; monitor.closedByUs = true; try { ws.close(); } catch (e2) {} }
124
+ });
125
+ ws.on("message", function (raw) {
126
+ let m; try { m = JSON.parse(raw.toString()); } catch (e) { return; }
127
+ if (m && m.auth) {
128
+ if (m.auth === "ok") {
129
+ monitor.state = "open"; monitor.since = Date.now();
130
+ try { ws.send(JSON.stringify({ subscribe: "status" })); ws.send(JSON.stringify({ subscribe: "notification" })); } catch (e) {}
131
+ } else { monitor.state = "auth-fail"; monitor.closedByUs = true; try { ws.close(); } catch (e) {} }
132
+ return;
133
+ }
134
+ const arr = Array.isArray(m) ? m : [m];
135
+ for (const one of arr) {
136
+ if (!one || typeof one !== "object") continue;
137
+ const topic = String(one.topic || "");
138
+ if (topic === "hb") { try { ws.send(JSON.stringify({ topic: "hb" })); } catch (e) {} continue; }
139
+ if (topic.indexOf("status/") === 0) {
140
+ const id = topic.slice(7);
141
+ const d = one.data || {};
142
+ if (d.fill) {
143
+ monitor.lastFill.set(id, d.fill);
144
+ monitor.lastStatus.set(id, { ts: Date.now(), fill: d.fill, shape: d.shape || null, text: String(d.text || "").slice(0, 200) });
145
+ if (monitor.lastStatus.size > 1000) {
146
+ const sorted = Array.from(monitor.lastStatus.entries()).sort(function (a, b) { return a[1].ts - b[1].ts; });
147
+ for (let i = 0; i < 200; i++) monitor.lastStatus.delete(sorted[i][0]);
148
+ }
149
+ }
150
+ if (d.fill === "red" || d.fill === "yellow") monitorRecord("status", { node_id: id, fill: d.fill, shape: d.shape || null, text: String(d.text || "") });
151
+ continue;
152
+ }
153
+ if (topic.indexOf("notification/") === 0) {
154
+ const d = one.data || {};
155
+ if (d && (d.type === "error" || d.type === "warning")) monitorRecord("notification", { level: d.type, text: String(d.text || "") });
156
+ continue;
157
+ }
158
+ }
159
+ });
160
+ ws.on("close", function () {
161
+ if (monitor.ws === ws) {
162
+ monitor.ws = null;
163
+ if (!monitor.closedByUs) { monitor.state = "reconnect-wait"; scheduleReconnect(); }
164
+ else monitor.state = "closed";
165
+ }
166
+ });
167
+ ws.on("error", function () { /* close handler reschedules */ });
168
+ }
169
+
170
+ function scheduleReconnect() {
171
+ if (monitor.reconnectTimer) return;
172
+ monitor.reconnectTimer = setTimeout(function () { monitor.reconnectTimer = null; monitorConnect(); }, monitor.reconnectMs);
173
+ }
174
+
175
+ async function ensureMonitor() {
176
+ if (monitor.ws && monitor.ws.readyState === 1) return;
177
+ if (monitor.ws && monitor.ws.readyState === 0) {
178
+ const t0 = Date.now();
179
+ while (Date.now() - t0 < 3000 && monitor.state !== "open") await new Promise(function (r) { setTimeout(r, 100); });
180
+ return;
181
+ }
182
+ if (AUTH_USER) { try { await getToken(true); } catch (e) { /* proceed, auth packet will fail visibly */ } }
183
+ monitorConnect();
184
+ const t0 = Date.now();
185
+ while (Date.now() - t0 < 4000 && monitor.state !== "open") await new Promise(function (r) { setTimeout(r, 100); });
186
+ }
187
+
69
188
  // ---------------- http client ----------------
70
189
  async function request(method, urlPath, body, extraHeaders) {
71
190
  const tk = await getToken(false);
@@ -87,8 +206,7 @@ async function request(method, urlPath, body, extraHeaders) {
87
206
  ca: ca || undefined,
88
207
  rejectUnauthorized: !INSECURE_TLS,
89
208
  }, (res) => {
90
- let data = "";
91
- res.setEncoding("utf8");
209
+ let data = ""; res.setEncoding("utf8");
92
210
  res.on("data", (c) => { data += c; });
93
211
  res.on("end", () => resolve({ status: res.statusCode, body: data }));
94
212
  });
@@ -148,65 +266,468 @@ async function deployFlows(flows) {
148
266
 
149
267
  function readOnlyError() { return "NODE_RED_READ_ONLY=true: write tools are disabled on this instance."; }
150
268
 
269
+ // ---------------- flow comprehension helpers ----------------
270
+ function buildIndex(flows) {
271
+ const byId = new Map();
272
+ for (const n of flows) if (n && n.id) byId.set(n.id, n);
273
+ return byId;
274
+ }
275
+ function shortId(id) { return String(id || "").slice(0, 8); }
276
+ function trunc(s, n) { s = String(s); return s.length <= n ? s : s.slice(0, n - 3) + "..."; }
277
+ function displayName(n) {
278
+ if (!n) return "?";
279
+ if (n.name && String(n.name).trim()) return String(n.name).trim();
280
+ if (n.type === "tab" || n.type === "subflow") return n.label || shortId(n.id);
281
+ return n.type + ":" + shortId(n.id);
282
+ }
283
+ function isConfigType(t) {
284
+ return t === "mqtt-broker" || t === "server" || t === "websocket-listener" || t === "websocket-client" || String(t).indexOf("ui_") === 0;
285
+ }
286
+ const ENTRY_TYPES = new Set(["inject", "mqtt in", "http in", "server-state-changed", "link in", "cronplus", "bigtimer", "poll-state", "websocket in", "udp in", "tcp in", "serial in"]);
287
+ const PARAM_SKIP = new Set(["id", "type", "name", "x", "y", "z", "w", "h", "g", "wires", "credentials", "env", "info", "func", "template", "rules", "status", "label", "icon", "order"]);
288
+
289
+ function paramLine(n, byId) {
290
+ const out = [];
291
+ const keys = Object.keys(n);
292
+ for (let i = 0; i < keys.length && out.length < 8; i++) {
293
+ const k = keys[i];
294
+ if (PARAM_SKIP.has(k)) continue;
295
+ const v = n[k];
296
+ if (v === "" || v === null || v === undefined || v === false) continue;
297
+ let s;
298
+ if (typeof v === "string") { s = byId && byId.has(v) ? displayName(byId.get(v)) + "(" + shortId(v) + ")" : trunc(v, 50); }
299
+ else if (typeof v === "number" || typeof v === "boolean") { s = String(v); }
300
+ else { s = trunc(JSON.stringify(v), 50); }
301
+ out.push(k + "=" + s);
302
+ }
303
+ if (typeof n.func === "string") out.push("func=" + n.func.split("\n").length + "L");
304
+ if (Array.isArray(n.rules)) out.push("rules=" + n.rules.length);
305
+ return out;
306
+ }
307
+
308
+ function outlineTab(flows, byId, containerId) {
309
+ const container = byId.get(containerId);
310
+ const nodes = flows.filter(function (n) { return n.z === containerId && n.type !== "tab"; });
311
+ const ids = new Set(nodes.map(function (n) { return n.id; }));
312
+ const indeg = new Map(); nodes.forEach(function (n) { indeg.set(n.id, 0); });
313
+ nodes.forEach(function (n) {
314
+ (n.wires || []).forEach(function (w) { (w || []).forEach(function (t) { if (ids.has(t) && t !== n.id) indeg.set(t, indeg.get(t) + 1); }); });
315
+ });
316
+ const depth = new Map();
317
+ const q = [];
318
+ nodes.forEach(function (n) { if (indeg.get(n.id) === 0) q.push([n, 0]); });
319
+ while (q.length) {
320
+ const it = q.shift(); const n = it[0]; const d = it[1];
321
+ if (depth.has(n.id)) continue;
322
+ depth.set(n.id, d);
323
+ (n.wires || []).forEach(function (w) { (w || []).forEach(function (t) { if (ids.has(t) && !depth.has(t) && t !== n.id) q.push([byId.get(t), d + 1]); }); });
324
+ }
325
+ const sorted = nodes.slice().sort(function (a, b) {
326
+ const da = depth.has(a.id) ? depth.get(a.id) : 99; const db = depth.has(b.id) ? depth.get(b.id) : 99;
327
+ if (da !== db) return da - db;
328
+ const ya = a.y || 0, yb = b.y || 0;
329
+ if (ya !== yb) return ya - yb;
330
+ return (a.x || 0) - (b.x || 0);
331
+ });
332
+ const disabledCount = nodes.filter(function (n) { return n.disabled; }).length;
333
+ const kind = container && container.type === "subflow" ? "subflow " : "tab ";
334
+ const lines = ["# " + kind + displayName(container) + " (id " + containerId + ", " + nodes.length + " nodes" + (disabledCount ? ", " + disabledCount + " disabled" : "") + ")"];
335
+ sorted.forEach(function (n) {
336
+ const d = depth.has(n.id) ? Math.min(depth.get(n.id), 8) : 0;
337
+ let label = n.type;
338
+ if (String(n.type).indexOf("subflow:") === 0) {
339
+ const def = byId.get(String(n.type).slice(9));
340
+ label = "subflow " + (def ? displayName(def) : String(n.type).slice(9));
341
+ }
342
+ const parts = [shortId(n.id), label];
343
+ if (n.name) parts.push(JSON.stringify(n.name));
344
+ if (n.disabled) parts.push("[disabled]");
345
+ const ps = paramLine(n, byId);
346
+ if (ps.length) parts.push("| " + ps.join(" "));
347
+ const outs = [];
348
+ (n.wires || []).forEach(function (w, i) {
349
+ const tg = (w || []).map(function (t) {
350
+ const tn = byId.get(t);
351
+ if (tn && ids.has(t)) return displayName(tn) + "(" + shortId(t) + ")";
352
+ if (tn) return "[ext] " + displayName(tn) + " (" + (tn.type === "tab" ? tn.label || "tab" : tn.type) + ")";
353
+ return "[missing:" + t + "]";
354
+ });
355
+ outs.push(((n.wires || []).length > 1 ? "[" + (i + 1) + "] " : "") + "-> " + (tg.join(", ") || "-"));
356
+ });
357
+ lines.push(" ".repeat(d) + parts.join(" ") + (outs.length ? " " + outs.join(" ") : ""));
358
+ });
359
+ return lines.join("\n");
360
+ }
361
+
362
+ function mermaidEscape(s) { return String(s).replace(/[\\"[\]"]/g, " ").replace(/[\r\n]+/g, " ").slice(0, 60); }
363
+ function mermaidTab(flows, byId, containerId) {
364
+ const nodes = flows.filter(function (n) { return n.z === containerId && n.type !== "tab"; });
365
+ const ids = new Set(nodes.map(function (n) { return n.id; }));
366
+ const mid = function (n) { return "n" + String(n.id).replace(/[^a-zA-Z0-9_]/g, "_"); };
367
+ const xid = function (t) { return "x" + String(t).replace(/[^a-zA-Z0-9_]/g, "_"); };
368
+ const lines = ["flowchart TD"];
369
+ nodes.forEach(function (n) {
370
+ let label = n.name ? n.name + " [" + n.type + "]" : n.type;
371
+ if (String(n.type).indexOf("subflow:") === 0) {
372
+ const def = byId.get(String(n.type).slice(9));
373
+ label = (n.name || (def ? displayName(def) : "subflow")) + " [subflow]";
374
+ }
375
+ if (n.disabled) label = label + " (disabled)";
376
+ lines.push(" " + mid(n) + '["' + mermaidEscape(label) + '"]');
377
+ });
378
+ const extDefs = new Map();
379
+ const edges = [];
380
+ nodes.forEach(function (n) {
381
+ (n.wires || []).forEach(function (w, i) {
382
+ (w || []).forEach(function (t) {
383
+ const tn = byId.get(t);
384
+ if (tn && ids.has(t)) {
385
+ edges.push(" " + mid(n) + ((n.wires || []).length > 1 ? " -->|out" + (i + 1) + "| " : " --> ") + mid(tn));
386
+ } else {
387
+ const k = xid(t);
388
+ if (!extDefs.has(k)) {
389
+ extDefs.set(k, " " + k + '["' + mermaidEscape(tn ? displayName(tn) + " (" + (tn.type === "tab" ? tn.label || "tab" : tn.type) + ")" : "missing " + String(t).slice(0, 12)) + '"]');
390
+ }
391
+ edges.push(" " + mid(n) + " -.-> " + k);
392
+ }
393
+ });
394
+ });
395
+ });
396
+ return lines.concat(Array.from(extDefs.values()), edges).join("\n");
397
+ }
398
+
399
+ function tabSummary(flows, byId, tab, detail) {
400
+ const nodes = flows.filter(function (n) { return n.z === tab.id && n.type !== "tab"; });
401
+ const base = { id: tab.id, label: tab.label || tab.id, disabled: !!tab.disabled, nodes: nodes.length, disabled_nodes: nodes.filter(function (n) { return n.disabled; }).length };
402
+ if (!detail) return base;
403
+ const types = {};
404
+ const entries = [];
405
+ const configs = {};
406
+ const sub = [];
407
+ nodes.forEach(function (n) {
408
+ types[n.type] = (types[n.type] || 0) + 1;
409
+ if (ENTRY_TYPES.has(n.type)) {
410
+ const e = { id: n.id, type: n.type, name: n.name || null };
411
+ ["topic", "url", "method", "repeat", "crontab", "entities", "entity_id", "entity"].forEach(function (k) { if (n[k] !== undefined && n[k] !== "") e[k] = n[k]; });
412
+ entries.push(e);
413
+ }
414
+ if (String(n.type).indexOf("subflow:") === 0) sub.push({ id: n.id, subflow: String(n.type).slice(9), name: n.name || null });
415
+ Object.keys(n).forEach(function (k) {
416
+ if (k === "wires" || k === "z" || k === "id") return;
417
+ const v = n[k];
418
+ if (typeof v !== "string") return;
419
+ const t = byId.get(v);
420
+ if (t && t.type !== "tab" && t.type !== "subflow" && String(t.type).indexOf("subflow:") !== 0 && (t.z === undefined || t.z === null || isConfigType(t.type))) configs[t.id] = displayName(t) + " (" + t.type + ", " + t.id + ")";
421
+ });
422
+ });
423
+ base.types = types;
424
+ base.entry_points = entries;
425
+ base.subflow_instances = sub;
426
+ base.config_refs = Object.values(configs);
427
+ return base;
428
+ }
429
+
430
+ function searchNodes(flows, a) {
431
+ const byId = buildIndex(flows);
432
+ const q = String(a.query || "").toLowerCase();
433
+ const limit = a.limit || 30;
434
+ const results = [];
435
+ const code = [];
436
+ flows.forEach(function (n) {
437
+ if (n.type === "tab") return;
438
+ if (a.type && n.type !== a.type && !(a.type === "subflow" && String(n.type).indexOf("subflow:") === 0)) return;
439
+ if (a.tab_id && n.z !== a.tab_id) return;
440
+ const tabNode = n.z ? byId.get(n.z) : null;
441
+ const tab = tabNode ? (tabNode.label || tabNode.name || tabNode.id) : (n.z || "config/global");
442
+ const hay = [n.id, n.type, n.name || "", n.topic || "", n.entity_id || "", n.url || ""].join(" ").toLowerCase();
443
+ let hit = hay.indexOf(q) >= 0;
444
+ let snippet = null;
445
+ if (!hit && typeof n.func === "string") {
446
+ const low = n.func.toLowerCase(); const i2 = low.indexOf(q);
447
+ if (i2 >= 0) snippet = trunc(n.func.slice(Math.max(0, i2 - 30), i2 + q.length + 30).replace(/[\r\n]+/g, " "), 90);
448
+ }
449
+ if (!hit && snippet === null) return;
450
+ const item = { id: n.id, type: n.type, name: n.name || null, tab: tab };
451
+ if (n.topic) item.topic = n.topic;
452
+ if (n.entity_id) item.entity_id = n.entity_id;
453
+ if (n.url) item.url = n.url;
454
+ if (n.disabled) item.disabled = true;
455
+ item.match = hit ? "fields" : "func";
456
+ if (snippet !== null) item.snippet = snippet;
457
+ (hit ? results : code).push(item);
458
+ });
459
+ return { query: a.query, matches: results.length + code.length, results: results.slice(0, limit), code_matches: code.slice(0, limit) };
460
+ }
461
+
462
+ // ---------------- validation + diff ----------------
463
+ function validateFlows(flows) {
464
+ const errors = []; const warnings = [];
465
+ if (!Array.isArray(flows)) return { ok: false, errors: ["flows must be an array"], warnings: warnings };
466
+ const ids = new Set();
467
+ flows.forEach(function (n) {
468
+ if (!n || typeof n !== "object") { errors.push("non-object entry in flows array"); return; }
469
+ if (!n.id) errors.push(String(n.type || "?") + " node missing id");
470
+ else if (ids.has(n.id)) errors.push("duplicate id " + n.id);
471
+ else ids.add(n.id);
472
+ if (!n.type) errors.push("node " + String(n.id) + " missing type");
473
+ });
474
+ flows.forEach(function (n) {
475
+ if (!n || !Array.isArray(n.wires)) return;
476
+ n.wires.forEach(function (w, i) {
477
+ if (!Array.isArray(w)) { errors.push(String(n.id) + " wires[" + i + "] is not an array"); return; }
478
+ (w || []).forEach(function (t) { if (!ids.has(t)) errors.push(String(n.id) + " wires[" + i + "] -> missing target " + String(t)); });
479
+ });
480
+ });
481
+ flows.forEach(function (n) {
482
+ if (n && n.z && !ids.has(n.z)) warnings.push(String(n.id) + " z=" + n.z + " not a known tab/subflow id (ok for scoped config nodes)");
483
+ });
484
+ flows.forEach(function (n) {
485
+ if (!n || typeof n !== "object") return;
486
+ if (n.type === "server-state-changed" && n.entityidfilter !== undefined && !n.entities) warnings.push(String(n.id) + " server-state-changed has legacy v3 field entityidfilter - contrib v6 expects entities.entity; the node may never fire");
487
+ if (typeof n.func === "string" && /flow\.get\([^)]*,\s*["']file["']\)/.test(n.func)) warnings.push(String(n.id) + " function uses flow.get(key, \"file\") - default instances have no file context store; use plain flow.get(key)");
488
+ });
489
+ return { ok: errors.length === 0, errors: errors, warnings: warnings };
490
+ }
491
+
492
+ function nodeDiff(before, after) {
493
+ const keys = new Set(Object.keys(before || {}));
494
+ Object.keys(after || {}).forEach(function (k) { keys.add(k); });
495
+ const out = [];
496
+ keys.forEach(function (k) {
497
+ const a = JSON.stringify(before ? before[k] : undefined);
498
+ const b = JSON.stringify(after ? after[k] : undefined);
499
+ if (a !== b) out.push(k + ": " + trunc(a, 90) + " -> " + trunc(b, 90));
500
+ });
501
+ return out;
502
+ }
503
+
504
+ function newId() { return crypto.randomBytes(8).toString("hex"); }
505
+ function removeNode(flows, nodeId) {
506
+ return flows.filter(function (n) { return n.id !== nodeId; }).map(function (n) {
507
+ if (!Array.isArray(n.wires)) return n;
508
+ const c = Object.assign({}, n);
509
+ c.wires = n.wires.map(function (w) { return (w || []).filter(function (t) { return t !== nodeId; }); });
510
+ return c;
511
+ });
512
+ }
513
+
151
514
  // ---------------- server ----------------
152
- const server = new McpServer({ name: "nodered-mcp", version: "0.1.0" });
515
+ const server = new McpServer({ name: "nodered-mcp", version: "0.4.1" });
153
516
  const log = (msg) => console.error("[nodered-mcp] " + msg);
154
517
  log("target " + URL_BASE + (TOKEN ? " (token)" : "") + (READ_ONLY ? " READ-ONLY" : ""));
155
518
 
156
- server.tool("get_settings", "Node-RED runtime settings (version, palette editability, contextStorage) — check limits before advanced work", {}, async () => {
519
+ server.tool("get_settings", "Node-RED runtime settings (version, palette editability, contextStorage) - check limits before advanced work", {}, async () => {
157
520
  const s = await apiGetJson("/settings");
158
521
  return { content: [{ type: "text", text: txt({ version: s.version, paletteEditable: s.paletteEditable ?? null, contextStorage: s.contextStorage ?? null, httpAdminRoot: s.httpAdminRoot ?? null }) }] };
159
522
  });
160
523
 
161
- server.tool("list_flows", "List flow tabs with node counts and disabled flags", {}, async () => {
524
+ server.tool("list_flows", "List flow tabs with node counts. detail:true adds per-tab node-type histogram, entry points (injects + intervals, mqtt topics, http endpoints, HA entities), config refs and subflow instances - the one-call overview of the whole instance.", { detail: z.boolean().optional() }, async ({ detail }) => {
162
525
  const flows = await apiGetJson("/flows");
163
- const tabs = flows.filter(n => n.type === "tab");
164
- const out = tabs.map(t => {
165
- const nodes = flows.filter(n => n.z === t.id);
166
- return { id: t.id, label: t.label, disabled: t.disabled || false, nodes: nodes.length, subflows: nodes.filter(n => n.type === "subflow").length };
167
- });
526
+ const byId = buildIndex(flows);
527
+ const tabs = flows.filter(function (n) { return n.type === "tab"; });
528
+ const out = tabs.map(function (t) { return tabSummary(flows, byId, t, !!detail); });
168
529
  return { content: [{ type: "text", text: txt(out) }] };
169
530
  });
170
531
 
171
- server.tool("get_flow", "Get nodes of one flow tab (by tab id) or the whole flow document", { tab_id: z.string().optional(), full: z.boolean().optional() }, async ({ tab_id, full }) => {
532
+ server.tool("get_flow_map", "Render one tab or subflow as an AI-readable map - use this FIRST to understand a flow before editing. format=outline (default): indented node lines in execution order, wiring resolved to node names (-> targets), config nodes inlined, functions summarized as line counts. format=mermaid: flowchart diagram. format=json: raw node array.", { tab_id: z.string(), format: z.enum(["outline", "mermaid", "json"]).optional() }, async ({ tab_id, format }) => {
533
+ const flows = await apiGetJson("/flows");
534
+ const byId = buildIndex(flows);
535
+ if (!byId.has(tab_id)) throw new Error("tab/subflow not found: " + tab_id + " (use list_flows for ids)");
536
+ const f = format || "outline";
537
+ if (f === "mermaid") return { content: [{ type: "text", text: txt(mermaidTab(flows, byId, tab_id)) }] };
538
+ if (f === "json") return { content: [{ type: "text", text: txt(flows.filter(function (n) { return n.z === tab_id; })) }] };
539
+ return { content: [{ type: "text", text: txt(outlineTab(flows, byId, tab_id)) }] };
540
+ });
541
+
542
+ server.tool("get_flow", "Get nodes of one flow tab (by tab id) or the whole flow document as JSON - for exact patching. compact:true strips x/y/w/h; offset/limit paginate large tabs. For understanding a flow prefer get_flow_map; for finding nodes prefer search_nodes.", {
543
+ tab_id: z.string().optional(), full: z.boolean().optional(), compact: z.boolean().optional(), offset: z.number().int().optional(), limit: z.number().int().optional()
544
+ }, async ({ tab_id, full, compact, offset, limit }) => {
172
545
  const flows = await apiGetJson("/flows");
173
- if (full || !tab_id) return { content: [{ type: "text", text: txt(flows) }] };
174
- const nodes = flows.filter(n => n.z === tab_id);
175
- return { content: [{ type: "text", text: txt(nodes) }] };
546
+ let out = full || !tab_id ? flows : flows.filter(function (n) { return n.z === tab_id; });
547
+ if (compact) out = out.map(function (n) { const c = Object.assign({}, n); delete c.x; delete c.y; delete c.w; delete c.h; return c; });
548
+ const total = out.length;
549
+ if (typeof offset === "number" || typeof limit === "number") {
550
+ const o = offset || 0;
551
+ const l = limit || Math.max(total - o, 0);
552
+ const page = out.slice(o, o + l);
553
+ return { content: [{ type: "text", text: txt({ total: total, offset: o, count: page.length, nodes: page }) }] };
554
+ }
555
+ return { content: [{ type: "text", text: txt(out) }] };
176
556
  });
177
557
 
178
- server.tool("get_node", "Get a single node by id (exact config, function code, wiring)", { node_id: z.string() }, async ({ node_id }) => {
558
+ server.tool("get_node", "Get a single node by id (exact config, function code, wiring). resolve_refs:true also inlines the config nodes it references (HA server, mqtt broker...).", { node_id: z.string(), resolve_refs: z.boolean().optional() }, async ({ node_id, resolve_refs }) => {
179
559
  const flows = await apiGetJson("/flows");
180
- const n = flows.find(x => x.id === node_id);
560
+ const n = flows.find(function (x) { return x.id === node_id; });
181
561
  if (!n) throw new Error("node not found: " + node_id);
182
- return { content: [{ type: "text", text: txt(n) }] };
562
+ let out = n;
563
+ if (resolve_refs) {
564
+ const byId = buildIndex(flows);
565
+ const refs = {};
566
+ Object.keys(n).forEach(function (k) {
567
+ if (k === "wires" || k === "z") return;
568
+ const v = n[k];
569
+ if (typeof v === "string" && v !== n.id && byId.has(v)) {
570
+ const t = byId.get(v);
571
+ if (t.type !== "tab" && t.type !== "subflow") refs[k] = t;
572
+ }
573
+ });
574
+ out = { node: n, refs: refs };
575
+ }
576
+ return { content: [{ type: "text", text: txt(out) }] };
183
577
  });
184
578
 
185
- server.tool("patch_node", "Patch one node by id (merge fields: func, wires, name, x, y, ...). Requires confirm:true. Takes automatic backup and deploys the full flow set.", {
186
- node_id: z.string(),
187
- patch: z.record(z.unknown()),
188
- confirm: z.boolean()
189
- }, async ({ node_id, patch, confirm }) => {
579
+ server.tool("search_nodes", "Find nodes by text across name, type, id, topic, entity, url AND function code (code matches returned separately with a snippet). Much cheaper than get_flow when hunting specific nodes. Optional type and tab_id filters; limit default 30.", {
580
+ query: z.string(), type: z.string().optional(), tab_id: z.string().optional(), limit: z.number().int().optional()
581
+ }, async (a) => {
582
+ const flows = await apiGetJson("/flows");
583
+ return { content: [{ type: "text", text: txt(searchNodes(flows, a)) }] };
584
+ });
585
+
586
+ server.tool("list_config_nodes", "List config nodes (mqtt brokers, HA servers, dashboard/ui config) with usage counts - who references each one.", {}, async () => {
587
+ const flows = await apiGetJson("/flows");
588
+ const byId = buildIndex(flows);
589
+ const cfgIds = new Set(flows.filter(function (n) {
590
+ return n.type !== "tab" && n.type !== "subflow" && String(n.type).indexOf("subflow:") !== 0 && (n.z === undefined || n.z === null || isConfigType(n.type));
591
+ }).map(function (n) { return n.id; }));
592
+ const users = new Map(); cfgIds.forEach(function (id2) { users.set(id2, 0); });
593
+ flows.forEach(function (n) {
594
+ if (cfgIds.has(n.id)) return;
595
+ Object.keys(n).forEach(function (k) {
596
+ if (k === "wires" || k === "z" || k === "id") return;
597
+ const v = n[k];
598
+ if (typeof v === "string" && cfgIds.has(v)) users.set(v, users.get(v) + 1);
599
+ });
600
+ });
601
+ const out = [];
602
+ cfgIds.forEach(function (id2) { const n = byId.get(id2); out.push({ id: id2, type: n.type, name: n.name || null, users: users.get(id2) }); });
603
+ out.sort(function (a, b) { return b.users - a.users; });
604
+ return { content: [{ type: "text", text: txt(out) }] };
605
+ });
606
+
607
+ server.tool("patch_node", "Patch ONE node by id (merge fields: func, wires, name, x, y, ...). dry_run:true previews diff + validation without writing. Applying requires confirm:true. Automatic backup + full-array deploy server-side.", {
608
+ node_id: z.string(), patch: z.record(z.unknown()), confirm: z.boolean().optional(), dry_run: z.boolean().optional()
609
+ }, async ({ node_id, patch, confirm, dry_run }) => {
190
610
  if (READ_ONLY) throw new Error(readOnlyError());
191
- if (!confirm) throw new Error("pass confirm:true to apply this patch");
192
611
  const flows = await apiGetJson("/flows");
193
- const i = flows.findIndex(x => x.id === node_id);
612
+ const i = flows.findIndex(function (x) { return x.id === node_id; });
194
613
  if (i < 0) throw new Error("node not found: " + node_id);
195
- flows[i] = Object.assign({}, flows[i], patch);
196
- const res = await deployFlows(flows);
197
- return { content: [{ type: "text", text: txt(Object.assign({ patched: node_id, fields: Object.keys(patch) }, res)) }] };
614
+ const merged = Object.assign({}, flows[i], patch);
615
+ const next = flows.slice(); next[i] = merged;
616
+ const val = validateFlows(next);
617
+ if (dry_run) return { content: [{ type: "text", text: txt({ dry_run: true, diff: nodeDiff(flows[i], merged), validation: val }) }] };
618
+ if (!confirm) throw new Error("pass confirm:true to apply this patch");
619
+ const res = await deployFlows(next);
620
+ return { content: [{ type: "text", text: txt(Object.assign({ patched: node_id, fields: Object.keys(patch), validation: val }, res)) }] };
198
621
  });
199
622
 
200
- server.tool("deploy_flows", "Deploy a FULL flow array (the only safe deploy type). Validates it is an array, takes automatic backup first. Requires confirm:true.", {
201
- flows: z.array(z.unknown()),
202
- confirm: z.boolean(),
203
- backup_label: z.string().optional()
204
- }, async ({ flows, confirm, backup_label }) => {
623
+ server.tool("patch_batch", "Apply several node patches in ONE deploy: patches=[{node_id, patch}, ...]. Server merges into the full flow set, validates, backs up and deploys once - you never send the whole array. dry_run:true previews all diffs. Applying requires confirm:true.", {
624
+ patches: z.array(z.object({ node_id: z.string(), patch: z.record(z.unknown()) })), confirm: z.boolean().optional(), dry_run: z.boolean().optional()
625
+ }, async ({ patches, confirm, dry_run }) => {
626
+ if (READ_ONLY) throw new Error(readOnlyError());
627
+ if (!Array.isArray(patches) || patches.length === 0) throw new Error("patches must be a non-empty array");
628
+ const flows = await apiGetJson("/flows");
629
+ const next = flows.slice();
630
+ const diffs = [];
631
+ for (const p of patches) {
632
+ const i = next.findIndex(function (x) { return x.id === p.node_id; });
633
+ if (i < 0) throw new Error("node not found: " + p.node_id);
634
+ const merged = Object.assign({}, next[i], p.patch);
635
+ diffs.push({ node_id: p.node_id, diff: nodeDiff(next[i], merged) });
636
+ next[i] = merged;
637
+ }
638
+ const val = validateFlows(next);
639
+ if (dry_run) return { content: [{ type: "text", text: txt({ dry_run: true, diffs: diffs, validation: val }) }] };
640
+ if (!confirm) throw new Error("pass confirm:true to apply these patches");
641
+ const res = await deployFlows(next);
642
+ return { content: [{ type: "text", text: txt(Object.assign({ patched: patches.length + " nodes", diffs: diffs, validation: val }, res)) }] };
643
+ });
644
+
645
+ server.tool("upsert_node", "Create a new node (auto id, z and position below the tab content) or update an existing one when node.id matches. Optional wire_from {node_id, output} appends this node to that output wire. dry_run:true previews. Applying requires confirm:true. Backup + full deploy server-side.", {
646
+ node: z.record(z.unknown()), tab_id: z.string().optional(), wire_from: z.object({ node_id: z.string(), output: z.number().int().optional() }).optional(), confirm: z.boolean().optional(), dry_run: z.boolean().optional()
647
+ }, async ({ node, tab_id, wire_from, confirm, dry_run }) => {
648
+ if (READ_ONLY) throw new Error(readOnlyError());
649
+ if (!node || typeof node !== "object" || !node.type) throw new Error("node.type is required");
650
+ const flows = await apiGetJson("/flows");
651
+ const byId = buildIndex(flows);
652
+ const exists = node.id && byId.has(node.id);
653
+ const next = flows.slice();
654
+ let action; let theNode;
655
+ if (exists) {
656
+ const i = next.findIndex(function (x) { return x.id === node.id; });
657
+ theNode = Object.assign({}, next[i], node);
658
+ next[i] = theNode; action = "updated";
659
+ } else {
660
+ const zid = tab_id || node.z || null;
661
+ if (!zid) throw new Error("tab_id required for new nodes");
662
+ if (!byId.has(zid)) throw new Error("tab/subflow not found: " + zid);
663
+ const inTab = flows.filter(function (n) { return n.z === zid && typeof n.y === "number"; });
664
+ const maxY = inTab.length ? Math.max.apply(null, inTab.map(function (n) { return n.y; })) : 100;
665
+ theNode = Object.assign({ id: newId(), x: 100, y: maxY + 100, wires: [] }, node, { z: zid });
666
+ next.push(theNode); action = "created";
667
+ }
668
+ if (wire_from) {
669
+ const wi = next.findIndex(function (x) { return x.id === wire_from.node_id; });
670
+ if (wi < 0) throw new Error("wire_from node not found: " + wire_from.node_id);
671
+ const src = Object.assign({}, next[wi]);
672
+ if (!Array.isArray(src.wires)) src.wires = [];
673
+ const o = wire_from.output || 0;
674
+ while (src.wires.length <= o) src.wires.push([]);
675
+ src.wires[o] = (src.wires[o] || []).concat([theNode.id]);
676
+ next[wi] = src;
677
+ }
678
+ const val = validateFlows(next);
679
+ if (dry_run) return { content: [{ type: "text", text: txt({ dry_run: true, action: action, node: theNode, validation: val }) }] };
680
+ if (!confirm) throw new Error("pass confirm:true to apply");
681
+ const res = await deployFlows(next);
682
+ return { content: [{ type: "text", text: txt(Object.assign({ action: action, node_id: theNode.id, validation: val }, res)) }] };
683
+ });
684
+
685
+ server.tool("delete_node", "Delete one node by id and clean every wire pointing to it. splice:true (single-output nodes only) rewires its inputs directly to its outputs - bypass semantics. dry_run:true previews. Applying requires confirm:true.", {
686
+ node_id: z.string(), splice: z.boolean().optional(), confirm: z.boolean().optional(), dry_run: z.boolean().optional()
687
+ }, async ({ node_id, splice, confirm, dry_run }) => {
688
+ if (READ_ONLY) throw new Error(readOnlyError());
689
+ const flows = await apiGetJson("/flows");
690
+ const n = flows.find(function (x) { return x.id === node_id; });
691
+ if (!n) throw new Error("node not found: " + node_id);
692
+ let next = flows.slice();
693
+ if (splice) {
694
+ if ((n.wires || []).length > 1) throw new Error("splice supports single-output nodes only");
695
+ const outs = (n.wires && n.wires[0]) || [];
696
+ next = next.map(function (m) {
697
+ if (!Array.isArray(m.wires)) return m;
698
+ const c = Object.assign({}, m);
699
+ c.wires = m.wires.map(function (w) {
700
+ const ix = (w || []).indexOf(node_id);
701
+ if (ix < 0) return w;
702
+ const nw = (w || []).slice();
703
+ nw.splice.apply(nw, [ix, 1].concat(outs));
704
+ return nw;
705
+ });
706
+ return c;
707
+ });
708
+ }
709
+ next = removeNode(next, node_id);
710
+ const val = validateFlows(next);
711
+ if (dry_run) return { content: [{ type: "text", text: txt({ dry_run: true, deleting: n, validation: val }) }] };
712
+ if (!confirm) throw new Error("pass confirm:true to delete");
713
+ const res = await deployFlows(next);
714
+ return { content: [{ type: "text", text: txt(Object.assign({ deleted: node_id, spliced: !!splice, validation: val }, res)) }] };
715
+ });
716
+
717
+ server.tool("deploy_flows", "Deploy a FULL flow array (the only safe deploy type). Validates it is an array, takes an automatic backup first. dry_run:true validates without deploying. Deploying requires confirm:true.", {
718
+ flows: z.array(z.unknown()), confirm: z.boolean().optional(), backup_label: z.string().optional(), dry_run: z.boolean().optional()
719
+ }, async ({ flows, confirm, backup_label, dry_run }) => {
205
720
  if (READ_ONLY) throw new Error(readOnlyError());
206
- if (!confirm) throw new Error("pass confirm:true to deploy");
207
721
  if (!Array.isArray(flows)) throw new Error("flows must be an array (the complete flow document)");
722
+ const val = validateFlows(flows);
723
+ if (dry_run) return { content: [{ type: "text", text: txt(Object.assign({ dry_run: true, nodes: flows.length }, val)) }] };
724
+ if (!confirm) throw new Error("pass confirm:true to deploy");
208
725
  const res = await deployFlows(flows);
209
- return { content: [{ type: "text", text: txt(res) }] };
726
+ return { content: [{ type: "text", text: txt(Object.assign({ validation: val }, res)) }] };
727
+ });
728
+
729
+ server.tool("validate_flows", "Validate a candidate full flow array WITHOUT deploying: duplicate ids, dangling wires, unknown z, legacy HA v3 fields on v6 contrib nodes, flow.get(key, \"file\") traps. Run it on any edit built by hand.", { flows: z.array(z.unknown()) }, async ({ flows }) => {
730
+ return { content: [{ type: "text", text: txt(validateFlows(flows)) }] };
210
731
  });
211
732
 
212
733
  server.tool("call_endpoint", "GET an HTTP endpoint served by Node-RED flows (e.g. custom diagnostic nodes). Path must start with /.", {
@@ -240,5 +761,59 @@ server.tool("list_node_types", "List installed palette modules and node types",
240
761
  return { content: [{ type: "text", text: txt(nodes.map(m => ({ module: m.module, version: m.version, types: m.types, local: m.local, disabled: m.disabled }))) }] };
241
762
  });
242
763
 
764
+ server.tool("get_errors", "Live runtime errors and warnings from the Node-RED editor comms channel: node statuses with red/yellow fill (e.g. 'Call-service error...', rejected commands) and runtime error notifications, with node name/type/tab resolved. The monitor connects on first call and keeps a rolling in-memory buffer (reconnects automatically); events are captured from the moment it first connects - there is no history before that. include_warnings:false hides yellow; tab_id filters one tab; clear:true empties the buffer after reading. include_last_status:true adds nodes_in_error_now (nodes whose latest status is red) and last_status_seen (latest status per node seen by the monitor - Node-RED has no status replay: silent nodes show nothing until they emit again).", {
765
+ limit: z.number().int().min(1).max(200).optional(),
766
+ tab_id: z.string().optional(),
767
+ include_warnings: z.boolean().optional(),
768
+ clear: z.boolean().optional(),
769
+ include_last_status: z.boolean().optional()
770
+ }, async ({ limit, tab_id, include_warnings, clear, include_last_status }) => {
771
+ await ensureMonitor();
772
+ const names = await nodeNameMap();
773
+ const wanted = limit || 30;
774
+ let seen = 0;
775
+ const entries = [];
776
+ const reversed = monitor.buffer.slice().reverse();
777
+ for (const e of reversed) {
778
+ if (entries.length >= wanted) break;
779
+ const isWarn = (e.kind === "status" && e.fill === "yellow") || (e.kind === "notification" && e.level === "warning");
780
+ if (include_warnings === false && isWarn) continue;
781
+ const info = e.node_id ? names.map.get(e.node_id) : null;
782
+ if (tab_id && (!info || (info.tab_id !== tab_id && info.tab_label !== tab_id))) continue;
783
+ entries.push({
784
+ time: new Date(e.ts).toISOString(),
785
+ kind: e.kind,
786
+ node_id: e.node_id || undefined,
787
+ node: info ? info.name : undefined,
788
+ node_type: info ? info.type : undefined,
789
+ tab: info ? info.tab_label : undefined,
790
+ fill: e.fill || undefined,
791
+ level: e.level || undefined,
792
+ still_current: e.kind === "status" ? ((monitor.lastStatus.get(e.node_id) || {}).fill) === e.fill : undefined,
793
+ text: e.text
794
+ });
795
+ }
796
+ if (clear) monitor.buffer.length = 0;
797
+ const out = {
798
+ monitor: { state: monitor.state, connected_since: monitor.since ? new Date(monitor.since).toISOString() : null, captured_events: monitor.buffer.length },
799
+ errors: entries
800
+ };
801
+ if (include_last_status) {
802
+ const seen = [];
803
+ const nowRed = [];
804
+ for (const [id, st] of monitor.lastStatus.entries()) {
805
+ const info = names.map.get(id);
806
+ if (tab_id && (!info || (info.tab_id !== tab_id && info.tab_label !== tab_id))) continue;
807
+ const row = { node_id: id, node: info ? info.name : undefined, node_type: info ? info.type : undefined, tab: info ? info.tab_label : undefined, fill: st.fill, shape: st.shape || undefined, text: st.text, seen_at: new Date(st.ts).toISOString() };
808
+ seen.push(row);
809
+ if (st.fill === "red") nowRed.push(row);
810
+ }
811
+ seen.sort(function (a, b) { return a.seen_at < b.seen_at ? 1 : -1; });
812
+ out.nodes_in_error_now = nowRed;
813
+ out.last_status_seen = seen.slice(0, 50);
814
+ }
815
+ return { content: [{ type: "text", text: txt(out) }] };
816
+ });
817
+
243
818
  await server.connect(new StdioServerTransport());
244
- log("ready: 10 tools");
819
+ log("ready: 18 tools (v0.4.1)");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nodered-mcp-full",
3
- "version": "0.2.0",
3
+ "version": "0.4.1",
4
4
  "description": "Full-featured MCP server for Node-RED: complete admin-API access for AI agents — read AND safe write (confirm + automatic backups + restore), env-driven for any setup: direct, reverse proxy with custom CA, adminAuth token, read-only mode.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,6 +23,7 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@modelcontextprotocol/sdk": "^1.0.0",
26
+ "ws": "^8.23.0",
26
27
  "zod": "^3.23.0"
27
28
  },
28
29
  "scripts": {
@@ -43,4 +44,4 @@
43
44
  "LICENSE",
44
45
  "CHANGELOG.md"
45
46
  ]
46
- }
47
+ }