Creating a custom Node-RED node to interface with an MCP (Modbus Communication Protocol) server involves writing a Node-RED node module in JavaScript. Below is a basic example of how to create a custom Node-RED node that connects to an MCP (assuming you mean Modbus TCP) server and reads data.
If by "MCP server" you meant something else, please clarify. For now, I’ll assume you want to connect to a Modbus TCP server using Node-RED.
We’ll use the modbus-serial npm package to communicate with the Modbus TCP server.
Step-by-step:
- Create a new Node-RED node module.
- Use modbus-serial to connect to the Modbus TCP server.
- Expose a node that can read holding registers.
Directory structure:
node-red-contrib-mcp/
├── package.json
├── mcp.js
└── mcp.html
Step 1: package.json
{
"name": "node-red-contrib-mcp",
"version": "1.0.0",
"description": "A Node-RED node to connect to an MCP (Modbus TCP) server",
"dependencies": {
"modbus-serial": "^9.0.6"
},
"keywords": [
"node-red",
"modbus",
"mcp",
"modbus-tcp"
],
"node-red": {
"nodes": {
"mcp": "mcp.js"
}
},
"author": "Your Name",
"license": "MIT"
}
Step 2: mcp.js
module.exports = function(RED) {
const ModbusRTU = require("modbus-serial");
function MCPNode(config) {
RED.nodes.createNode(this, config);
const node = this;
const host = config.host || "127.0.0.1";
const port = parseInt(config.port) || 502;
const unitId = parseInt(config.unitId) || 1;
const address = parseInt(config.address) || 0;
const length = parseInt(config.length) || 1;
const client = new ModbusRTU();
client.connectTCP(host, { port: port })
.then(() => {
client.setID(unitId);
node.status({ fill: "green", shape: "dot", text: "connected" });
})
.catch(err => {
node.error("Connection error: " + err.message);
node.status({ fill: "red", shape: "ring", text: "disconnected" });
});
node.on("input", function(msg) {
client.readHoldingRegisters(address, length)
.then(data => {
msg.payload = data.data;
node.send(msg);
})
.catch(err => {
node.error("Read error: " + err.message);
});
});
node.on("close", function(done) {
client.close(() => {
node.status({ fill: "grey", shape: "ring", text: "closed" });
done();
});
});
}
RED.nodes.registerType("mcp", MCPNode);
};
Step 3: mcp.html
Installation:
- Place the node-red-contrib-mcp folder in your Node-RED user directory (usually ~/.node-red).
- Run npm install ./node-red-contrib-mcp inside that directory.
- Restart Node-RED.
Usage:
- Drag the "mcp" node into your flow.
- Configure the host, port, unit ID, address, and length.
- Send a message (any payload) into the node to trigger a read.
- The node will output the register values in msg.payload.
Let me know if you need write support or RTU support as well.