domotz-mcp
Version:
MCP server for Domotz API and BMS (Building Management System) integration with IoT device monitoring
80 lines (79 loc) • 2.73 kB
JavaScript
import { z } from "zod";
import { MCPTool } from "mcp-framework";
import { mqttConnections } from "./MQTTConnectionTool.js";
export default class MQTTPublishTool extends MCPTool {
name = "mqtt_publish";
description = "Publish messages to MQTT topics to control IoT devices";
schema = {
connection_id: {
type: z.string(),
description: "The connection ID from mqtt_connect"
},
topic: {
type: z.string(),
description: "MQTT topic to publish to"
},
message: {
type: z.string(),
description: "Message payload (can be JSON string for complex data)"
},
qos: {
type: z.number().optional(),
description: "Quality of Service level (0, 1, or 2, default: 0)"
},
retain: {
type: z.boolean().optional(),
description: "Retain message on broker (default: false)"
}
};
async execute(params) {
try {
const { connection_id, topic, message, qos = 0, retain = false } = params;
const client = mqttConnections.get(connection_id);
if (!client) {
return {
success: false,
error: "No active connection found with the specified ID"
};
}
if (!client.connected) {
return {
success: false,
error: "MQTT client is not connected"
};
}
return new Promise((resolve) => {
client.publish(topic, message, {
qos: qos,
retain
}, (error) => {
if (error) {
resolve({
success: false,
error: `Failed to publish: ${error.message}`
});
}
else {
resolve({
success: true,
message: "Message published successfully",
details: {
topic,
message_length: message.length,
qos,
retain,
timestamp: new Date().toISOString()
}
});
}
});
});
}
catch (error) {
return {
success: false,
error: error.message || "Failed to publish message"
};
}
}
}