zigbee2mqtt-mcp 0.1.0

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.
@@ -0,0 +1,187 @@
1
+ export function detectCapabilities(info, availability) {
2
+ const config = (info?.config ?? {});
3
+ const lastSeenSetting = config?.advanced?.last_seen;
4
+ const availabilitySetting = config?.availability;
5
+ const coordinatorType = info?.coordinator?.type;
6
+ return {
7
+ last_seen: typeof lastSeenSetting === "string" && lastSeenSetting !== "disable",
8
+ availability: availability.size > 0 ||
9
+ availabilitySetting === true ||
10
+ (typeof availabilitySetting === "object" && availabilitySetting !== null),
11
+ coordinator_check: typeof coordinatorType === "string" && /^z(Stack|np)/i.test(coordinatorType),
12
+ coordinator_type: typeof coordinatorType === "string" ? coordinatorType : undefined,
13
+ };
14
+ }
15
+ export function normalize(raw, deviceState, availability) {
16
+ const state = deviceState.get(raw.friendly_name) ?? {};
17
+ const update = state.update;
18
+ const device = {
19
+ friendly_name: raw.friendly_name,
20
+ ieee_address: raw.ieee_address,
21
+ type: raw.type,
22
+ supported: raw.supported !== false,
23
+ disabled: raw.disabled === true,
24
+ interview_state: raw.interview_state ?? (raw.interview_completed ? "SUCCESSFUL" : "PENDING"),
25
+ endpoint_count: Object.keys(raw.endpoints ?? {}).length,
26
+ has_state: deviceState.has(raw.friendly_name),
27
+ };
28
+ if (raw.network_address !== undefined)
29
+ device.network_address = raw.network_address;
30
+ if (raw.definition?.model)
31
+ device.model = raw.definition.model;
32
+ if (raw.definition?.vendor)
33
+ device.vendor = raw.definition.vendor;
34
+ if (raw.description || raw.definition?.description) {
35
+ device.description = raw.description || raw.definition?.description;
36
+ }
37
+ if (raw.power_source)
38
+ device.power_source = raw.power_source;
39
+ if (raw.software_build_id)
40
+ device.software_build_id = raw.software_build_id;
41
+ if (raw.date_code)
42
+ device.date_code = raw.date_code;
43
+ if (typeof state.linkquality === "number")
44
+ device.linkquality = state.linkquality;
45
+ if (typeof state.battery === "number")
46
+ device.battery = state.battery;
47
+ if (typeof state.battery_low === "boolean")
48
+ device.battery_low = state.battery_low;
49
+ if (state.last_seen !== undefined)
50
+ device.last_seen = String(state.last_seen);
51
+ if (update && typeof update === "object")
52
+ device.update = update;
53
+ const avail = availability.get(raw.friendly_name);
54
+ if (avail)
55
+ device.availability = avail;
56
+ return device;
57
+ }
58
+ export function isCoordinator(raw) {
59
+ return raw.type === "Coordinator";
60
+ }
61
+ export function buildHealthReport(devices, info, bridgeState, bridgeHealth, capabilities, config) {
62
+ const issues = {
63
+ offline: [],
64
+ stale: [],
65
+ weak_link: [],
66
+ low_battery: [],
67
+ interview_incomplete: [],
68
+ unsupported: [],
69
+ disabled: [],
70
+ update_available: [],
71
+ rejoining: [],
72
+ address_changing: [],
73
+ silent: [],
74
+ };
75
+ const staleCutoff = Date.now() - config.staleHours * 3_600_000;
76
+ const deviceHealth = (bridgeHealth?.devices ?? {});
77
+ for (const device of devices) {
78
+ const ref = { friendly_name: device.friendly_name, ieee_address: device.ieee_address };
79
+ if (device.disabled) {
80
+ issues.disabled.push({ ...ref, detail: "Device is disabled in Zigbee2MQTT" });
81
+ continue; // disabled devices produce no traffic, so other checks are noise
82
+ }
83
+ if (device.availability === "offline") {
84
+ issues.offline.push({ ...ref, detail: "Availability reports offline" });
85
+ }
86
+ if (device.interview_state !== "SUCCESSFUL") {
87
+ issues.interview_incomplete.push({ ...ref, detail: `interview_state=${device.interview_state}` });
88
+ }
89
+ if (!device.supported) {
90
+ issues.unsupported.push({
91
+ ...ref,
92
+ detail: `No converter for model_id; exposed generically${device.model ? ` (${device.model})` : ""}`,
93
+ });
94
+ }
95
+ if (device.linkquality !== undefined && device.linkquality < config.weakLinkThreshold) {
96
+ issues.weak_link.push({ ...ref, detail: `linkquality=${device.linkquality} (< ${config.weakLinkThreshold})` });
97
+ }
98
+ if (device.battery !== undefined && device.battery < config.lowBatteryThreshold) {
99
+ issues.low_battery.push({ ...ref, detail: `battery=${device.battery}% (< ${config.lowBatteryThreshold}%)` });
100
+ }
101
+ else if (device.battery_low) {
102
+ issues.low_battery.push({ ...ref, detail: "Device reports battery_low" });
103
+ }
104
+ if (device.update?.state === "available") {
105
+ const from = device.update.installed_version;
106
+ const to = device.update.latest_version;
107
+ issues.update_available.push({
108
+ ...ref,
109
+ detail: from && to ? `OTA update available: ${from} -> ${to}` : "OTA update available",
110
+ });
111
+ }
112
+ // A missing last_seen is not a finding: Zigbee2MQTT only publishes it when a
113
+ // device reports, so absence means no data yet. The authoritative signal for
114
+ // a device that has never reported is bridge/health messages === 0, below.
115
+ if (capabilities.last_seen && device.last_seen) {
116
+ const seen = Date.parse(device.last_seen);
117
+ if (!Number.isNaN(seen) && seen < staleCutoff) {
118
+ const hours = Math.round((Date.now() - seen) / 3_600_000);
119
+ issues.stale.push({ ...ref, detail: `Last seen ${hours}h ago (> ${config.staleHours}h)` });
120
+ }
121
+ }
122
+ // bridge/health counters are cumulative since the bridge started and are
123
+ // available immediately, unlike anything derived from device state topics.
124
+ const stats = deviceHealth[device.ieee_address];
125
+ if (stats) {
126
+ if (stats.leave_count > 0) {
127
+ issues.rejoining.push({
128
+ ...ref,
129
+ detail: `Left and rejoined the network ${stats.leave_count} time(s) since bridge start`,
130
+ });
131
+ }
132
+ if (stats.network_address_changes > 0) {
133
+ issues.address_changing.push({
134
+ ...ref,
135
+ detail: `Network address changed ${stats.network_address_changes} time(s), which suggests an unstable route`,
136
+ });
137
+ }
138
+ if (stats.messages === 0) {
139
+ issues.silent.push({ ...ref, detail: "No messages received since bridge start" });
140
+ }
141
+ }
142
+ }
143
+ const hints = [];
144
+ if (!capabilities.last_seen) {
145
+ hints.push("Staleness checks are unavailable because advanced.last_seen is 'disable' in your Zigbee2MQTT " +
146
+ "configuration. Set it to 'ISO_8601' to enable them.");
147
+ }
148
+ if (!capabilities.availability) {
149
+ hints.push("Offline detection is unavailable because device availability is not enabled. " +
150
+ "Set availability.enabled to true in your Zigbee2MQTT configuration.");
151
+ }
152
+ if (capabilities.last_seen && devices.some((d) => d.has_state && !d.last_seen)) {
153
+ hints.push("Staleness coverage is partial: some devices last reported before advanced.last_seen was enabled, " +
154
+ "so they carry no timestamp yet. Coverage completes as each device next reports.");
155
+ }
156
+ if (devices.every((d) => d.linkquality === undefined)) {
157
+ hints.push("No link quality data yet. Zigbee2MQTT does not retain device state topics, so these values only " +
158
+ "appear as devices report in. Pass collect_seconds to listen for live traffic, or use " +
159
+ "z2m_network_map for an authoritative mesh-wide reading.");
160
+ }
161
+ if (info?.restart_required === true) {
162
+ hints.push("Zigbee2MQTT reports restart_required=true; pending option changes are not active yet.");
163
+ }
164
+ if (bridgeState && bridgeState.state !== "online") {
165
+ hints.push(`Bridge state is '${String(bridgeState.state)}'.`);
166
+ }
167
+ const nonEmpty = Object.fromEntries(Object.entries(issues).filter(([, list]) => list.length > 0));
168
+ return {
169
+ bridge: {
170
+ state: bridgeState?.state ?? "unknown",
171
+ version: info?.version,
172
+ coordinator_type: capabilities.coordinator_type,
173
+ permit_join: info?.permit_join,
174
+ restart_required: info?.restart_required,
175
+ },
176
+ totals: {
177
+ devices: devices.length,
178
+ routers: devices.filter((d) => d.type === "Router").length,
179
+ end_devices: devices.filter((d) => d.type === "EndDevice").length,
180
+ issue_count: Object.values(nonEmpty).reduce((sum, list) => sum + list.length, 0),
181
+ },
182
+ capabilities,
183
+ issues: nonEmpty,
184
+ hints,
185
+ };
186
+ }
187
+ //# sourceMappingURL=devices.js.map
package/dist/index.js ADDED
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5
+ import { Z2MClient } from "./client.js";
6
+ import { createLogger, loadConfig } from "./config.js";
7
+ import { selectTools } from "./tools.js";
8
+ async function main() {
9
+ const config = loadConfig();
10
+ const log = createLogger(config.logLevel);
11
+ const client = new Z2MClient(config, log);
12
+ const ctx = { client, config };
13
+ const tools = selectTools(config.writeMode);
14
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
15
+ log.info(`write mode '${config.writeMode}' exposes ${tools.length} tools against ` +
16
+ `${config.mqttUrl} (base topic '${config.baseTopic}')`);
17
+ const server = new Server({ name: "zigbee2mqtt-mcp", version: "0.1.0" }, { capabilities: { tools: {} } });
18
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
19
+ tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
20
+ }));
21
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
22
+ const tool = byName.get(request.params.name);
23
+ if (!tool) {
24
+ const known = [...byName.keys()].join(", ");
25
+ return {
26
+ isError: true,
27
+ content: [
28
+ {
29
+ type: "text",
30
+ text: `Unknown tool '${request.params.name}'. Available tools: ${known}. ` +
31
+ `Write mode is '${config.writeMode}'; raise Z2M_WRITE_MODE to expose more.`,
32
+ },
33
+ ],
34
+ };
35
+ }
36
+ try {
37
+ const result = await tool.handler(request.params.arguments ?? {}, ctx);
38
+ return {
39
+ content: [{ type: "text", text: JSON.stringify(result, replacer, 2) }],
40
+ };
41
+ }
42
+ catch (error) {
43
+ log.error(`${tool.name} failed:`, error.message);
44
+ return {
45
+ isError: true,
46
+ content: [{ type: "text", text: `${tool.name} failed: ${error.message}` }],
47
+ };
48
+ }
49
+ });
50
+ const shutdown = async () => {
51
+ await client.disconnect().catch(() => undefined);
52
+ process.exit(0);
53
+ };
54
+ process.on("SIGINT", shutdown);
55
+ process.on("SIGTERM", shutdown);
56
+ // The open MQTT socket keeps the event loop alive, so the process would
57
+ // otherwise outlive the client that spawned it.
58
+ server.onclose = shutdown;
59
+ await server.connect(new StdioServerTransport());
60
+ log.info("ready on stdio");
61
+ }
62
+ /** Maps are used for the internal caches; render them as plain objects. */
63
+ function replacer(_key, value) {
64
+ return value instanceof Map ? Object.fromEntries(value) : value;
65
+ }
66
+ main().catch((error) => {
67
+ console.error(`[zigbee2mqtt-mcp] fatal: ${error.message}`);
68
+ process.exit(1);
69
+ });
70
+ //# sourceMappingURL=index.js.map