zigbee2mqtt-mcp 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -63,6 +63,9 @@ Add to your MCP configuration:
63
63
 
64
64
  > Point `Z2M_MQTT_URL` at your **MQTT broker**, not at the Zigbee2MQTT frontend port. If Zigbee2MQTT's `configuration.yaml` says `mqtt.server: mqtt://192.168.1.10:1883`, use that value verbatim.
65
65
 
66
+ > Behind a corporate npm proxy? If `npm config get registry` is not `https://registry.npmjs.org/`, your proxy's upstream feed may not carry this package. Add an explicit override to the args rather than changing your global registry:
67
+ > `"args": ["-y", "--registry", "https://registry.npmjs.org/", "zigbee2mqtt-mcp"]`
68
+
66
69
  ## Configuration
67
70
 
68
71
  | Variable | Default | Purpose |
@@ -70,7 +73,7 @@ Add to your MCP configuration:
70
73
  | `Z2M_MQTT_URL` | *required* | Broker URL. `mqtt://`, `mqtts://`, `ws://`, `wss://` |
71
74
  | `Z2M_MQTT_USERNAME` / `Z2M_MQTT_PASSWORD` | – | Broker credentials |
72
75
  | `Z2M_BASE_TOPIC` | `zigbee2mqtt` | Must match `mqtt.base_topic` |
73
- | `Z2M_WRITE_MODE` | `full` | `off`, `safe` or `full` |
76
+ | `Z2M_WRITE_MODE` | `safe` | `off`, `safe` or `full` |
74
77
  | `Z2M_LOG_LEVEL` | `error` | Diagnostics on stderr |
75
78
  | `Z2M_WEAK_LINK_THRESHOLD` | `30` | Link quality below this is flagged |
76
79
  | `Z2M_LOW_BATTERY_THRESHOLD` | `20` | Battery percentage below this is flagged |
@@ -87,11 +90,17 @@ Tools above the active tier are not registered at all, so a model cannot reach f
87
90
  | Mode | Exposes |
88
91
  | --- | --- |
89
92
  | `off` | Read-only tools |
90
- | `safe` | Read plus non-destructive writes: pairing, options, rename, configure, interview, binding, reporting, groups, state |
93
+ | `safe` | **Default.** Read plus non-destructive writes: pairing, options, rename, configure, interview, binding, reporting, groups, state |
91
94
  | `full` | Everything, including device removal, OTA flashing, Touchlink and bridge restart |
92
95
 
93
96
  Irreversible tools (`z2m_remove_device`, `z2m_ota_update`, `z2m_touchlink`, `z2m_restart_bridge`, `z2m_set_bridge_options`) additionally require `confirm: true` on every call.
94
97
 
98
+ Opt in to the destructive tier only when you want it:
99
+
100
+ ```jsonc
101
+ "env": { "Z2M_WRITE_MODE": "full" }
102
+ ```
103
+
95
104
  ## Tools
96
105
 
97
106
  ### Read
@@ -145,11 +154,24 @@ npm run watch
145
154
  # Manual smoke test against a real instance
146
155
  Z2M_MQTT_URL=mqtt://192.168.1.10:1883 node scripts/smoke.mjs
147
156
  Z2M_MQTT_URL=mqtt://192.168.1.10:1883 node scripts/smoke.mjs z2m_list_devices '{"only_problems":true}'
