zigbee2mqtt-mcp 0.5.0 → 0.7.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.
package/README.md CHANGED
@@ -9,7 +9,7 @@ A [Model Context Protocol](https://modelcontextprotocol.io) server for **adminis
9
9
 
10
10
  Most Zigbee integrations already let an assistant turn a light on. This one is for the layer underneath: mesh health, weak links, devices that keep rejoining, stale batteries, firmware updates, pairing, binding, reporting intervals and device options — the things you normally open the Zigbee2MQTT frontend for.
11
11
 
12
- It talks directly to the Zigbee2MQTT [MQTT bridge API](https://www.zigbee2mqtt.io/guide/usage/mqtt_topics_and_messages.html), so it works with any Zigbee2MQTT 1.17+ installation regardless of whether you use Home Assistant, Node-RED, openHAB or nothing at all.
12
+ It talks directly to the Zigbee2MQTT [MQTT bridge API](https://www.zigbee2mqtt.io/guide/usage/mqtt_topics_and_messages.html), so it works regardless of whether you use Home Assistant, Node-RED, openHAB or nothing at all. Tested against Zigbee2MQTT 2.x; several tools depend on bridge endpoints that only exist there, including `bridge/health`, `device/binds/clear` and the OTA scheduling topics.
13
13
 
14
14
  ## Why this exists
15
15
 
@@ -78,6 +78,7 @@ Add to your MCP configuration:
78
78
  | `Z2M_MQTT_URL` | *required* | Broker URL. `mqtt://`, `mqtts://`, `ws://`, `wss://` |
79
79
  | `Z2M_MQTT_USERNAME` / `Z2M_MQTT_PASSWORD` | – | Broker credentials |
80
80
  | `Z2M_BASE_TOPIC` | `zigbee2mqtt` | Must match `mqtt.base_topic` |
81
+ | `Z2M_MQTT_CLIENT_ID` | `zigbee2mqtt-mcp-<pid>` | Override if your broker requires a fixed client ID |
81
82
  | `Z2M_WRITE_MODE` | `safe` | `off`, `safe` or `full` |
82
83
  | `Z2M_LOG_LEVEL` | `error` | Diagnostics on stderr |
83
84
  | `Z2M_WEAK_LINK_THRESHOLD` | `30` | Link quality below this is flagged |
@@ -98,7 +99,7 @@ Tools above the active tier are not registered at all, so a model cannot reach f
98
99
  | `safe` | **Default.** Read plus non-destructive writes: pairing, options, rename, configure, interview, binding, reporting, groups, state |
99
100
  | `full` | Everything, including device removal, OTA flashing, Touchlink and bridge restart |
100
101
 
101
- Irreversible tools (`z2m_remove_device`, `z2m_ota_update`, `z2m_touchlink`, `z2m_restart_bridge`, `z2m_set_bridge_options`) additionally require `confirm: true` on every call. Three `safe` tools reduce state rather than only adding to it, so they are annotated destructive and the reducing actions also require `confirm: true`: `z2m_manage_group` (`remove`, `remove_all_members`) and `z2m_bind` (`clear`). `z2m_rename_device` is annotated destructive because it breaks anything referencing the old name, but stays unconfirmed since renaming back restores it.
102
+ Irreversible tools (`z2m_remove_device`, `z2m_ota_update`, `z2m_touchlink`, `z2m_restart_bridge`, `z2m_set_bridge_options`) additionally require `confirm: true` on every call. Three `safe` tools reduce state rather than only adding to it, so they are annotated destructive: `z2m_rename_device`, `z2m_manage_group` and `z2m_bind`. Their reducing actions also require `confirm: true` — `z2m_manage_group` (`remove`, `remove_all_members`) and `z2m_bind` (`clear`). `z2m_rename_device` is annotated destructive because it breaks anything referencing the old name, but stays unconfirmed since renaming back restores it.
102
103
 
103
104
  Every tool also advertises MCP [tool annotations](https://modelcontextprotocol.io/specification/server/tools) so a client can decide what may run without prompting:
104
105
 
@@ -123,7 +124,7 @@ Opt in to the destructive tier only when you want it:
123
124
 
124
125
  | Tool | Purpose |
125
126
  | --- | --- |
126
- | `z2m_connection_status` | Broker reachability, TLS posture and cached message counts — reports instead of throwing when the connection is down |
127
+ | `z2m_connection_status` | Broker reachability, TLS posture and cached message counts — reports instead of throwing, even when nothing is configured yet |
127
128
  | `z2m_bridge_info` | Version, coordinator, channel, PAN ID, permit_join, restart_required, runtime stats |
128
129
  | `z2m_list_devices` | Filter and sort devices by type, availability, link quality, battery, pending update |
129
130
  | `z2m_get_device` | Exposes, settable options, endpoints, bindings, configured reportings, current state |
@@ -150,11 +151,11 @@ Some fields depend on your Zigbee2MQTT configuration. The server detects what is
150
151
  | `last_seen` | `advanced.last_seen` set to e.g. `ISO_8601` (default is `disable`) | Staleness checks are skipped and a hint is returned |
151
152
  | `availability` | `availability.enabled: true` | Offline detection is skipped and a hint is returned |
152
153
  | `linkquality`, `battery`, `update` | Live device traffic — Zigbee2MQTT does not retain device state topics | Pass `collect_seconds` to listen briefly, or use `z2m_network_map` for authoritative link quality |
153
- | `z2m_coordinator_check` | A Texas Instruments adapter (CC2652/CC1352) | Returns an error on other adapters; `z2m_bridge_info` reports whether it is supported |
154
+ | `z2m_coordinator_check` | An adapter that supports coordinator backups (TI zStack, Silicon Labs EmberZNet; not deCONZ or ZiGate) | Returns an error on unsupported adapters; `z2m_bridge_info` reports the expectation |
154
155
 
155
156
  ## Security notes
156
157
 
157
- - The broker URL may carry credentials (`mqtt://user:pass@host`). They are redacted everywhere the URL is echoed back to a model or written to a log, and error text from the MQTT client is scrubbed before it leaves the process.
158
+ - The broker URL may carry credentials (`mqtt://user:pass@host`). They are redacted everywhere the URL is echoed back to a model or written to a log, and error text from the MQTT client is scrubbed before it leaves the process. Zigbee2MQTT logs its own broker URL at startup, so lines relayed by `z2m_get_logs` are scrubbed too.
158
159
  - `safe` mode can actuate anything on the mesh via `z2m_set_state`, including locks, valves and sirens. Use `off` if that matters.
159
160
  - `z2m_permit_join` opens the network to any nearby Zigbee device for the duration of the window. It is in `safe` because it is routine and reversible, but it is a security boundary.
160
161
 
@@ -196,6 +197,17 @@ The unit tests cover health classification, capability detection, topic routing,
196
197
  write-mode gating and configuration parsing. They are broker-free by design, so
197
198
  anything that needs a live mesh belongs in `scripts/` instead.
198
199
 
200
+ A passing suite only proves the tests ran, so `scripts/mutate.mjs` breaks the
201
+ source one change at a time and checks the suite notices each one:
202
+
203
+ ```bash
204
+ node scripts/mutate.mjs # every mutant
205
+ node scripts/mutate.mjs redact # only mutants whose name matches
206
+ ```
207
+
208
+ A surviving mutant marks behaviour nothing actually tests, and exits non-zero.
209
+ Add a mutant alongside any fix worth keeping fixed.
210
+
199
211
  Releases are tag-driven: `npm version <patch|minor|major>` then
200
212
  `git push --follow-tags`. CI publishes to npm with provenance, rewrites
201
213
  `server.json`'s version from the tag and publishes to the MCP Registry, then
package/dist/client.js CHANGED
@@ -47,6 +47,7 @@ export class Z2MClient {
47
47
  transactionCounter = 0;
48
48
  lastMessageAt = 0;
49
49
  bridgeRevision = 0;
50
+ brokerHandshake = false;
50
51
  bridge = new Map();
51
52
  deviceState = new Map();
52
53
  availability = new Map();
@@ -64,6 +65,12 @@ export class Z2MClient {
64
65
  async connect() {
65
66
  if (this.client?.connected)
66
67
  return;
68
+ // A client that exists but is not connected is mid-reconnect. Dialling
69
+ // again would orphan it and flap the shared client ID on the broker.
70
+ if (this.client && !this.connectPromise) {
71
+ await this.awaitReconnect();
72
+ return;
73
+ }
67
74
  if (!this.connectPromise) {
68
75
  this.connectPromise = this.doConnect().finally(() => {
69
76
  this.connectPromise = null;
@@ -96,6 +103,7 @@ export class Z2MClient {
96
103
  if (settled)
97
104
  return;
98
105
  settled = true;
106
+ clearTimeout(timer);
99
107
  client.end(true);
100
108
  this.client = null;
101
109
  reject(error);
@@ -106,7 +114,12 @@ export class Z2MClient {
106
114
  fail(new Error(`MQTT connection to ${this.safeUrl} failed: ${scrubSecrets(error.message, config)}`));
107
115
  });
108
116
  client.on("message", (topic, payload) => this.handleMessage(topic, payload));
109
- client.on("connect", () => {
117
+ client.on("close", () => this.log.debug("mqtt connection closed"));
118
+ client.on("reconnect", () => this.log.debug("mqtt reconnecting"));
119
+ client.once("connect", () => {
120
+ this.brokerHandshake = true;
121
+ // `once`: mqtt.js re-emits this on every reconnect, and a second
122
+ // waitForBridgeData poll would be pure dead work.
110
123
  this.log.debug("connected, subscribing");
111
124
  client.subscribe(`${config.baseTopic}/#`, { qos: 1 }, (error) => {
112
125
  if (error) {
@@ -127,6 +140,21 @@ export class Z2MClient {
127
140
  });
128
141
  });
129
142
  }
143
+ /** Lets mqtt.js finish its own reconnect instead of opening a rival client. */
144
+ async awaitReconnect() {
145
+ const deadline = Date.now() + this.config.connectTimeoutMs;
146
+ while (Date.now() < deadline) {
147
+ if (this.client?.connected)
148
+ return;
149
+ if (!this.client)
150
+ break;
151
+ await sleep(100);
152
+ }
153
+ if (!this.client?.connected) {
154
+ throw new Error(`Lost the connection to ${this.safeUrl} and it has not come back within ` +
155
+ `${this.config.connectTimeoutMs}ms. Check that the broker is reachable.`);
156
+ }
157
+ }
130
158
  async waitForBridgeData(timeoutMs = 5_000) {
131
159
  const deadline = Date.now() + timeoutMs;
132
160
  while (Date.now() < deadline && !(this.bridge.has("devices") && this.bridge.has("info"))) {
@@ -178,7 +206,8 @@ export class Z2MClient {
178
206
  push(this.logs, LOG_BUFFER, {
179
207
  received_at: new Date().toISOString(),
180
208
  level: String(entry.level ?? "info"),
181
- message: String(entry.message ?? raw),
209
+ // Zigbee2MQTT logs its own broker URL at startup, credentials included.
210
+ message: scrubSecrets(String(entry.message ?? raw), this.config),
182
211
  namespace: entry.namespace,
183
212
  });
184
213
  }
@@ -196,8 +225,16 @@ export class Z2MClient {
196
225
  return;
197
226
  }
198
227
  case "bridge":
228
+ // We subscribe to the whole base topic, so our own publishes to
229
+ // bridge/request/* come straight back. Caching them would inflate the
230
+ // topic count and, worse, satisfy awaitBridgeRefresh before
231
+ // Zigbee2MQTT has republished anything.
232
+ if (route.name.startsWith("request/"))
233
+ return;
199
234
  this.bridge.set(route.name, parsed ?? raw);
200
235
  this.bridgeRevision++;
236
+ if (route.name === "devices")
237
+ this.pruneStaleState();
201
238
  return;
202
239
  case "availability": {
203
240
  const state = typeof parsed === "object" && parsed !== null
@@ -213,8 +250,30 @@ export class Z2MClient {
213
250
  this.deviceState.set(route.device, parsed);
214
251
  }
215
252
  return;
253
+ default: {
254
+ // Adding a TopicRoute variant without handling it is a compile error,
255
+ // rather than messages being silently dropped.
256
+ const unhandled = route;
257
+ void unhandled;
258
+ }
216
259
  }
217
260
  }
261
+ /**
262
+ * Renames and removals would otherwise leave their old keys behind forever,
263
+ * and these two maps are the only caches without a bound.
264
+ */
265
+ pruneStaleState() {
266
+ const devices = this.bridge.get("devices");
267
+ if (!Array.isArray(devices) || devices.length === 0)
268
+ return;
269
+ const known = new Set(devices.map((d) => d.friendly_name).filter((n) => typeof n === "string"));
270
+ for (const name of this.deviceState.keys())
271
+ if (!known.has(name))
272
+ this.deviceState.delete(name);
273
+ for (const name of this.availability.keys())
274
+ if (!known.has(name))
275
+ this.availability.delete(name);
276
+ }
218
277
  resolveWaiter(subTopic, parsed) {
219
278
  if (!parsed || typeof parsed !== "object")
220
279
  return;
@@ -286,7 +345,17 @@ export class Z2MClient {
286
345
  throw new Error("MQTT client is not connected");
287
346
  const body = typeof payload === "string" ? payload : JSON.stringify(payload);
288
347
  return new Promise((resolve, reject) => {
289
- client.publish(topic, body, { qos: 1 }, (error) => error ? reject(new Error(`Failed to publish to ${topic}: ${error.message}`)) : resolve());
348
+ // Settles only on the QoS 1 acknowledgement, which never arrives if the
349
+ // broker drops mid-publish, so bound it like request() does.
350
+ const timer = setTimeout(() => reject(new Error(`Timed out after ${this.config.requestTimeoutMs}ms publishing to ${topic}. ` +
351
+ "The message may still be queued for delivery.")), this.config.requestTimeoutMs);
352
+ client.publish(topic, body, { qos: 1 }, (error) => {
353
+ clearTimeout(timer);
354
+ if (error)
355
+ reject(new Error(`Failed to publish to ${topic}: ${error.message}`));
356
+ else
357
+ resolve();
358
+ });
290
359
  });
291
360
  }
292
361
  // ----------------------------------------------------------------- accessors
@@ -324,6 +393,7 @@ export class Z2MClient {
324
393
  client_certificate: this.config.cert !== undefined,
325
394
  },
326
395
  authenticated: this.config.username !== undefined,
396
+ broker_handshake: this.brokerHandshake,
327
397
  cached: {
328
398
  bridge_topics: this.bridge.size,
329
399
  device_state: this.deviceState.size,
package/dist/config.js CHANGED
@@ -3,10 +3,14 @@ function int(name, fallback) {
3
3
  const raw = process.env[name];
4
4
  if (raw === undefined || raw === "")
5
5
  return fallback;
6
- const parsed = Number.parseInt(raw, 10);
7
- if (Number.isNaN(parsed)) {
6
+ // parseInt would accept '12abc' as 12, which hides a typo in a timeout.
7
+ if (!/^-?\d+$/.test(raw.trim())) {
8
8
  throw new Error(`${name} must be an integer, got ${JSON.stringify(raw)}`);
9
9
  }
10
+ const parsed = Number.parseInt(raw, 10);
11
+ if (parsed < 0) {
12
+ throw new Error(`${name} must not be negative, got ${JSON.stringify(raw)}`);
13
+ }
10
14
  return parsed;
11
15
  }
12
16
  function bool(name, fallback) {
package/dist/devices.js CHANGED
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Adapters whose backup support makes coordinator_check work. Zigbee2MQTT
3
+ * gates it on adapter.supportsBackup(), which deCONZ and ZiGate do not have.
4
+ */
5
+ const BACKUP_CAPABLE = /^(zStack|znp|ember)/i;
1
6
  export function detectCapabilities(info, availability) {
2
7
  const config = (info?.config ?? {});
3
8
  const lastSeenSetting = config?.advanced?.last_seen;
@@ -8,7 +13,7 @@ export function detectCapabilities(info, availability) {
8
13
  availability: availability.size > 0 ||
9
14
  availabilitySetting === true ||
10
15
  (typeof availabilitySetting === "object" && availabilitySetting !== null),
11
- coordinator_check: typeof coordinatorType === "string" && /^z(Stack|np)/i.test(coordinatorType),
16
+ coordinator_check: typeof coordinatorType === "string" && BACKUP_CAPABLE.test(coordinatorType),
12
17
  coordinator_type: typeof coordinatorType === "string" ? coordinatorType : undefined,
13
18
  };
14
19
  }
package/dist/index.js CHANGED
@@ -5,7 +5,8 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
5
5
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
6
6
  import { Z2MClient } from "./client.js";
7
7
  import { createLogger, loadConfig } from "./config.js";
8
- import { redactUrl, scrubSecrets } from "./redact.js";
8
+ import { redactUrl } from "./redact.js";
9
+ import { render, toolErrorText } from "./render.js";
9
10
  import { selectTools } from "./tools.js";
10
11
  const { version } = createRequire(import.meta.url)("../package.json");
11
12
  async function main() {
@@ -22,7 +23,7 @@ async function main() {
22
23
  if (configError)
23
24
  log.error(configError);
24
25
  const client = new Z2MClient(config, log);
25
- const ctx = { client, config };
26
+ const ctx = { client, config, configError };
26
27
  const tools = selectTools(config.writeMode);
27
28
  const byName = new Map(tools.map((tool) => [tool.name, tool]));
28
29
  log.info(`write mode '${config.writeMode}' exposes ${tools.length} tools against ` +
@@ -37,13 +38,15 @@ async function main() {
37
38
  })),
38
39
  }));
39
40
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
40
- if (configError) {
41
+ const tool = byName.get(request.params.name);
42
+ // The connection diagnostic has to survive a missing URL: that is the most
43
+ // common misconfiguration, and it is the tool a user reaches for.
44
+ if (configError && !tool?.runsUnconfigured) {
41
45
  return {
42
46
  isError: true,
43
47
  content: [{ type: "text", text: configError }],
44
48
  };
45
49
  }
46
- const tool = byName.get(request.params.name);
47
50
  if (!tool) {
48
51
  const known = [...byName.keys()].join(", ");
49
52
  return {
@@ -60,17 +63,13 @@ async function main() {
60
63
  try {
61
64
  const result = await tool.handler(request.params.arguments ?? {}, ctx);
62
65
  return {
63
- content: [{ type: "text", text: JSON.stringify(result, replacer, 2) }],
66
+ content: [{ type: "text", text: render(result) }],
64
67
  };
65
68
  }
66
69
  catch (error) {
67
- // mqtt.js quotes back whatever URL it was given, so never return a raw message.
68
- const message = scrubSecrets(error.message, config);
69
- log.error(`${tool.name} failed:`, message);
70
- return {
71
- isError: true,
72
- content: [{ type: "text", text: `${tool.name} failed: ${message}` }],
73
- };
70
+ const text = toolErrorText(tool.name, error, config);
71
+ log.error(text);
72
+ return { isError: true, content: [{ type: "text", text }] };
74
73
  }
75
74
  });
76
75
  const shutdown = async () => {
@@ -85,10 +84,15 @@ async function main() {
85
84
  await server.connect(new StdioServerTransport());
86
85
  log.info("ready on stdio");
87
86
  }
88
- /** Maps are used for the internal caches; render them as plain objects. */
89
- function replacer(_key, value) {
90
- return value instanceof Map ? Object.fromEntries(value) : value;
91
- }
87
+ // A throw inside an event listener would otherwise kill the session with no
88
+ // diagnostic on stderr, which is indistinguishable from a clean exit.
89
+ process.on("unhandledRejection", (reason) => {
90
+ console.error(`[zigbee2mqtt-mcp] unhandled rejection: ${String(reason)}`);
91
+ });
92
+ process.on("uncaughtException", (error) => {
93
+ console.error(`[zigbee2mqtt-mcp] uncaught exception: ${error.message}`);
94
+ process.exit(1);
95
+ });
92
96
  main().catch((error) => {
93
97
  console.error(`[zigbee2mqtt-mcp] fatal: ${error.message}`);
94
98
  process.exit(1);
package/dist/render.js ADDED
@@ -0,0 +1,23 @@
1
+ import { scrubSecrets } from "./redact.js";
2
+ /** A large estate can otherwise return more JSON than a model can read. */
3
+ export const MAX_RESULT_BYTES = 100_000;
4
+ /** Maps are used for the internal caches; render them as plain objects. */
5
+ function replacer(_key, value) {
6
+ return value instanceof Map ? Object.fromEntries(value) : value;
7
+ }
8
+ export function render(result) {
9
+ // JSON.stringify(undefined) is undefined, which is not valid tool content.
10
+ const text = JSON.stringify(result, replacer, 2) ?? "null";
11
+ if (text.length <= MAX_RESULT_BYTES)
12
+ return text;
13
+ return (`${text.slice(0, MAX_RESULT_BYTES)}\n\n... truncated at ${MAX_RESULT_BYTES} characters of ` +
14
+ `${text.length}. Narrow the query: pass a limit, a specific device, or fewer fields.`);
15
+ }
16
+ /**
17
+ * Every tool failure reaches the model through here, and mqtt.js quotes back
18
+ * whatever URL it was given, so this is the last place to remove credentials.
19
+ */
20
+ export function toolErrorText(toolName, error, config) {
21
+ return `${toolName} failed: ${scrubSecrets(error.message, config)}`;
22
+ }
23
+ //# sourceMappingURL=render.js.map
package/dist/tools.js CHANGED
@@ -24,7 +24,7 @@ const DEVICE_ID = {
24
24
  // --------------------------------------------------------------------- helpers
25
25
  async function loadDevices(ctx, collectSeconds) {
26
26
  if (collectSeconds) {
27
- await ctx.client.collectState(Math.min(Number(collectSeconds), 120) * 1000);
27
+ await ctx.client.collectState(num({ collect_seconds: collectSeconds }, "collect_seconds", { min: 1, max: 120 }) * 1000);
28
28
  }
29
29
  const snap = await ctx.client.snapshot();
30
30
  const raw = snap.devices.filter((d) => !isCoordinator(d));
@@ -58,6 +58,26 @@ export function findRaw(raw, id) {
58
58
  }
59
59
  throw new Error(`No device matches '${id}'. Use z2m_list_devices to see available devices.`);
60
60
  }
61
+ /**
62
+ * Number("ten") is NaN, which silently becomes slice(0, NaN) or setTimeout(0)
63
+ * rather than an error a model can correct.
64
+ */
65
+ function num(args, name, { min = 0, max = Number.MAX_SAFE_INTEGER, fallback } = {}) {
66
+ const raw = args[name];
67
+ if (raw === undefined || raw === "") {
68
+ if (fallback !== undefined)
69
+ return fallback;
70
+ throw new Error(`${name} is required.`);
71
+ }
72
+ const value = Number(raw);
73
+ if (!Number.isFinite(value)) {
74
+ throw new Error(`${name} must be a number, got ${JSON.stringify(raw)}.`);
75
+ }
76
+ if (value < min || value > max) {
77
+ throw new Error(`${name} must be between ${min} and ${max}, got ${value}.`);
78
+ }
79
+ return value;
80
+ }
61
81
  function requireConfirm(args, action) {
62
82
  if (args.confirm !== true) {
63
83
  throw new Error(`${action} is irreversible or disruptive. Re-run with confirm=true to proceed.`);
@@ -75,8 +95,16 @@ function summariseExposes(exposes) {
75
95
  out.push(`${node.type}`);
76
96
  return;
77
97
  }
78
- if (node.property)
79
- out.push(`${node.property}:${node.type ?? "unknown"}`);
98
+ if (node.property) {
99
+ // The description tells the model to use this to discover valid
100
+ // values, so a bare type is not enough.
101
+ const bounds = node.type === "enum" && Array.isArray(node.values)
102
+ ? ` [${node.values.join("|")}]`
103
+ : node.value_min !== undefined || node.value_max !== undefined
104
+ ? ` [${node.value_min ?? "?"}..${node.value_max ?? "?"}${node.unit ? " " + node.unit : ""}]`
105
+ : "";
106
+ out.push(`${node.property}:${node.type ?? "unknown"}${bounds}`);
107
+ }
80
108
  };
81
109
  for (const expose of exposes ?? [])
82
110
  walk(expose);
@@ -88,14 +116,24 @@ const readTools = [
88
116
  name: "z2m_connection_status",
89
117
  tier: "read",
90
118
  annotations: readOnly("Check MQTT connection"),
119
+ runsUnconfigured: true,
91
120
  description: "Check whether this server can reach the MQTT broker and whether Zigbee2MQTT is publishing to it. " +
92
- "Read-only, and the only tool that reports rather than throws when the connection is down, so call " +
93
- "it first when any other tool fails with a connection or timeout error. Distinguishes an unreachable " +
94
- "broker from a reachable broker carrying no Zigbee2MQTT data, which usually means Z2M_BASE_TOPIC " +
95
- "does not match the mqtt.base_topic setting in Zigbee2MQTT. Reports the broker URL with credentials " +
96
- "redacted, TLS settings, cached message counts and the active write mode.",
121
+ "Read-only, and the only tool that reports rather than throws when the connection is down or not " +
122
+ "configured at all, so call it first when any other tool fails with a connection or timeout error. " +
123
+ "Distinguishes an unreachable broker from a reachable broker carrying no Zigbee2MQTT data, which " +
124
+ "usually means Z2M_BASE_TOPIC does not match the mqtt.base_topic setting in Zigbee2MQTT. Reports " +
125
+ "the broker URL with credentials redacted, TLS settings, cached message counts and the write mode.",
97
126
  inputSchema: EMPTY,
98
127
  handler: async (_args, ctx) => {
128
+ if (ctx.configError) {
129
+ return {
130
+ configured: false,
131
+ broker_reachable: false,
132
+ zigbee2mqtt_responding: false,
133
+ error: ctx.configError,
134
+ hints: ["Set Z2M_MQTT_URL in the server's environment, then call this tool again."],
135
+ };
136
+ }
99
137
  let brokerReachable = true;
100
138
  let zigbee2mqttResponding = true;
101
139
  let error;
@@ -105,9 +143,9 @@ const readTools = [
105
143
  catch (e) {
106
144
  error = scrubSecrets(e.message, ctx.config);
107
145
  zigbee2mqttResponding = false;
108
- // Reaching the broker and finding nothing on it is a different fault
109
- // from not reaching the broker at all.
110
- brokerReachable = e instanceof NoBridgeDataError;
146
+ // Whether the broker answered is a fact the client observed, not
147
+ // something to infer from which error happened to surface.
148
+ brokerReachable = ctx.client.status().broker_handshake || e instanceof NoBridgeDataError;
111
149
  }
112
150
  const status = ctx.client.status();
113
151
  const hints = [];
@@ -124,6 +162,7 @@ const readTools = [
124
162
  hints.push("TLS certificate verification is disabled, so the broker's identity is not checked.");
125
163
  }
126
164
  return {
165
+ configured: true,
127
166
  broker_reachable: brokerReachable,
128
167
  zigbee2mqtt_responding: zigbee2mqttResponding,
129
168
  ...status,
@@ -163,7 +202,7 @@ const readTools = [
163
202
  network: info.network,
164
203
  permit_join: info.permit_join,
165
204
  permit_join_end: info.permit_join_end
166
- ? new Date(Number(info.permit_join_end) * 1000).toISOString()
205
+ ? new Date(Number(info.permit_join_end)).toISOString()
167
206
  : undefined,
168
207
  log_level: info.log_level,
169
208
  restart_required: info.restart_required,
@@ -263,8 +302,7 @@ const readTools = [
263
302
  return String(av).localeCompare(String(bv));
264
303
  });
265
304
  const total = list.length;
266
- if (args.limit)
267
- list = list.slice(0, Number(args.limit));
305
+ list = list.slice(0, num(args, "limit", { min: 1, max: 1000, fallback: 100 }));
268
306
  return { total, returned: list.length, capabilities, devices: list };
269
307
  },
270
308
  },
@@ -349,14 +387,17 @@ const readTools = [
349
387
  include_routes: { type: "boolean", description: "Include active routes. Slower. Default false." },
350
388
  raw: { type: "boolean", description: "Return the unsummarised graph. Default false." },
351
389
  timeout_ms: { type: "number", description: "Scan timeout. Default 180000." },
390
+ max_nodes: { type: "number", description: "Cap the nodes returned. Default 200." },
352
391
  },
353
392
  },
354
393
  handler: async (args, ctx) => {
355
- const data = await ctx.client.request("networkmap", { type: "raw", routes: args.include_routes === true }, Number(args.timeout_ms ?? 180_000));
394
+ const data = await ctx.client.request("networkmap", { type: "raw", routes: args.include_routes === true }, num(args, "timeout_ms", { min: 1_000, max: 600_000, fallback: 180_000 }));
356
395
  const value = data?.value ?? data;
357
396
  if (args.raw)
358
397
  return value;
359
- const nodes = value?.nodes ?? [];
398
+ const allNodes = value?.nodes ?? [];
399
+ const maxNodes = num(args, "max_nodes", { min: 1, max: 1000, fallback: 200 });
400
+ const nodes = allNodes.slice(0, maxNodes);
360
401
  const links = value?.links ?? [];
361
402
  const byAddress = new Map(nodes.map((n) => [n.ieeeAddr, n]));
362
403
  const summary = nodes.map((node) => {
@@ -375,7 +416,11 @@ const readTools = [
375
416
  };
376
417
  });
377
418
  return {
419
+ total_nodes: allNodes.length,
378
420
  node_count: nodes.length,
421
+ ...(nodes.length < allNodes.length
422
+ ? { truncated: `Showing ${nodes.length} of ${allNodes.length} nodes; raise max_nodes to see more.` }
423
+ : {}),
379
424
  link_count: links.length,
380
425
  orphans: summary.filter((n) => n.parent === null && n.type !== "Coordinator"),
381
426
  weak: summary.filter((n) => n.linkquality !== undefined && n.linkquality < ctx.config.weakLinkThreshold),
@@ -426,14 +471,14 @@ const readTools = [
426
471
  const rank = { error: 3, warning: 2, warn: 2, info: 1 };
427
472
  const min = args.level ? rank[String(args.level)] ?? 0 : 0;
428
473
  let lines = args.watch_seconds
429
- ? await ctx.client.collectLogs(Math.min(Number(args.watch_seconds), 120) * 1000)
474
+ ? await ctx.client.collectLogs(num(args, "watch_seconds", { min: 1, max: 120 }) * 1000)
430
475
  : [...ctx.client.recentLogs()];
431
476
  lines = lines.filter((l) => (rank[l.level] ?? 1) >= min);
432
477
  if (args.contains) {
433
478
  const needle = String(args.contains).toLowerCase();
434
479
  lines = lines.filter((l) => l.message.toLowerCase().includes(needle));
435
480
  }
436
- const limit = Number(args.limit ?? 100);
481
+ const limit = num(args, "limit", { min: 1, max: 1000, fallback: 100 });
437
482
  return {
438
483
  note: ctx.client.recentLogs().length === 0 && !args.watch_seconds
439
484
  ? "No logs buffered yet. Logs are captured only while this server is connected; use watch_seconds to collect live."
@@ -448,9 +493,10 @@ const readTools = [
448
493
  tier: "read",
449
494
  annotations: readOnly("Check coordinator memory"),
450
495
  description: "Check whether any routers are missing from the coordinator's memory, which causes pairing failures and " +
451
- "devices dropping off. Changes nothing, but queries the coordinator directly. Only supported on Texas " +
452
- "Instruments adapters (CC2652/CC1352); other adapters return an error — z2m_bridge_info reports whether " +
453
- "yours qualifies under capabilities.coordinator_check. Returns {missing_routers[]}; an empty list is " +
496
+ "devices dropping off. Changes nothing, but queries the coordinator directly. Needs an adapter that " +
497
+ "supports coordinator backups, which Texas Instruments zStack and Silicon Labs EmberZNet do and " +
498
+ "deCONZ and ZiGate do not; unsupported adapters return an error, and z2m_bridge_info reports the " +
499
+ "expectation under capabilities.coordinator_check. Returns {missing_routers[]}; an empty list is " +
454
500
  "healthy. Use z2m_network_map for a topology view on any adapter.",
455
501
  inputSchema: EMPTY,
456
502
  handler: async (_args, ctx) => ctx.client.request("coordinator_check", {}, 60_000),
@@ -471,14 +517,26 @@ const safeTools = [
471
517
  properties: {
472
518
  device: { ...DEVICE_ID, description: "Check a single device. Omit to check all mains-powered devices." },
473
519
  timeout_ms: { type: "number", description: "Per-device timeout. Default 60000." },
520
+ max_devices: {
521
+ type: "number",
522
+ description: "Stop after this many devices so the call returns before a client times out. Default 10.",
523
+ },
524
+ offset: { type: "number", description: "Skip this many devices, to continue a previous sweep." },
474
525
  },
475
526
  },
476
527
  handler: async (args, ctx) => {
477
528
  const { raw } = await loadDevices(ctx);
478
- const timeout = Number(args.timeout_ms ?? 60_000);
479
- const targets = args.device
529
+ const timeout = num(args, "timeout_ms", { min: 1_000, max: 600_000, fallback: 60_000 });
530
+ // Mains-powered covers routers and anything else Zigbee2MQTT reports
531
+ // as mains powered; battery devices sleep and would just time out.
532
+ const candidates = args.device
480
533
  ? [findRaw(raw, String(args.device))]
481
- : raw.filter((d) => d.disabled !== true && d.type === "Router");
534
+ : raw.filter((d) => d.disabled !== true &&
535
+ (d.type === "Router" || (d.power_source ?? "").toLowerCase() === "mains (single phase)"));
536
+ const offset = num(args, "offset", { fallback: 0 });
537
+ const maxDevices = num(args, "max_devices", { min: 1, max: 100, fallback: 10 });
538
+ const targets = candidates.slice(offset, offset + maxDevices);
539
+ const remaining = Math.max(0, candidates.length - (offset + targets.length));
482
540
  const results = [];
483
541
  for (const target of targets) {
484
542
  try {
@@ -489,7 +547,13 @@ const safeTools = [
489
547
  results.push({ device: target.friendly_name, error: error.message });
490
548
  }
491
549
  }
492
- return { checked: results.length, results };
550
+ return {
551
+ checked: results.length,
552
+ total_candidates: candidates.length,
553
+ remaining,
554
+ ...(remaining > 0 ? { next_offset: offset + targets.length } : {}),
555
+ results,
556
+ };
493
557
  },
494
558
  },
495
559
  {
@@ -515,7 +579,7 @@ const safeTools = [
515
579
  required: ["time"],
516
580
  },
517
581
  handler: async (args, ctx) => {
518
- const payload = { time: Number(args.time) };
582
+ const payload = { time: num(args, "time", { min: 0, max: 254 }) };
519
583
  if (args.device)
520
584
  payload.device = String(args.device);
521
585
  return ctx.client.request("permit_join", payload);
@@ -656,7 +720,11 @@ const safeTools = [
656
720
  group: { type: "string", description: "Group friendly_name or numeric ID." },
657
721
  new_name: { type: "string", description: "Required for action=rename." },
658
722
  id: { type: "number", description: "Optional numeric ID for action=add." },
659
- device: { type: "string", description: "Device for member actions. Append /ENDPOINT to target an endpoint." },
723
+ device: { type: "string", description: "Device for member actions." },
724
+ endpoint: {
725
+ type: ["string", "number"],
726
+ description: "Endpoint for member actions, e.g. 'l1' or 1. Defaults to the device's default endpoint.",
727
+ },
660
728
  force: { type: "boolean", description: "Force removal even if a member device is unreachable." },
661
729
  confirm: { type: "boolean", description: "Required for action=remove and action=remove_all_members." },
662
730
  },
@@ -668,7 +736,7 @@ const safeTools = [
668
736
  case "add":
669
737
  return ctx.client.request("group/add", {
670
738
  friendly_name: group,
671
- ...(args.id !== undefined ? { id: Number(args.id) } : {}),
739
+ ...(args.id !== undefined ? { id: num(args, "id", { min: 1, max: 65_535 }) } : {}),
672
740
  });
673
741
  case "remove":
674
742
  requireConfirm(args, `Removing group '${group}'`);
@@ -680,11 +748,19 @@ const safeTools = [
680
748
  case "add_member":
681
749
  if (!args.device)
682
750
  throw new Error("device is required for action=add_member");
683
- return ctx.client.request("group/members/add", { group, device: String(args.device) });
751
+ return ctx.client.request("group/members/add", {
752
+ group,
753
+ device: String(args.device),
754
+ ...(args.endpoint !== undefined ? { endpoint: args.endpoint } : {}),
755
+ });
684
756
  case "remove_member":
685
757
  if (!args.device)
686
758
  throw new Error("device is required for action=remove_member");
687
- return ctx.client.request("group/members/remove", { group, device: String(args.device) });
759
+ return ctx.client.request("group/members/remove", {
760
+ group,
761
+ device: String(args.device),
762
+ ...(args.endpoint !== undefined ? { endpoint: args.endpoint } : {}),
763
+ });
688
764
  case "remove_all_members":
689
765
  requireConfirm(args, `Removing every member of group '${group}'`);
690
766
  return ctx.client.request("group/members/remove_all", { group });
@@ -701,19 +777,32 @@ const safeTools = [
701
777
  "control a light directly over Zigbee without a round trip through the coordinator, so it keeps working " +
702
778
  "even if the bridge is down. Reversible with action='unbind'; action='clear' removes all binds from the " +
703
779
  "source device at once and needs confirm=true, because the previous set cannot be recovered. " +
704
- "Append /ENDPOINT to target a specific endpoint, e.g. 'my_remote/left' — check " +
705
- "z2m_get_device endpoints first. Both devices must be awake.",
780
+ "To target one button of a multi-button remote, pass from_endpoint and to_endpoint as separate " +
781
+ "arguments — check z2m_get_device endpoints first. Both devices must be awake.",
706
782
  inputSchema: {
707
783
  type: "object",
708
784
  properties: {
709
785
  action: { type: "string", enum: ["bind", "unbind", "clear"] },
710
- from: { type: "string", description: "Source device, optionally with /ENDPOINT." },
786
+ from: { type: "string", description: "Source device friendly_name or ieee_address." },
711
787
  to: { type: "string", description: "Target device or group. Not needed for action=clear." },
788
+ from_endpoint: {
789
+ type: ["string", "number"],
790
+ description: "Source endpoint, e.g. 'left' or 1. Defaults to the device's default endpoint.",
791
+ },
792
+ to_endpoint: {
793
+ type: ["string", "number"],
794
+ description: "Target endpoint. Only meaningful when the target is a device, not a group.",
795
+ },
712
796
  clusters: {
713
797
  type: "array",
714
798
  items: { type: "string" },
715
799
  description: "Clusters to bind, e.g. ['genOnOff','genLevelCtrl']. Omit to bind all supported clusters.",
716
800
  },
801
+ ieee_list: {
802
+ type: "array",
803
+ items: { type: "string" },
804
+ description: "For action=clear: specific bind targets to remove. Omit to clear every binding.",
805
+ },
717
806
  confirm: { type: "boolean", description: "Required for action=clear." },
718
807
  },
719
808
  required: ["action", "from"],
@@ -721,11 +810,19 @@ const safeTools = [
721
810
  handler: async (args, ctx) => {
722
811
  if (args.action === "clear") {
723
812
  requireConfirm(args, `Clearing every binding from '${String(args.from)}'`);
724
- return ctx.client.request("device/binds/clear", { id: String(args.from) }, 60_000);
813
+ // Zigbee2MQTT rejects anything without a string `target` as "Invalid payload".
814
+ const clear = { target: String(args.from) };
815
+ if (Array.isArray(args.ieee_list) && args.ieee_list.length > 0)
816
+ clear.ieee_list = args.ieee_list;
817
+ return ctx.client.request("device/binds/clear", clear, 60_000);
725
818
  }
726
819
  if (!args.to)
727
820
  throw new Error("'to' is required for bind and unbind");
728
821
  const payload = { from: String(args.from), to: String(args.to) };
822
+ if (args.from_endpoint !== undefined)
823
+ payload.from_endpoint = args.from_endpoint;
824
+ if (args.to_endpoint !== undefined)
825
+ payload.to_endpoint = args.to_endpoint;
729
826
  if (Array.isArray(args.clusters) && args.clusters.length > 0)
730
827
  payload.clusters = args.clusters;
731
828
  return ctx.client.request(args.action === "bind" ? "device/bind" : "device/unbind", payload, 60_000);
@@ -758,12 +855,14 @@ const safeTools = [
758
855
  const target = findRaw(raw, String(args.device));
759
856
  return ctx.client.request("device/reporting/configure", {
760
857
  id: target.friendly_name,
761
- endpoint: Number(args.endpoint ?? 1),
858
+ endpoint: num(args, "endpoint", { min: 1, max: 255, fallback: 1 }),
762
859
  cluster: String(args.cluster),
763
860
  attribute: String(args.attribute),
764
- minimum_report_interval: Number(args.minimum_report_interval),
765
- maximum_report_interval: Number(args.maximum_report_interval),
766
- ...(args.reportable_change !== undefined ? { reportable_change: Number(args.reportable_change) } : {}),
861
+ minimum_report_interval: num(args, "minimum_report_interval", { max: 65_535 }),
862
+ maximum_report_interval: num(args, "maximum_report_interval", { max: 65_535 }),
863
+ ...(args.reportable_change !== undefined
864
+ ? { reportable_change: num(args, "reportable_change") }
865
+ : {}),
767
866
  }, 60_000);
768
867
  },
769
868
  },
@@ -785,7 +884,6 @@ const fullTools = [
785
884
  device: DEVICE_ID,
786
885
  force: { type: "boolean", description: "Delete from the database even if the device does not respond." },
787
886
  block: { type: "boolean", description: "Prevent the device from rejoining." },
788
- clear_cache: { type: "boolean", description: "Discard cached data so a rejoin re-interviews from scratch." },
789
887
  confirm: { type: "boolean", description: "Must be true to proceed." },
790
888
  },
791
889
  required: ["device", "confirm"],
@@ -798,7 +896,6 @@ const fullTools = [
798
896
  id: target.friendly_name,
799
897
  force: args.force === true,
800
898
  block: args.block === true,
801
- clear_cache: args.clear_cache === true,
802
899
  }, 60_000);
803
900
  },
804
901
  },
@@ -836,7 +933,8 @@ const fullTools = [
836
933
  : action === "unschedule"
837
934
  ? "device/ota_update/unschedule"
838
935
  : "device/ota_update/update";
839
- return ctx.client.request(topic, { id: target.friendly_name }, Number(args.timeout_ms ?? 1_800_000));
936
+ const timeoutMs = num(args, "timeout_ms", { min: 1_000, max: 3_600_000, fallback: 1_800_000 });
937
+ return ctx.client.request(topic, { id: target.friendly_name }, timeoutMs);
840
938
  },
841
939
  },
842
940
  {
@@ -886,25 +984,47 @@ const fullTools = [
886
984
  tier: "full",
887
985
  annotations: mutating("Touchlink scan, identify or reset", { destructive: true }),
888
986
  description: "Touchlink scan, identify or factory reset. action='scan' and 'identify' are harmless; " +
889
- "action='factory_reset' is IRREVERSIBLE and, without ieee_address and channel, affects the physically " +
890
- "nearest Touchlink device, which may not be the one you intend — run 'scan' first and pass an explicit " +
891
- "target. Use z2m_remove_device to remove a device already paired to this network. Requires confirm=true.",
987
+ "action='factory_reset' is IRREVERSIBLE. Pass both ieee_address and channel to target a device, and " +
988
+ "run 'scan' first to discover them. Supplying only one is rejected rather than falling back. Set " +
989
+ "nearest=true to act on whichever Touchlink device is physically closest, which may not be the one " +
990
+ "you intend. Use z2m_remove_device for a device already paired to this network. Requires confirm=true.",
892
991
  inputSchema: {
893
992
  type: "object",
894
993
  properties: {
895
994
  action: { type: "string", enum: ["scan", "identify", "factory_reset"] },
896
- ieee_address: { type: "string", description: "Required for identify and targeted factory_reset." },
897
- channel: { type: "number", description: "Required for identify and targeted factory_reset." },
995
+ ieee_address: { type: "string", description: "Target address. Required together with channel." },
996
+ channel: { type: "number", description: "Target channel. Required together with ieee_address." },
997
+ nearest: {
998
+ type: "boolean",
999
+ description: "Act on the physically nearest device instead of a named target.",
1000
+ },
898
1001
  confirm: { type: "boolean", description: "Must be true to proceed." },
899
1002
  },
900
1003
  required: ["action", "confirm"],
901
1004
  },
902
1005
  handler: async (args, ctx) => {
903
1006
  requireConfirm(args, "Touchlink");
904
- const payload = args.ieee_address && args.channel !== undefined
905
- ? { ieee_address: String(args.ieee_address), channel: Number(args.channel) }
906
- : {};
907
- return ctx.client.request(`touchlink/${String(args.action)}`, payload, 120_000);
1007
+ const action = String(args.action);
1008
+ const hasAddress = args.ieee_address !== undefined && String(args.ieee_address) !== "";
1009
+ const hasChannel = args.channel !== undefined;
1010
+ // Zigbee2MQTT treats an empty payload as "act on the first device found",
1011
+ // so a half-specified target must never fall through to it.
1012
+ if (hasAddress !== hasChannel) {
1013
+ throw new Error(`Touchlink ${action} needs both ieee_address and channel, or neither. ` +
1014
+ `Run action='scan' to discover the ${hasAddress ? "channel" : "address"}.`);
1015
+ }
1016
+ let payload = {};
1017
+ if (hasAddress) {
1018
+ if (args.nearest === true) {
1019
+ throw new Error("Pass either ieee_address with channel, or nearest=true, not both.");
1020
+ }
1021
+ payload = { ieee_address: String(args.ieee_address), channel: num(args, "channel") };
1022
+ }
1023
+ else if (action !== "scan" && args.nearest !== true) {
1024
+ throw new Error(`Touchlink ${action} without a target acts on the physically nearest device and cannot be ` +
1025
+ "undone. Pass ieee_address and channel, or set nearest=true to accept that.");
1026
+ }
1027
+ return ctx.client.request(`touchlink/${action}`, payload, 120_000);
908
1028
  },
909
1029
  },
910
1030
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zigbee2mqtt-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "mcpName": "io.github.alexpfau/zigbee2mqtt-mcp",
5
5
  "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.",
6
6
  "keywords": [