@gmag11/nodered-mcp-server 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.
Files changed (89) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +162 -0
  3. package/index.js +133 -0
  4. package/package.json +58 -0
  5. package/resources/skills/nodered-flow-builder/SKILL.md +659 -0
  6. package/resources/skills/nodered-flow-layout/SKILL.md +395 -0
  7. package/resources/skills/nodered-flowfuse-dashboard/SKILL.md +941 -0
  8. package/resources/skills/nodered-fundamentals/SKILL.md +323 -0
  9. package/resources/skills/nodered-jsonata/SKILL.md +1039 -0
  10. package/resources/skills/nodered-mustache/SKILL.md +588 -0
  11. package/resources/skills/nodered-node-reference/SKILL.md +1020 -0
  12. package/resources/skills/nodered-node-reference/examples/common.json +113 -0
  13. package/resources/skills/nodered-node-reference/examples/network.json +107 -0
  14. package/resources/skills/nodered-node-reference/examples/parser.json +147 -0
  15. package/resources/skills/nodered-node-reference/examples/sequence.json +141 -0
  16. package/resources/skills/nodered-node-reference/examples/storage.json +104 -0
  17. package/resources/skills/nodered-patterns/SKILL.md +414 -0
  18. package/resources/skills/nodered-patterns/examples/error-handler.json +72 -0
  19. package/resources/skills/nodered-patterns/examples/http-endpoint.json +42 -0
  20. package/resources/skills/nodered-patterns/examples/mqtt-subscriber.json +47 -0
  21. package/resources/skills/nodered-patterns/examples/timer-flow.json +50 -0
  22. package/resources/skills/nodered-subflows/SKILL.md +261 -0
  23. package/resources/skills/nodered-uibuilder/SKILL.md +500 -0
  24. package/src/auth/api-key-verifier.js +36 -0
  25. package/src/auth/composite-verifier.js +59 -0
  26. package/src/auth/config.js +106 -0
  27. package/src/auth/oauth-clients-store.js +107 -0
  28. package/src/auth/oauth-provider.js +149 -0
  29. package/src/auth/oauth-token-store.js +312 -0
  30. package/src/nodered/auth.js +158 -0
  31. package/src/nodered/client.js +199 -0
  32. package/src/nodered/comms-client.js +500 -0
  33. package/src/renderer/colors.js +161 -0
  34. package/src/renderer/geometry.js +115 -0
  35. package/src/renderer/html-builder.js +571 -0
  36. package/src/renderer/index.js +51 -0
  37. package/src/renderer/ir-builder.js +161 -0
  38. package/src/renderer/layout.js +126 -0
  39. package/src/renderer/mermaid-builder.js +109 -0
  40. package/src/renderer/svg-builder.js +228 -0
  41. package/src/schemas/responses.js +283 -0
  42. package/src/server.js +844 -0
  43. package/src/skills/loader.js +84 -0
  44. package/src/staging-store.js +258 -0
  45. package/src/tools/add-nodes-to-group.js +216 -0
  46. package/src/tools/connect-nodes.js +115 -0
  47. package/src/tools/constants.js +45 -0
  48. package/src/tools/create-flow.js +87 -0
  49. package/src/tools/create-node.js +126 -0
  50. package/src/tools/create-subflow-instance.js +123 -0
  51. package/src/tools/create-subflow.js +101 -0
  52. package/src/tools/delete-context.js +60 -0
  53. package/src/tools/delete-flow.js +81 -0
  54. package/src/tools/delete-group.js +116 -0
  55. package/src/tools/delete-node.js +73 -0
  56. package/src/tools/delete-subflow.js +103 -0
  57. package/src/tools/deploy.js +94 -0
  58. package/src/tools/disconnect-nodes.js +158 -0
  59. package/src/tools/export-flow.js +161 -0
  60. package/src/tools/export-subflow.js +78 -0
  61. package/src/tools/flow-utils.js +376 -0
  62. package/src/tools/get-config-nodes.js +86 -0
  63. package/src/tools/get-context.js +76 -0
  64. package/src/tools/get-flow-diagram.js +99 -0
  65. package/src/tools/get-flow-nodes.js +116 -0
  66. package/src/tools/get-flows.js +74 -0
  67. package/src/tools/get-node-detail.js +77 -0
  68. package/src/tools/get-node-type-detail.js +92 -0
  69. package/src/tools/get-palette-nodes.js +63 -0
  70. package/src/tools/get-staging-status.js +34 -0
  71. package/src/tools/get-subflow-detail.js +110 -0
  72. package/src/tools/get-subflows.js +105 -0
  73. package/src/tools/import-flow.js +310 -0
  74. package/src/tools/inject-message.js +117 -0
  75. package/src/tools/install-node.js +31 -0
  76. package/src/tools/read-debug-messages.js +155 -0
  77. package/src/tools/refresh-staging.js +62 -0
  78. package/src/tools/remove-nodes-from-group.js +162 -0
  79. package/src/tools/render-staging.js +69 -0
  80. package/src/tools/response-utils.js +42 -0
  81. package/src/tools/search-nodes.js +134 -0
  82. package/src/tools/uninstall-node.js +31 -0
  83. package/src/tools/update-flow.js +95 -0
  84. package/src/tools/update-group.js +77 -0
  85. package/src/tools/update-node.js +132 -0
  86. package/src/tools/update-subflow.js +84 -0
  87. package/src/transport/http.js +252 -0
  88. package/src/transport/stdio.js +16 -0
  89. package/src/transport/ws-server.js +223 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 gmag11
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,162 @@
1
+ # NodeRed-MCP
2
+
3
+ > **⚠️ IMPORTANT DISCLAIMER**
4
+ >
5
+ > This MCP server provides **programmatic, unattended access** to a Node-RED instance's Admin API. An AI agent using this server can create, modify, delete flows, inject messages, and execute arbitrary code through Function nodes — including operations that can disrupt or permanently damage your Node-RED environment and its connected systems.
6
+ >
7
+ > **This software is NOT designed or tested for production environments.** It is intended for development, experimentation, and learning purposes only.
8
+ >
9
+ > By using this software you acknowledge that:
10
+ > - **Use at your own risk.** The authors and contributors provide NO warranty, express or implied, and accept NO liability for any direct or indirect damages, data loss, service disruption, or security incidents resulting from its use.
11
+ > - You are **solely responsible** for:
12
+ > - Restricting network access to the MCP server
13
+ > - Configuring authentication (`MCP_API_KEY` or `MCP_OAUTH_ENABLED`)
14
+ > - Validating that the AI agent's actions are safe before deploying
15
+ > - Maintaining backups of your flows
16
+ > - **Never expose this server to the public internet** without a reverse proxy, strong authentication, and TLS.
17
+ > - **Never grant this server access to a Node-RED instance that contains sensitive data, business-critical flows, or production infrastructure.**
18
+ >
19
+ > If you choose to run this server, you do so entirely at your own risk.
20
+
21
+ MCP (Model Context Protocol) server for controlling Node-RED instances via the Admin API. Connects LLM-powered tools to Node-RED flows.
22
+
23
+ ## Quick Start
24
+
25
+ ```bash
26
+ cp .env.example .env
27
+ # Edit .env with your Node-RED URL
28
+ npm install
29
+ npm run start:http
30
+ ```
31
+
32
+ ## Authentication
33
+
34
+ The MCP server supports two authentication methods for the HTTP transport. Both are optional — if neither is configured, the server runs open (backward compatible).
35
+
36
+ ### API Key (recommended for most deployments)
37
+
38
+ Set the `MCP_API_KEY` environment variable:
39
+
40
+ ```bash
41
+ # Generate a secure key
42
+ openssl rand -hex 32
43
+
44
+ # Add to .env
45
+ MCP_API_KEY=your-generated-key
46
+ ```
47
+
48
+ Clients must include the key as a Bearer token:
49
+
50
+ ```
51
+ Authorization: Bearer your-generated-key
52
+ ```
53
+
54
+ ### OAuth 2.0 (for multi-client deployments)
55
+
56
+ Enable OAuth 2.0 with dynamic client registration and PKCE:
57
+
58
+ ```bash
59
+ MCP_OAUTH_ENABLED=true
60
+ MCP_OAUTH_ISSUER_URL=https://your-server.example.com
61
+ ```
62
+
63
+ The server exposes standard OAuth endpoints:
64
+
65
+ | Endpoint | Description |
66
+ |---|---|
67
+ | `POST /register` | Dynamic client registration |
68
+ | `GET /authorize` | Authorization code flow (PKCE) |
69
+ | `POST /token` | Token issuance and refresh |
70
+ | `POST /revoke` | Token revocation |
71
+ | `GET /.well-known/oauth-authorization-server` | RFC 8414 metadata |
72
+ | `GET /.well-known/oauth-protected-resource/mcp` | RFC 9728 metadata |
73
+
74
+ MCP clients discover OAuth automatically via the well-known endpoints — no manual configuration needed beyond the server URL.
75
+
76
+ ### Both methods
77
+
78
+ When both `MCP_API_KEY` and `MCP_OAUTH_ENABLED=true` are configured, either a valid API key or a valid OAuth access token grants access.
79
+
80
+ ### No authentication
81
+
82
+ When neither `MCP_API_KEY` nor `MCP_OAUTH_ENABLED` is configured, the server operates without authentication (useful for local development).
83
+
84
+ ## Connecting to a Node-RED Instance
85
+
86
+ This section covers how the MCP server authenticates **to** the Node-RED Admin API — not to be confused with the [MCP server authentication](#authentication) section above, which protects access **to** the MCP server itself.
87
+
88
+ The client auto-detects the auth mode by calling `GET /auth/login` on startup, unless `NODERED_API_KEY` is set (which skips detection).
89
+
90
+ ### No authentication
91
+
92
+ If your Node-RED instance has no `adminAuth` configured, no extra variables are needed.
93
+
94
+ ### Standard credentials (`type: "credentials"`)
95
+
96
+ Set username and password. The client calls `POST /auth/token` with the `password` grant to obtain a Bearer token.
97
+
98
+ ```env
99
+ NODERED_USERNAME=admin
100
+ NODERED_PASSWORD=your-password
101
+ ```
102
+
103
+ ### OIDC / custom strategies (`type: "oidc"` or similar)
104
+
105
+ OIDC uses the **authorization code flow with PKCE**, which requires a browser — the MCP server is headless and cannot complete that flow interactively.
106
+
107
+ The supported approach is to **add an API key alongside OIDC** in your Node-RED `settings.js` using the `tokens` function:
108
+
109
+ ```js
110
+ adminAuth: {
111
+ type: "oidc",
112
+ // ... your OIDC provider config ...
113
+ tokens: async (token) => {
114
+ if (token === "mcp-server-secret-key-here") {
115
+ return { username: "mcp-server", scope: "*" }
116
+ }
117
+ return null
118
+ }
119
+ }
120
+ ```
121
+
122
+ Then configure the MCP server:
123
+
124
+ ```env
125
+ NODERED_API_KEY=mcp-server-secret-key-here
126
+ ```
127
+
128
+ When `NODERED_API_KEY` is set, the client skips the auto-detection call and uses it directly as a Bearer token on every request.
129
+
130
+ ### API key natively (`NODERED_API_KEY`)
131
+
132
+ If your Node-RED instance already exposes an API key (e.g., via the `tokens` function or a custom strategy), just set:
133
+
134
+ ```env
135
+ NODERED_API_KEY=your-api-key
136
+ ```
137
+
138
+ > **Note**: `NODERED_API_KEY` takes priority over `NODERED_USERNAME`/`NODERED_PASSWORD`. If both are set, the API key is used.
139
+
140
+ ## Configuration Reference
141
+
142
+ | Variable | Required | Default | Description |
143
+ |---|---|---|---|
144
+ | `NODERED_URL` | **Yes** | — | Node-RED instance URL |
145
+ | `NODERED_USERNAME` | No | — | Node-RED credentials auth (`type: "credentials"`) |
146
+ | `NODERED_PASSWORD` | No | — | Node-RED credentials auth (`type: "credentials"`) |
147
+ | `NODERED_API_KEY` | No | — | Node-RED API key auth (OIDC, custom strategies, or native API key) |
148
+ | `MCP_HTTP_PORT` | No | `3000` | HTTP transport port |
149
+ | `MCP_API_KEY` | No | — | API key for MCP server auth |
150
+ | `MCP_OAUTH_ENABLED` | No | `false` | Enable OAuth 2.0 server |
151
+ | `MCP_OAUTH_ISSUER_URL` | Conditional | — | OAuth issuer base URL |
152
+ | `MCP_OAUTH_CLIENTS_FILE` | No | `./oauth-clients.json` | OAuth client registry |
153
+ | `MCP_OAUTH_TOKENS_FILE` | No | `./oauth-tokens.json` | OAuth token store |
154
+
155
+ ## Transports
156
+
157
+ - **stdio** (default): `npm run start:stdio` — for local MCP client integration
158
+ - **HTTP**: `npm run start:http` — Streamable HTTP with optional auth, WebSocket staging viewer at `/staging-ws`
159
+
160
+ ## License
161
+
162
+ MIT
package/index.js ADDED
@@ -0,0 +1,133 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Entry point for the Node-RED MCP server.
5
+ *
6
+ * Usage:
7
+ * node index.js → stdio (default)
8
+ * node index.js --transport=stdio → stdio
9
+ * node index.js --transport=http → HTTP on port 3000
10
+ * node index.js --transport=http --port=8080
11
+ */
12
+
13
+ import 'dotenv/config';
14
+ import { AuthManager } from './src/nodered/auth.js';
15
+ import { createNodeRedClient } from './src/nodered/client.js';
16
+ import { CommsClient } from './src/nodered/comms-client.js';
17
+ import { createMcpServer } from './src/server.js';
18
+ import { startStdioTransport } from './src/transport/stdio.js';
19
+ import { startHttpTransport } from './src/transport/http.js';
20
+ import { loadAuthConfig } from './src/auth/config.js';
21
+
22
+ // --- Parse CLI arguments ---
23
+
24
+ function parseArgs(argv) {
25
+ const args = { transport: 'stdio', port: 3000 };
26
+
27
+ for (const arg of argv.slice(2)) {
28
+ if (arg.startsWith('--transport=')) {
29
+ args.transport = arg.split('=')[1];
30
+ } else if (arg.startsWith('--port=')) {
31
+ args.port = parseInt(arg.split('=')[1], 10);
32
+ }
33
+ }
34
+
35
+ return args;
36
+ }
37
+
38
+ // --- Main ---
39
+
40
+ async function main() {
41
+ const args = parseArgs(process.argv);
42
+
43
+ // Validate required configuration
44
+ const baseUrl = process.env.NODERED_URL;
45
+ if (!baseUrl) {
46
+ console.error('Error: NODERED_URL environment variable is required.');
47
+ console.error('Set it in your .env file or environment. Example: NODERED_URL=http://localhost:1880');
48
+ process.exit(1);
49
+ }
50
+
51
+ // Initialize authentication
52
+ const authManager = new AuthManager({
53
+ baseUrl,
54
+ username: process.env.NODERED_USERNAME,
55
+ password: process.env.NODERED_PASSWORD,
56
+ apiKey: process.env.NODERED_API_KEY,
57
+ });
58
+
59
+ await authManager.init();
60
+ console.error(`[nodered-mcp] Connected to ${baseUrl} (Node-RED auth mode: ${authManager.mode})`);
61
+
62
+ // Load MCP server authentication configuration
63
+ const { config: authConfig, mode: authMode } = loadAuthConfig();
64
+ console.error(`[nodered-mcp] MCP server auth: ${authMode}`);
65
+
66
+ // Create Node-RED client and MCP server
67
+ const nodeRedClient = createNodeRedClient(baseUrl, authManager);
68
+
69
+ // Create and connect the comms client for real-time debug messages
70
+ const commsClient = new CommsClient({
71
+ baseUrl,
72
+ username: process.env.NODERED_USERNAME,
73
+ password: process.env.NODERED_PASSWORD,
74
+ // Pre-obtained token from auth manager takes precedence
75
+ token: authManager.mode === 'credentials' || authManager.mode === 'apikey'
76
+ ? authManager.getAuthHeader()?.replace('Bearer ', '')
77
+ : undefined,
78
+ });
79
+ // connect() is async (may fetch token); fire-and-forget — errors are
80
+ // emitted on the 'error' event and auto-reconnect handles the rest.
81
+ commsClient.connect().catch((err) => {
82
+ console.error(`[nodered-mcp] CommsClient initial connect failed: ${err.message}`);
83
+ });
84
+
85
+ // Start the selected transport
86
+ const port = process.env.MCP_HTTP_PORT
87
+ ? parseInt(process.env.MCP_HTTP_PORT, 10)
88
+ : args.port;
89
+
90
+ if (args.transport === 'http') {
91
+ // Build auth options for the HTTP transport
92
+ /** @type {object|undefined} */
93
+ let authOptions;
94
+
95
+ if (authConfig.apiKey || authConfig.oauthEnabled) {
96
+ authOptions = {
97
+ apiKey: authConfig.apiKey,
98
+ oauthProvider: null,
99
+ oauthIssuerUrl: authConfig.oauthIssuerUrl,
100
+ };
101
+
102
+ // Set up OAuth if enabled
103
+ if (authConfig.oauthEnabled) {
104
+ const { createClientsStore } = await import('./src/auth/oauth-clients-store.js');
105
+ const { createTokenStore } = await import('./src/auth/oauth-token-store.js');
106
+ const { createOAuthProvider } = await import('./src/auth/oauth-provider.js');
107
+
108
+ const clientsStore = await createClientsStore(authConfig.oauthClientsFile);
109
+ const tokenStore = await createTokenStore(authConfig.oauthTokensFile);
110
+ authOptions.oauthProvider = createOAuthProvider({ clientsStore, tokenStore });
111
+
112
+ console.error(`[nodered-mcp] OAuth clients store: ${authConfig.oauthClientsFile || 'oauth-clients.json'}`);
113
+ console.error(`[nodered-mcp] OAuth tokens store: ${authConfig.oauthTokensFile || 'oauth-tokens.json'}`);
114
+ }
115
+ }
116
+
117
+ // Eagerly create one MCP server to load staging for the viewer/WS
118
+ const bootstrapServer = await createMcpServer(nodeRedClient, commsClient);
119
+ const staging = bootstrapServer.__staging;
120
+ await startHttpTransport(() => createMcpServer(nodeRedClient, commsClient), port, staging, authOptions);
121
+ } else if (args.transport === 'stdio') {
122
+ const mcpServer = await createMcpServer(nodeRedClient, commsClient);
123
+ await startStdioTransport(mcpServer);
124
+ } else {
125
+ console.error(`Error: Unknown transport "${args.transport}". Use "stdio" or "http".`);
126
+ process.exit(1);
127
+ }
128
+ }
129
+
130
+ main().catch((err) => {
131
+ console.error('[nodered-mcp] Fatal error:', err.message);
132
+ process.exit(1);
133
+ });
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@gmag11/nodered-mcp-server",
3
+ "version": "1.0.1",
4
+ "description": "MCP server for controlling Node-RED instances via the Admin API",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "bin": {
8
+ "nodered-mcp-server": "index.js"
9
+ },
10
+ "scripts": {
11
+ "start:stdio": "node index.js --transport=stdio",
12
+ "start:http": "node index.js --transport=http",
13
+ "test": "vitest run",
14
+ "test:watch": "vitest",
15
+ "prepublishOnly": "npm test"
16
+ },
17
+ "keywords": [
18
+ "mcp",
19
+ "node-red",
20
+ "model-context-protocol",
21
+ "automation"
22
+ ],
23
+ "license": "Apache-2.0",
24
+ "author": {
25
+ "name": "Germán Martín",
26
+ "email": "github@gmartin.net"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/gmag11/NodeRed-MCP.git"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/gmag11/NodeRed-MCP/issues"
34
+ },
35
+ "homepage": "https://github.com/gmag11/NodeRed-MCP#readme",
36
+ "files": [
37
+ "index.js",
38
+ "src/",
39
+ "resources/skills/",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "dependencies": {
44
+ "@modelcontextprotocol/sdk": "^1.12.1",
45
+ "dotenv": "^16.5.0",
46
+ "express": "^5.1.0",
47
+ "gray-matter": "^4.0.3",
48
+ "turndown": "^7.2.4",
49
+ "ws": "^8.18.2",
50
+ "zod": "^3.25.20"
51
+ },
52
+ "devDependencies": {
53
+ "vitest": "^3.2.1"
54
+ },
55
+ "engines": {
56
+ "node": ">=18.0.0"
57
+ }
58
+ }