157
+
158
+ # Sequential read-after-write test. Renames a device and creates a group, then
159
+ # restores both, including on failure. Set Z2M_TEST_DEVICE to pick the device,
160
+ # or ROUNDTRIP_GROUPS_ONLY=1 to skip the rename.
161
+ Z2M_MQTT_URL=mqtt://192.168.1.10:1883 node scripts/roundtrip.mjs
148
162
  ```
149
163
 
164
+ Note that an MCP server may receive requests concurrently. When testing ordering,
165
+ await each response before sending the next, as `roundtrip.mjs` does — piping
166
+ several requests at once will produce misleading results.
167
+
150
168
  ## Safety
151
169
 
152
- This server can remove devices from your network and flash firmware. Both are irreversible and OTA failures can brick hardware. Run with `Z2M_WRITE_MODE=safe` or `off` if you do not want an assistant able to do that. Broker credentials are read from the environment and never logged.
170
+ This server can remove devices from your network and flash firmware. Both are irreversible and OTA failures can brick hardware. Those tools live in the `full` tier, which is **not** enabled by default — you must opt in with `Z2M_WRITE_MODE=full`. Broker credentials are read from the environment and never logged.
171
+
172
+ ## Status
173
+
174
+ Early release. Developed and tested against a 50-device EmberZNet estate on Zigbee2MQTT 2.12.x. Other adapters (Texas Instruments, deCONZ/ConBee, zStack), TLS and WebSocket brokers, and large estates are unverified. Bug reports and pull requests are very welcome — please include your adapter type and Zigbee2MQTT version from `z2m_bridge_info`.
153
175
 
154
176
  ## License
155
177
 
package/dist/client.js CHANGED
@@ -1,6 +1,21 @@
1
1
  import mqtt from "mqtt";
2
2
  const LOG_BUFFER = 1000;
3
3
  const EVENT_BUFFER = 200;
4
+ /**
5
+ * Requests that do not change bridge state, so callers need not wait for a
6
+ * retained republish. `restart` is included because the bridge goes away rather
7
+ * than republishing.
8
+ */
9
+ const NON_MUTATING = new Set([
10
+ "networkmap",
11
+ "health_check",
12
+ "coordinator_check",
13
+ "backup",
14
+ "restart",
15
+ "device/ota_update/check",
16
+ "device/ota_update/check/downgrade",
17
+ "device/reporting/read",
18
+ ]);
4
19
  /**
5
20
  * Zigbee2MQTT publishes its bridge topics as retained messages, so a fresh
6
21
  * subscription yields a complete picture within milliseconds. This client keeps
@@ -14,6 +29,7 @@ export class Z2MClient {
14
29
  connectPromise = null;
15
30
  transactionCounter = 0;
16
31
  lastMessageAt = 0;
32
+ bridgeRevision = 0;
17
33
  bridge = new Map();
18
34
  deviceState = new Map();
19
35
  availability = new Map();
@@ -161,6 +177,7 @@ export class Z2MClient {
161
177
  }
162
178
  if (rest.startsWith("bridge/")) {
163
179
  this.bridge.set(rest.slice("bridge/".length), parsed ?? raw);
180
+ this.bridgeRevision++;
164
181
  return;
165
182
  }
166
183
  // Friendly names may contain '/', so match on the suffix rather than splitting.
@@ -200,7 +217,8 @@ export class Z2MClient {
200
217
  const timeout = timeoutMs ?? this.config.requestTimeoutMs;
201
218
  const transaction = `mcp-${++this.transactionCounter}`;
202
219
  const key = `${subTopic}|${transaction}`;
203
- return new Promise((resolve, reject) => {
220
+ const revisionBefore = this.bridgeRevision;
221
+ const result = await new Promise((resolve, reject) => {
204
222
  const timer = setTimeout(() => {
205
223
  this.waiters.delete(key);
206
224
  reject(new Error(`Timed out after ${timeout}ms waiting for ${this.config.baseTopic}/bridge/response/${subTopic}. ` +
@@ -226,6 +244,20 @@ export class Z2MClient {
226
244
  }
227
245
  });
228
246
  });
247
+ // Zigbee2MQTT acknowledges a request before republishing its retained bridge
248
+ // topics, so a caller could in principle read a stale cache immediately
249
+ // afterwards. Not reproducible against a local broker, where the republish
250
+ // always wins the race, but the ordering is not guaranteed. Bounded guard.
251
+ if (!NON_MUTATING.has(subTopic)) {
252
+ await this.awaitBridgeRefresh(revisionBefore);
253
+ }
254
+ return result;
255
+ }
256
+ async awaitBridgeRefresh(since, timeoutMs = 2_000) {
257
+ const deadline = Date.now() + timeoutMs;
258
+ while (Date.now() < deadline && this.bridgeRevision === since) {
259
+ await sleep(25);
260
+ }
229
261
  }
230
262
  /** Fire-and-forget publish, used for device `set` and `get` commands. */
231
263
  async publish(topic, payload) {
package/dist/config.js CHANGED
@@ -54,7 +54,7 @@ export function loadConfig() {
54
54
  key: file("Z2M_MQTT_KEY"),
55
55
  connectTimeoutMs: int("Z2M_CONNECT_TIMEOUT_MS", 10_000),
56
56
  requestTimeoutMs: int("Z2M_REQUEST_TIMEOUT_MS", 15_000),
57
- writeMode: oneOf("Z2M_WRITE_MODE", ["off", "safe", "full"], "full"),
57
+ writeMode: oneOf("Z2M_WRITE_MODE", ["off", "safe", "full"], "safe"),
58
58
  logLevel: oneOf("Z2M_LOG_LEVEL", ["silent", "error", "warn", "info", "debug"], "error"),
59
59
  weakLinkThreshold: int("Z2M_WEAK_LINK_THRESHOLD", 30),
60
60
  lowBatteryThreshold: int("Z2M_LOW_BATTERY_THRESHOLD", 20),
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
2
3
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
5
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5
6
  import { Z2MClient } from "./client.js";
6
7
  import { createLogger, loadConfig } from "./config.js";
7
8
  import { selectTools } from "./tools.js";
9
+ const { version } = createRequire(import.meta.url)("../package.json");
8
10
  async function main() {
9
11
  const config = loadConfig();
10
12
  const log = createLogger(config.logLevel);
@@ -14,7 +16,7 @@ async function main() {
14
16
  const byName = new Map(tools.map((tool) => [tool.name, tool]));
15
17
  log.info(`write mode '${config.writeMode}' exposes ${tools.length} tools against ` +
16
18
  `${config.mqttUrl} (base topic '${config.baseTopic}')`);
17
- const server = new Server({ name: "zigbee2mqtt-mcp", version: "0.1.0" }, { capabilities: { tools: {} } });
19
+ const server = new Server({ name: "zigbee2mqtt-mcp", version }, { capabilities: { tools: {} } });
18
20
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
19
21
  tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
20
22
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zigbee2mqtt-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Model Context Protocol server for administering a Zigbee2MQTT estate: health reporting, network diagnostics, OTA updates, pairing and device management over the MQTT bridge API.",
5
5
  "keywords": [
6
6
  "mcp",