zigbee2mqtt-mcp 0.6.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 +15 -3
- package/dist/client.js +56 -2
- package/dist/devices.js +6 -1
- package/dist/index.js +15 -13
- package/dist/render.js +23 -0
- package/dist/tools.js +151 -42
- package/package.json +1 -1
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
|
|
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
|
|
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
|
|
|
@@ -150,7 +151,7 @@ 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` |
|
|
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
|
|
|
@@ -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
|
@@ -65,6 +65,12 @@ export class Z2MClient {
|
|
|
65
65
|
async connect() {
|
|
66
66
|
if (this.client?.connected)
|
|
67
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
|
+
}
|
|
68
74
|
if (!this.connectPromise) {
|
|
69
75
|
this.connectPromise = this.doConnect().finally(() => {
|
|
70
76
|
this.connectPromise = null;
|
|
@@ -97,6 +103,7 @@ export class Z2MClient {
|
|
|
97
103
|
if (settled)
|
|
98
104
|
return;
|
|
99
105
|
settled = true;
|
|
106
|
+
clearTimeout(timer);
|
|
100
107
|
client.end(true);
|
|
101
108
|
this.client = null;
|
|
102
109
|
reject(error);
|
|
@@ -107,8 +114,12 @@ export class Z2MClient {
|
|
|
107
114
|
fail(new Error(`MQTT connection to ${this.safeUrl} failed: ${scrubSecrets(error.message, config)}`));
|
|
108
115
|
});
|
|
109
116
|
client.on("message", (topic, payload) => this.handleMessage(topic, payload));
|
|
110
|
-
client.on("
|
|
117
|
+
client.on("close", () => this.log.debug("mqtt connection closed"));
|
|
118
|
+
client.on("reconnect", () => this.log.debug("mqtt reconnecting"));
|
|
119
|
+
client.once("connect", () => {
|
|
111
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.
|
|
112
123
|
this.log.debug("connected, subscribing");
|
|
113
124
|
client.subscribe(`${config.baseTopic}/#`, { qos: 1 }, (error) => {
|
|
114
125
|
if (error) {
|
|
@@ -129,6 +140,21 @@ export class Z2MClient {
|
|
|
129
140
|
});
|
|
130
141
|
});
|
|
131
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
|
+
}
|
|
132
158
|
async waitForBridgeData(timeoutMs = 5_000) {
|
|
133
159
|
const deadline = Date.now() + timeoutMs;
|
|
134
160
|
while (Date.now() < deadline && !(this.bridge.has("devices") && this.bridge.has("info"))) {
|
|
@@ -207,6 +233,8 @@ export class Z2MClient {
|
|
|
207
233
|
return;
|
|
208
234
|
this.bridge.set(route.name, parsed ?? raw);
|
|
209
235
|
this.bridgeRevision++;
|
|
236
|
+
if (route.name === "devices")
|
|
237
|
+
this.pruneStaleState();
|
|
210
238
|
return;
|
|
211
239
|
case "availability": {
|
|
212
240
|
const state = typeof parsed === "object" && parsed !== null
|
|
@@ -230,6 +258,22 @@ export class Z2MClient {
|
|
|
230
258
|
}
|
|
231
259
|
}
|
|
232
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
|
+
}
|
|
233
277
|
resolveWaiter(subTopic, parsed) {
|
|
234
278
|
if (!parsed || typeof parsed !== "object")
|
|
235
279
|
return;
|
|
@@ -301,7 +345,17 @@ export class Z2MClient {
|
|
|
301
345
|
throw new Error("MQTT client is not connected");
|
|
302
346
|
const body = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
303
347
|
return new Promise((resolve, reject) => {
|
|
304
|
-
|
|
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
|
+
});
|
|
305
359
|
});
|
|
306
360
|
}
|
|
307
361
|
// ----------------------------------------------------------------- accessors
|
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" &&
|
|
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
|
|
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() {
|
|
@@ -62,17 +63,13 @@ async function main() {
|
|
|
62
63
|
try {
|
|
63
64
|
const result = await tool.handler(request.params.arguments ?? {}, ctx);
|
|
64
65
|
return {
|
|
65
|
-
content: [{ type: "text", text:
|
|
66
|
+
content: [{ type: "text", text: render(result) }],
|
|
66
67
|
};
|
|
67
68
|
}
|
|
68
69
|
catch (error) {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
return {
|
|
73
|
-
isError: true,
|
|
74
|
-
content: [{ type: "text", text: `${tool.name} failed: ${message}` }],
|
|
75
|
-
};
|
|
70
|
+
const text = toolErrorText(tool.name, error, config);
|
|
71
|
+
log.error(text);
|
|
72
|
+
return { isError: true, content: [{ type: "text", text }] };
|
|
76
73
|
}
|
|
77
74
|
});
|
|
78
75
|
const shutdown = async () => {
|
|
@@ -87,10 +84,15 @@ async function main() {
|
|
|
87
84
|
await server.connect(new StdioServerTransport());
|
|
88
85
|
log.info("ready on stdio");
|
|
89
86
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
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
|
+
});
|
|
94
96
|
main().catch((error) => {
|
|
95
97
|
console.error(`[zigbee2mqtt-mcp] fatal: ${error.message}`);
|
|
96
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(
|
|
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
|
-
|
|
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);
|
|
@@ -174,7 +202,7 @@ const readTools = [
|
|
|
174
202
|
network: info.network,
|
|
175
203
|
permit_join: info.permit_join,
|
|
176
204
|
permit_join_end: info.permit_join_end
|
|
177
|
-
? new Date(Number(info.permit_join_end)
|
|
205
|
+
? new Date(Number(info.permit_join_end)).toISOString()
|
|
178
206
|
: undefined,
|
|
179
207
|
log_level: info.log_level,
|
|
180
208
|
restart_required: info.restart_required,
|
|
@@ -274,8 +302,7 @@ const readTools = [
|
|
|
274
302
|
return String(av).localeCompare(String(bv));
|
|
275
303
|
});
|
|
276
304
|
const total = list.length;
|
|
277
|
-
|
|
278
|
-
list = list.slice(0, Number(args.limit));
|
|
305
|
+
list = list.slice(0, num(args, "limit", { min: 1, max: 1000, fallback: 100 }));
|
|
279
306
|
return { total, returned: list.length, capabilities, devices: list };
|
|
280
307
|
},
|
|
281
308
|
},
|
|
@@ -360,14 +387,17 @@ const readTools = [
|
|
|
360
387
|
include_routes: { type: "boolean", description: "Include active routes. Slower. Default false." },
|
|
361
388
|
raw: { type: "boolean", description: "Return the unsummarised graph. Default false." },
|
|
362
389
|
timeout_ms: { type: "number", description: "Scan timeout. Default 180000." },
|
|
390
|
+
max_nodes: { type: "number", description: "Cap the nodes returned. Default 200." },
|
|
363
391
|
},
|
|
364
392
|
},
|
|
365
393
|
handler: async (args, ctx) => {
|
|
366
|
-
const data = await ctx.client.request("networkmap", { type: "raw", routes: args.include_routes === true },
|
|
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 }));
|
|
367
395
|
const value = data?.value ?? data;
|
|
368
396
|
if (args.raw)
|
|
369
397
|
return value;
|
|
370
|
-
const
|
|
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);
|
|
371
401
|
const links = value?.links ?? [];
|
|
372
402
|
const byAddress = new Map(nodes.map((n) => [n.ieeeAddr, n]));
|
|
373
403
|
const summary = nodes.map((node) => {
|
|
@@ -386,7 +416,11 @@ const readTools = [
|
|
|
386
416
|
};
|
|
387
417
|
});
|
|
388
418
|
return {
|
|
419
|
+
total_nodes: allNodes.length,
|
|
389
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
|
+
: {}),
|
|
390
424
|
link_count: links.length,
|
|
391
425
|
orphans: summary.filter((n) => n.parent === null && n.type !== "Coordinator"),
|
|
392
426
|
weak: summary.filter((n) => n.linkquality !== undefined && n.linkquality < ctx.config.weakLinkThreshold),
|
|
@@ -437,14 +471,14 @@ const readTools = [
|
|
|
437
471
|
const rank = { error: 3, warning: 2, warn: 2, info: 1 };
|
|
438
472
|
const min = args.level ? rank[String(args.level)] ?? 0 : 0;
|
|
439
473
|
let lines = args.watch_seconds
|
|
440
|
-
? await ctx.client.collectLogs(
|
|
474
|
+
? await ctx.client.collectLogs(num(args, "watch_seconds", { min: 1, max: 120 }) * 1000)
|
|
441
475
|
: [...ctx.client.recentLogs()];
|
|
442
476
|
lines = lines.filter((l) => (rank[l.level] ?? 1) >= min);
|
|
443
477
|
if (args.contains) {
|
|
444
478
|
const needle = String(args.contains).toLowerCase();
|
|
445
479
|
lines = lines.filter((l) => l.message.toLowerCase().includes(needle));
|
|
446
480
|
}
|
|
447
|
-
const limit =
|
|
481
|
+
const limit = num(args, "limit", { min: 1, max: 1000, fallback: 100 });
|
|
448
482
|
return {
|
|
449
483
|
note: ctx.client.recentLogs().length === 0 && !args.watch_seconds
|
|
450
484
|
? "No logs buffered yet. Logs are captured only while this server is connected; use watch_seconds to collect live."
|
|
@@ -459,9 +493,10 @@ const readTools = [
|
|
|
459
493
|
tier: "read",
|
|
460
494
|
annotations: readOnly("Check coordinator memory"),
|
|
461
495
|
description: "Check whether any routers are missing from the coordinator's memory, which causes pairing failures and " +
|
|
462
|
-
"devices dropping off. Changes nothing, but queries the coordinator directly.
|
|
463
|
-
"
|
|
464
|
-
"
|
|
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 " +
|
|
465
500
|
"healthy. Use z2m_network_map for a topology view on any adapter.",
|
|
466
501
|
inputSchema: EMPTY,
|
|
467
502
|
handler: async (_args, ctx) => ctx.client.request("coordinator_check", {}, 60_000),
|
|
@@ -482,14 +517,26 @@ const safeTools = [
|
|
|
482
517
|
properties: {
|
|
483
518
|
device: { ...DEVICE_ID, description: "Check a single device. Omit to check all mains-powered devices." },
|
|
484
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." },
|
|
485
525
|
},
|
|
486
526
|
},
|
|
487
527
|
handler: async (args, ctx) => {
|
|
488
528
|
const { raw } = await loadDevices(ctx);
|
|
489
|
-
const timeout =
|
|
490
|
-
|
|
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
|
|
491
533
|
? [findRaw(raw, String(args.device))]
|
|
492
|
-
: raw.filter((d) => d.disabled !== true &&
|
|
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));
|
|
493
540
|
const results = [];
|
|
494
541
|
for (const target of targets) {
|
|
495
542
|
try {
|
|
@@ -500,7 +547,13 @@ const safeTools = [
|
|
|
500
547
|
results.push({ device: target.friendly_name, error: error.message });
|
|
501
548
|
}
|
|
502
549
|
}
|
|
503
|
-
return {
|
|
550
|
+
return {
|
|
551
|
+
checked: results.length,
|
|
552
|
+
total_candidates: candidates.length,
|
|
553
|
+
remaining,
|
|
554
|
+
...(remaining > 0 ? { next_offset: offset + targets.length } : {}),
|
|
555
|
+
results,
|
|
556
|
+
};
|
|
504
557
|
},
|
|
505
558
|
},
|
|
506
559
|
{
|
|
@@ -526,7 +579,7 @@ const safeTools = [
|
|
|
526
579
|
required: ["time"],
|
|
527
580
|
},
|
|
528
581
|
handler: async (args, ctx) => {
|
|
529
|
-
const payload = { time:
|
|
582
|
+
const payload = { time: num(args, "time", { min: 0, max: 254 }) };
|
|
530
583
|
if (args.device)
|
|
531
584
|
payload.device = String(args.device);
|
|
532
585
|
return ctx.client.request("permit_join", payload);
|
|
@@ -667,7 +720,11 @@ const safeTools = [
|
|
|
667
720
|
group: { type: "string", description: "Group friendly_name or numeric ID." },
|
|
668
721
|
new_name: { type: "string", description: "Required for action=rename." },
|
|
669
722
|
id: { type: "number", description: "Optional numeric ID for action=add." },
|
|
670
|
-
device: { type: "string", description: "Device for member actions.
|
|
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
|
+
},
|
|
671
728
|
force: { type: "boolean", description: "Force removal even if a member device is unreachable." },
|
|
672
729
|
confirm: { type: "boolean", description: "Required for action=remove and action=remove_all_members." },
|
|
673
730
|
},
|
|
@@ -679,7 +736,7 @@ const safeTools = [
|
|
|
679
736
|
case "add":
|
|
680
737
|
return ctx.client.request("group/add", {
|
|
681
738
|
friendly_name: group,
|
|
682
|
-
...(args.id !== undefined ? { id:
|
|
739
|
+
...(args.id !== undefined ? { id: num(args, "id", { min: 1, max: 65_535 }) } : {}),
|
|
683
740
|
});
|
|
684
741
|
case "remove":
|
|
685
742
|
requireConfirm(args, `Removing group '${group}'`);
|
|
@@ -691,11 +748,19 @@ const safeTools = [
|
|
|
691
748
|
case "add_member":
|
|
692
749
|
if (!args.device)
|
|
693
750
|
throw new Error("device is required for action=add_member");
|
|
694
|
-
return ctx.client.request("group/members/add", {
|
|
751
|
+
return ctx.client.request("group/members/add", {
|
|
752
|
+
group,
|
|
753
|
+
device: String(args.device),
|
|
754
|
+
...(args.endpoint !== undefined ? { endpoint: args.endpoint } : {}),
|
|
755
|
+
});
|
|
695
756
|
case "remove_member":
|
|
696
757
|
if (!args.device)
|
|
697
758
|
throw new Error("device is required for action=remove_member");
|
|
698
|
-
return ctx.client.request("group/members/remove", {
|
|
759
|
+
return ctx.client.request("group/members/remove", {
|
|
760
|
+
group,
|
|
761
|
+
device: String(args.device),
|
|
762
|
+
...(args.endpoint !== undefined ? { endpoint: args.endpoint } : {}),
|
|
763
|
+
});
|
|
699
764
|
case "remove_all_members":
|
|
700
765
|
requireConfirm(args, `Removing every member of group '${group}'`);
|
|
701
766
|
return ctx.client.request("group/members/remove_all", { group });
|
|
@@ -712,19 +777,32 @@ const safeTools = [
|
|
|
712
777
|
"control a light directly over Zigbee without a round trip through the coordinator, so it keeps working " +
|
|
713
778
|
"even if the bridge is down. Reversible with action='unbind'; action='clear' removes all binds from the " +
|
|
714
779
|
"source device at once and needs confirm=true, because the previous set cannot be recovered. " +
|
|
715
|
-
"
|
|
716
|
-
"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.",
|
|
717
782
|
inputSchema: {
|
|
718
783
|
type: "object",
|
|
719
784
|
properties: {
|
|
720
785
|
action: { type: "string", enum: ["bind", "unbind", "clear"] },
|
|
721
|
-
from: { type: "string", description: "Source device
|
|
786
|
+
from: { type: "string", description: "Source device friendly_name or ieee_address." },
|
|
722
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
|
+
},
|
|
723
796
|
clusters: {
|
|
724
797
|
type: "array",
|
|
725
798
|
items: { type: "string" },
|
|
726
799
|
description: "Clusters to bind, e.g. ['genOnOff','genLevelCtrl']. Omit to bind all supported clusters.",
|
|
727
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
|
+
},
|
|
728
806
|
confirm: { type: "boolean", description: "Required for action=clear." },
|
|
729
807
|
},
|
|
730
808
|
required: ["action", "from"],
|
|
@@ -732,11 +810,19 @@ const safeTools = [
|
|
|
732
810
|
handler: async (args, ctx) => {
|
|
733
811
|
if (args.action === "clear") {
|
|
734
812
|
requireConfirm(args, `Clearing every binding from '${String(args.from)}'`);
|
|
735
|
-
|
|
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);
|
|
736
818
|
}
|
|
737
819
|
if (!args.to)
|
|
738
820
|
throw new Error("'to' is required for bind and unbind");
|
|
739
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;
|
|
740
826
|
if (Array.isArray(args.clusters) && args.clusters.length > 0)
|
|
741
827
|
payload.clusters = args.clusters;
|
|
742
828
|
return ctx.client.request(args.action === "bind" ? "device/bind" : "device/unbind", payload, 60_000);
|
|
@@ -769,12 +855,14 @@ const safeTools = [
|
|
|
769
855
|
const target = findRaw(raw, String(args.device));
|
|
770
856
|
return ctx.client.request("device/reporting/configure", {
|
|
771
857
|
id: target.friendly_name,
|
|
772
|
-
endpoint:
|
|
858
|
+
endpoint: num(args, "endpoint", { min: 1, max: 255, fallback: 1 }),
|
|
773
859
|
cluster: String(args.cluster),
|
|
774
860
|
attribute: String(args.attribute),
|
|
775
|
-
minimum_report_interval:
|
|
776
|
-
maximum_report_interval:
|
|
777
|
-
...(args.reportable_change !== undefined
|
|
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
|
+
: {}),
|
|
778
866
|
}, 60_000);
|
|
779
867
|
},
|
|
780
868
|
},
|
|
@@ -796,7 +884,6 @@ const fullTools = [
|
|
|
796
884
|
device: DEVICE_ID,
|
|
797
885
|
force: { type: "boolean", description: "Delete from the database even if the device does not respond." },
|
|
798
886
|
block: { type: "boolean", description: "Prevent the device from rejoining." },
|
|
799
|
-
clear_cache: { type: "boolean", description: "Discard cached data so a rejoin re-interviews from scratch." },
|
|
800
887
|
confirm: { type: "boolean", description: "Must be true to proceed." },
|
|
801
888
|
},
|
|
802
889
|
required: ["device", "confirm"],
|
|
@@ -809,7 +896,6 @@ const fullTools = [
|
|
|
809
896
|
id: target.friendly_name,
|
|
810
897
|
force: args.force === true,
|
|
811
898
|
block: args.block === true,
|
|
812
|
-
clear_cache: args.clear_cache === true,
|
|
813
899
|
}, 60_000);
|
|
814
900
|
},
|
|
815
901
|
},
|
|
@@ -847,7 +933,8 @@ const fullTools = [
|
|
|
847
933
|
: action === "unschedule"
|
|
848
934
|
? "device/ota_update/unschedule"
|
|
849
935
|
: "device/ota_update/update";
|
|
850
|
-
|
|
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);
|
|
851
938
|
},
|
|
852
939
|
},
|
|
853
940
|
{
|
|
@@ -897,25 +984,47 @@ const fullTools = [
|
|
|
897
984
|
tier: "full",
|
|
898
985
|
annotations: mutating("Touchlink scan, identify or reset", { destructive: true }),
|
|
899
986
|
description: "Touchlink scan, identify or factory reset. action='scan' and 'identify' are harmless; " +
|
|
900
|
-
"action='factory_reset' is IRREVERSIBLE
|
|
901
|
-
"
|
|
902
|
-
"
|
|
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.",
|
|
903
991
|
inputSchema: {
|
|
904
992
|
type: "object",
|
|
905
993
|
properties: {
|
|
906
994
|
action: { type: "string", enum: ["scan", "identify", "factory_reset"] },
|
|
907
|
-
ieee_address: { type: "string", description: "
|
|
908
|
-
channel: { type: "number", description: "
|
|
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
|
+
},
|
|
909
1001
|
confirm: { type: "boolean", description: "Must be true to proceed." },
|
|
910
1002
|
},
|
|
911
1003
|
required: ["action", "confirm"],
|
|
912
1004
|
},
|
|
913
1005
|
handler: async (args, ctx) => {
|
|
914
1006
|
requireConfirm(args, "Touchlink");
|
|
915
|
-
const
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
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);
|
|
919
1028
|
},
|
|
920
1029
|
},
|
|
921
1030
|
];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zigbee2mqtt-mcp",
|
|
3
|
-
"version": "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": [
|