zigbee2mqtt-mcp 0.3.1 → 0.4.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 +27 -4
- package/dist/client.js +101 -54
- package/dist/index.js +6 -3
- package/dist/redact.js +44 -0
- package/dist/tools.js +81 -19
- package/dist/topics.js +26 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -98,17 +98,19 @@ Tools above the active tier are not registered at all, so a model cannot reach f
|
|
|
98
98
|
| `safe` | **Default.** Read plus non-destructive writes: pairing, options, rename, configure, interview, binding, reporting, groups, state |
|
|
99
99
|
| `full` | Everything, including device removal, OTA flashing, Touchlink and bridge restart |
|
|
100
100
|
|
|
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.
|
|
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
102
|
|
|
103
103
|
Every tool also advertises MCP [tool annotations](https://modelcontextprotocol.io/specification/server/tools) so a client can decide what may run without prompting:
|
|
104
104
|
|
|
105
105
|
| Annotation | Meaning here |
|
|
106
106
|
| --- | --- |
|
|
107
|
-
| `readOnlyHint: true` | The
|
|
108
|
-
| `destructiveHint: true` | `z2m_remove_device`, `z2m_ota_update`, `z2m_touchlink`, `z2m_restart_bridge`, `z2m_set_bridge_options` |
|
|
107
|
+
| `readOnlyHint: true` | The nine read tools. They never change the network. |
|
|
108
|
+
| `destructiveHint: true` | `z2m_remove_device`, `z2m_ota_update`, `z2m_touchlink`, `z2m_restart_bridge`, `z2m_set_bridge_options`, plus `z2m_rename_device`, `z2m_manage_group` and `z2m_bind` |
|
|
109
109
|
| `idempotentHint` | True where repeating the call has no additional effect |
|
|
110
110
|
| `openWorldHint: true` | Always — every tool reaches a live Zigbee network |
|
|
111
111
|
|
|
112
|
+
Annotations describe the tool, not the tier: a `safe` tool can still be destructive. The tier decides what is registered, the annotation tells the client what to ask about.
|
|
113
|
+
|
|
112
114
|
Opt in to the destructive tier only when you want it:
|
|
113
115
|
|
|
114
116
|
```jsonc
|
|
@@ -121,6 +123,7 @@ Opt in to the destructive tier only when you want it:
|
|
|
121
123
|
|
|
122
124
|
| Tool | Purpose |
|
|
123
125
|
| --- | --- |
|
|
126
|
+
| `z2m_connection_status` | Broker reachability, TLS posture and cached message counts — reports instead of throwing when the connection is down |
|
|
124
127
|
| `z2m_bridge_info` | Version, coordinator, channel, PAN ID, permit_join, restart_required, runtime stats |
|
|
125
128
|
| `z2m_list_devices` | Filter and sort devices by type, availability, link quality, battery, pending update |
|
|
126
129
|
| `z2m_get_device` | Exposes, settable options, endpoints, bindings, configured reportings, current state |
|
|
@@ -128,6 +131,7 @@ Opt in to the destructive tier only when you want it:
|
|
|
128
131
|
| `z2m_network_map` | Mesh topology with parent, depth, link quality, orphan detection |
|
|
129
132
|
| `z2m_list_groups` | Groups, members and scenes |
|
|
130
133
|
| `z2m_get_logs` | Bridge logs and lifecycle events, buffered or watched live |
|
|
134
|
+
| `z2m_coordinator_check` | Routers missing from the coordinator's memory (Texas Instruments adapters only) |
|
|
131
135
|
|
|
132
136
|
### Safe writes
|
|
133
137
|
|
|
@@ -135,7 +139,7 @@ Opt in to the destructive tier only when you want it:
|
|
|
135
139
|
|
|
136
140
|
### Full writes
|
|
137
141
|
|
|
138
|
-
`z2m_remove_device`, `z2m_ota_update`, `z2m_restart_bridge`, `z2m_set_bridge_options`, `
|
|
142
|
+
`z2m_remove_device`, `z2m_ota_update`, `z2m_restart_bridge`, `z2m_set_bridge_options`, `z2m_touchlink`
|
|
139
143
|
|
|
140
144
|
## Data availability caveats
|
|
141
145
|
|
|
@@ -148,6 +152,12 @@ Some fields depend on your Zigbee2MQTT configuration. The server detects what is
|
|
|
148
152
|
| `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 |
|
|
149
153
|
| `z2m_coordinator_check` | A Texas Instruments adapter (CC2652/CC1352) | Returns an error on other adapters; `z2m_bridge_info` reports whether it is supported |
|
|
150
154
|
|
|
155
|
+
## Security notes
|
|
156
|
+
|
|
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
|
+
- `safe` mode can actuate anything on the mesh via `z2m_set_state`, including locks, valves and sirens. Use `off` if that matters.
|
|
159
|
+
- `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
|
+
|
|
151
161
|
## Example prompts
|
|
152
162
|
|
|
153
163
|
- "Is my Zigbee network healthy?"
|
|
@@ -165,6 +175,9 @@ npm install
|
|
|
165
175
|
npm run build
|
|
166
176
|
npm run watch
|
|
167
177
|
|
|
178
|
+
# Unit tests. No broker required; they run on every push across Node 20, 22 and 24.
|
|
179
|
+
npm test
|
|
180
|
+
|
|
168
181
|
# Manual smoke test against a real instance
|
|
169
182
|
Z2M_MQTT_URL=mqtt://192.168.1.10:1883 node scripts/smoke.mjs
|
|
170
183
|
Z2M_MQTT_URL=mqtt://192.168.1.10:1883 node scripts/smoke.mjs z2m_list_devices '{"only_problems":true}'
|
|
@@ -179,6 +192,16 @@ Note that an MCP server may receive requests concurrently. When testing ordering
|
|
|
179
192
|
await each response before sending the next, as `roundtrip.mjs` does — piping
|
|
180
193
|
several requests at once will produce misleading results.
|
|
181
194
|
|
|
195
|
+
The unit tests cover health classification, capability detection, topic routing,
|
|
196
|
+
write-mode gating and configuration parsing. They are broker-free by design, so
|
|
197
|
+
anything that needs a live mesh belongs in `scripts/` instead.
|
|
198
|
+
|
|
199
|
+
Releases are tag-driven: `npm version <patch|minor|major>` then
|
|
200
|
+
`git push --follow-tags`. CI publishes to npm with provenance, rewrites
|
|
201
|
+
`server.json`'s version from the tag and publishes to the MCP Registry, then
|
|
202
|
+
creates the GitHub release. The `version` committed in `server.json` is therefore
|
|
203
|
+
not authoritative — the tag is.
|
|
204
|
+
|
|
182
205
|
## Safety
|
|
183
206
|
|
|
184
207
|
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.
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,21 @@
|
|
|
1
1
|
import mqtt from "mqtt";
|
|
2
|
+
import { redactUrl, scrubSecrets } from "./redact.js";
|
|
3
|
+
import { classifyTopic } from "./topics.js";
|
|
4
|
+
/**
|
|
5
|
+
* Correlates bridge/request with bridge/response. Both sides must build the key
|
|
6
|
+
* identically or every write tool times out, so it lives in one place.
|
|
7
|
+
*/
|
|
8
|
+
export function waiterKey(subTopic, transaction) {
|
|
9
|
+
return `${subTopic}|${transaction ?? ""}`;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The broker accepted the connection but published no Zigbee2MQTT bridge data.
|
|
13
|
+
* Distinguished from a connection failure because the remedy is different: the
|
|
14
|
+
* base topic is wrong, or Zigbee2MQTT is not running against this broker.
|
|
15
|
+
*/
|
|
16
|
+
export class NoBridgeDataError extends Error {
|
|
17
|
+
name = "NoBridgeDataError";
|
|
18
|
+
}
|
|
2
19
|
const LOG_BUFFER = 1000;
|
|
3
20
|
const EVENT_BUFFER = 200;
|
|
4
21
|
/**
|
|
@@ -36,9 +53,12 @@ export class Z2MClient {
|
|
|
36
53
|
logs = [];
|
|
37
54
|
events = [];
|
|
38
55
|
waiters = new Map();
|
|
56
|
+
/** Never interpolate config.mqttUrl into a message; it may carry credentials. */
|
|
57
|
+
safeUrl;
|
|
39
58
|
constructor(config, log) {
|
|
40
59
|
this.config = config;
|
|
41
60
|
this.log = log;
|
|
61
|
+
this.safeUrl = redactUrl(config.mqttUrl);
|
|
42
62
|
}
|
|
43
63
|
// ---------------------------------------------------------------- lifecycle
|
|
44
64
|
async connect() {
|
|
@@ -68,7 +88,7 @@ export class Z2MClient {
|
|
|
68
88
|
key: config.key,
|
|
69
89
|
};
|
|
70
90
|
return new Promise((resolve, reject) => {
|
|
71
|
-
this.log.debug(`connecting to ${
|
|
91
|
+
this.log.debug(`connecting to ${this.safeUrl}`);
|
|
72
92
|
const client = mqtt.connect(config.mqttUrl, options);
|
|
73
93
|
this.client = client;
|
|
74
94
|
let settled = false;
|
|
@@ -80,10 +100,10 @@ export class Z2MClient {
|
|
|
80
100
|
this.client = null;
|
|
81
101
|
reject(error);
|
|
82
102
|
};
|
|
83
|
-
const timer = setTimeout(() => fail(new Error(`Timed out connecting to ${
|
|
103
|
+
const timer = setTimeout(() => fail(new Error(`Timed out connecting to ${this.safeUrl} after ${config.connectTimeoutMs}ms`)), config.connectTimeoutMs);
|
|
84
104
|
client.on("error", (error) => {
|
|
85
|
-
this.log.error("mqtt error:", error.message);
|
|
86
|
-
fail(new Error(`MQTT connection to ${
|
|
105
|
+
this.log.error("mqtt error:", scrubSecrets(error.message, config));
|
|
106
|
+
fail(new Error(`MQTT connection to ${this.safeUrl} failed: ${scrubSecrets(error.message, config)}`));
|
|
87
107
|
});
|
|
88
108
|
client.on("message", (topic, payload) => this.handleMessage(topic, payload));
|
|
89
109
|
client.on("connect", () => {
|
|
@@ -113,7 +133,7 @@ export class Z2MClient {
|
|
|
113
133
|
await sleep(25);
|
|
114
134
|
}
|
|
115
135
|
if (!this.bridge.has("devices")) {
|
|
116
|
-
throw new
|
|
136
|
+
throw new NoBridgeDataError(`Connected to the broker but received no retained '${this.config.baseTopic}/bridge/devices' ` +
|
|
117
137
|
`message within ${timeoutMs}ms. Check that Zigbee2MQTT is running and that Z2M_BASE_TOPIC ` +
|
|
118
138
|
`(currently '${this.config.baseTopic}') matches its mqtt.base_topic setting.`);
|
|
119
139
|
}
|
|
@@ -140,67 +160,66 @@ export class Z2MClient {
|
|
|
140
160
|
await new Promise((resolve) => client.end(false, {}, () => resolve()));
|
|
141
161
|
}
|
|
142
162
|
// ----------------------------------------------------------------- messages
|
|
163
|
+
/** Exposed for tests; the live path is the client's 'message' event. */
|
|
143
164
|
handleMessage(topic, payload) {
|
|
144
|
-
const
|
|
145
|
-
if (
|
|
165
|
+
const route = classifyTopic(this.config.baseTopic, topic);
|
|
166
|
+
if (route.kind === "foreign")
|
|
146
167
|
return;
|
|
147
168
|
this.lastMessageAt = Date.now();
|
|
148
|
-
const rest = topic.slice(prefix.length);
|
|
149
169
|
const raw = payload.toString();
|
|
150
170
|
const parsed = safeParse(raw);
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
171
|
+
switch (route.kind) {
|
|
172
|
+
case "response":
|
|
173
|
+
this.resolveWaiter(route.subTopic, parsed);
|
|
174
|
+
return;
|
|
175
|
+
case "logging": {
|
|
176
|
+
const entry = parsed;
|
|
177
|
+
if (entry && typeof entry === "object") {
|
|
178
|
+
push(this.logs, LOG_BUFFER, {
|
|
179
|
+
received_at: new Date().toISOString(),
|
|
180
|
+
level: String(entry.level ?? "info"),
|
|
181
|
+
message: String(entry.message ?? raw),
|
|
182
|
+
namespace: entry.namespace,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
164
186
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
187
|
+
case "event": {
|
|
188
|
+
const event = parsed;
|
|
189
|
+
if (event && typeof event === "object") {
|
|
190
|
+
push(this.events, EVENT_BUFFER, {
|
|
191
|
+
received_at: new Date().toISOString(),
|
|
192
|
+
type: String(event.type ?? "unknown"),
|
|
193
|
+
data: event.data ?? {},
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return;
|
|
175
197
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
if (parsed && typeof parsed === "object") {
|
|
195
|
-
this.deviceState.set(rest, parsed);
|
|
198
|
+
case "bridge":
|
|
199
|
+
this.bridge.set(route.name, parsed ?? raw);
|
|
200
|
+
this.bridgeRevision++;
|
|
201
|
+
return;
|
|
202
|
+
case "availability": {
|
|
203
|
+
const state = typeof parsed === "object" && parsed !== null
|
|
204
|
+
? String(parsed.state ?? raw)
|
|
205
|
+
: raw;
|
|
206
|
+
this.availability.set(route.device, state);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
case "command":
|
|
210
|
+
return;
|
|
211
|
+
case "state":
|
|
212
|
+
if (parsed && typeof parsed === "object") {
|
|
213
|
+
this.deviceState.set(route.device, parsed);
|
|
214
|
+
}
|
|
215
|
+
return;
|
|
196
216
|
}
|
|
197
217
|
}
|
|
198
218
|
resolveWaiter(subTopic, parsed) {
|
|
199
219
|
if (!parsed || typeof parsed !== "object")
|
|
200
220
|
return;
|
|
201
221
|
const response = parsed;
|
|
202
|
-
const
|
|
203
|
-
const waiter = this.waiters.get(key);
|
|
222
|
+
const waiter = this.waiters.get(waiterKey(subTopic, response.transaction));
|
|
204
223
|
if (waiter)
|
|
205
224
|
waiter(response);
|
|
206
225
|
}
|
|
@@ -216,7 +235,7 @@ export class Z2MClient {
|
|
|
216
235
|
throw new Error("MQTT client is not connected");
|
|
217
236
|
const timeout = timeoutMs ?? this.config.requestTimeoutMs;
|
|
218
237
|
const transaction = `mcp-${++this.transactionCounter}`;
|
|
219
|
-
const key =
|
|
238
|
+
const key = waiterKey(subTopic, transaction);
|
|
220
239
|
const revisionBefore = this.bridgeRevision;
|
|
221
240
|
const result = await new Promise((resolve, reject) => {
|
|
222
241
|
const timer = setTimeout(() => {
|
|
@@ -287,6 +306,34 @@ export class Z2MClient {
|
|
|
287
306
|
availability: this.availability,
|
|
288
307
|
};
|
|
289
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Deliberately does not connect: this is what a caller reaches for when the
|
|
311
|
+
* connection is the thing under suspicion.
|
|
312
|
+
*/
|
|
313
|
+
status() {
|
|
314
|
+
return {
|
|
315
|
+
connected: this.client?.connected === true,
|
|
316
|
+
broker_url: this.safeUrl,
|
|
317
|
+
base_topic: this.config.baseTopic,
|
|
318
|
+
client_id: this.config.clientId,
|
|
319
|
+
write_mode: this.config.writeMode,
|
|
320
|
+
tls: {
|
|
321
|
+
enabled: /^(mqtts|wss):/.test(this.config.mqttUrl),
|
|
322
|
+
reject_unauthorized: this.config.rejectUnauthorized,
|
|
323
|
+
custom_ca: this.config.ca !== undefined,
|
|
324
|
+
client_certificate: this.config.cert !== undefined,
|
|
325
|
+
},
|
|
326
|
+
authenticated: this.config.username !== undefined,
|
|
327
|
+
cached: {
|
|
328
|
+
bridge_topics: this.bridge.size,
|
|
329
|
+
device_state: this.deviceState.size,
|
|
330
|
+
availability: this.availability.size,
|
|
331
|
+
logs: this.logs.length,
|
|
332
|
+
events: this.events.length,
|
|
333
|
+
},
|
|
334
|
+
last_message_at: this.lastMessageAt ? new Date(this.lastMessageAt).toISOString() : null,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
290
337
|
recentLogs() {
|
|
291
338
|
return this.logs;
|
|
292
339
|
}
|
package/dist/index.js
CHANGED
|
@@ -5,6 +5,7 @@ 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
9
|
import { selectTools } from "./tools.js";
|
|
9
10
|
const { version } = createRequire(import.meta.url)("../package.json");
|
|
10
11
|
async function main() {
|
|
@@ -25,7 +26,7 @@ async function main() {
|
|
|
25
26
|
const tools = selectTools(config.writeMode);
|
|
26
27
|
const byName = new Map(tools.map((tool) => [tool.name, tool]));
|
|
27
28
|
log.info(`write mode '${config.writeMode}' exposes ${tools.length} tools against ` +
|
|
28
|
-
`${config.mqttUrl} (base topic '${config.baseTopic}')`);
|
|
29
|
+
`${redactUrl(config.mqttUrl)} (base topic '${config.baseTopic}')`);
|
|
29
30
|
const server = new Server({ name: "zigbee2mqtt-mcp", version }, { capabilities: { tools: {} } });
|
|
30
31
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
31
32
|
tools: tools.map(({ name, description, inputSchema, annotations }) => ({
|
|
@@ -63,10 +64,12 @@ async function main() {
|
|
|
63
64
|
};
|
|
64
65
|
}
|
|
65
66
|
catch (error) {
|
|
66
|
-
|
|
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);
|
|
67
70
|
return {
|
|
68
71
|
isError: true,
|
|
69
|
-
content: [{ type: "text", text: `${tool.name} failed: ${
|
|
72
|
+
content: [{ type: "text", text: `${tool.name} failed: ${message}` }],
|
|
70
73
|
};
|
|
71
74
|
}
|
|
72
75
|
});
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Schemes mqtt.js accepts. Anything else is not a broker URL we should echo. */
|
|
2
|
+
const BROKER_SCHEME = /^(mqtt|mqtts|tcp|tls|ssl|ws|wss):\/\//i;
|
|
3
|
+
/** Any URL userinfo, whatever the scheme. */
|
|
4
|
+
const USERINFO = /([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+@/gi;
|
|
5
|
+
/**
|
|
6
|
+
* Broker URLs may carry credentials as `mqtt://user:pass@host`, and ws/wss
|
|
7
|
+
* brokers accept tokens in the query string. Anything echoed back to a model
|
|
8
|
+
* or written to a log must go through here first.
|
|
9
|
+
*/
|
|
10
|
+
export function redactUrl(url) {
|
|
11
|
+
// A schemeless value still parses: new URL('user:pass@host') reads 'user:' as
|
|
12
|
+
// the scheme, leaving username and password empty, so it would pass through
|
|
13
|
+
// untouched. Refuse to echo anything that is not recognisably a broker URL.
|
|
14
|
+
if (!BROKER_SCHEME.test(url))
|
|
15
|
+
return "<malformed broker URL>";
|
|
16
|
+
try {
|
|
17
|
+
const parsed = new URL(url);
|
|
18
|
+
if (parsed.username)
|
|
19
|
+
parsed.username = "***";
|
|
20
|
+
if (parsed.password)
|
|
21
|
+
parsed.password = "***";
|
|
22
|
+
parsed.search = "";
|
|
23
|
+
parsed.hash = "";
|
|
24
|
+
return parsed.toString();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// The scheme is known-good here, so this keeps the transport diagnosable.
|
|
28
|
+
return `${url.slice(0, url.indexOf("://") + 3)}***`;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Last line of defence for text that leaves the process: errors bubbling up
|
|
33
|
+
* from mqtt.js quote whatever URL they were given.
|
|
34
|
+
*/
|
|
35
|
+
export function scrubSecrets(text, config) {
|
|
36
|
+
let out = text.replace(USERINFO, "$1***@");
|
|
37
|
+
const password = config.password;
|
|
38
|
+
// A short password would match innocuous substrings and mangle the message;
|
|
39
|
+
// userinfo in a URL is already covered above.
|
|
40
|
+
if (password && password.length >= 6)
|
|
41
|
+
out = out.split(password).join("***");
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=redact.js.map
|
package/dist/tools.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { NoBridgeDataError } from "./client.js";
|
|
2
|
+
import { scrubSecrets } from "./redact.js";
|
|
1
3
|
import { buildHealthReport, detectCapabilities, isCoordinator, normalize, } from "./devices.js";
|
|
2
4
|
/** Every tool reaches a live Zigbee network, so openWorldHint is always true. */
|
|
3
5
|
const readOnly = (title) => ({
|
|
@@ -35,8 +37,13 @@ const COLLECT_SECONDS = {
|
|
|
35
37
|
description: "Listen for live device traffic for this many seconds before answering, to populate linkquality, " +
|
|
36
38
|
"battery and OTA fields that Zigbee2MQTT does not publish as retained messages. Max 120.",
|
|
37
39
|
};
|
|
38
|
-
|
|
39
|
-
|
|
40
|
+
/** Exported for tests; disambiguation rules are easy to regress. */
|
|
41
|
+
export function findRaw(raw, id) {
|
|
42
|
+
const needle = id.trim().toLowerCase();
|
|
43
|
+
// Every name contains the empty string, so an unguarded blank would match the
|
|
44
|
+
// first device on a single-device estate.
|
|
45
|
+
if (!needle)
|
|
46
|
+
throw new Error("A device friendly_name or ieee_address is required.");
|
|
40
47
|
const match = raw.find((d) => d.friendly_name.toLowerCase() === needle || d.ieee_address.toLowerCase() === needle);
|
|
41
48
|
if (match)
|
|
42
49
|
return match;
|
|
@@ -77,6 +84,54 @@ function summariseExposes(exposes) {
|
|
|
77
84
|
}
|
|
78
85
|
// ----------------------------------------------------------------- read tools
|
|
79
86
|
const readTools = [
|
|
87
|
+
{
|
|
88
|
+
name: "z2m_connection_status",
|
|
89
|
+
tier: "read",
|
|
90
|
+
annotations: readOnly("Check MQTT connection"),
|
|
91
|
+
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.",
|
|
97
|
+
inputSchema: EMPTY,
|
|
98
|
+
handler: async (_args, ctx) => {
|
|
99
|
+
let brokerReachable = true;
|
|
100
|
+
let zigbee2mqttResponding = true;
|
|
101
|
+
let error;
|
|
102
|
+
try {
|
|
103
|
+
await ctx.client.connect();
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
error = scrubSecrets(e.message, ctx.config);
|
|
107
|
+
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;
|
|
111
|
+
}
|
|
112
|
+
const status = ctx.client.status();
|
|
113
|
+
const hints = [];
|
|
114
|
+
if (!brokerReachable) {
|
|
115
|
+
hints.push("Could not reach the broker. Check that Z2M_MQTT_URL points at the MQTT broker Zigbee2MQTT " +
|
|
116
|
+
"uses rather than the Zigbee2MQTT frontend port, and that any credentials are correct.");
|
|
117
|
+
}
|
|
118
|
+
else if (!zigbee2mqttResponding || status.cached.bridge_topics === 0) {
|
|
119
|
+
hints.push(`The broker is reachable, but nothing was published under '${status.base_topic}/bridge/'. ` +
|
|
120
|
+
"Either Zigbee2MQTT is not running against this broker, or Z2M_BASE_TOPIC does not match " +
|
|
121
|
+
"its mqtt.base_topic setting.");
|
|
122
|
+
}
|
|
123
|
+
if (status.tls.enabled && !status.tls.reject_unauthorized) {
|
|
124
|
+
hints.push("TLS certificate verification is disabled, so the broker's identity is not checked.");
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
broker_reachable: brokerReachable,
|
|
128
|
+
zigbee2mqtt_responding: zigbee2mqttResponding,
|
|
129
|
+
...status,
|
|
130
|
+
error,
|
|
131
|
+
hints,
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
},
|
|
80
135
|
{
|
|
81
136
|
name: "z2m_bridge_info",
|
|
82
137
|
tier: "read",
|
|
@@ -388,6 +443,18 @@ const readTools = [
|
|
|
388
443
|
};
|
|
389
444
|
},
|
|
390
445
|
},
|
|
446
|
+
{
|
|
447
|
+
name: "z2m_coordinator_check",
|
|
448
|
+
tier: "read",
|
|
449
|
+
annotations: readOnly("Check coordinator memory"),
|
|
450
|
+
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 " +
|
|
454
|
+
"healthy. Use z2m_network_map for a topology view on any adapter.",
|
|
455
|
+
inputSchema: EMPTY,
|
|
456
|
+
handler: async (_args, ctx) => ctx.client.request("coordinator_check", {}, 60_000),
|
|
457
|
+
},
|
|
391
458
|
];
|
|
392
459
|
// ----------------------------------------------------------- safe write tools
|
|
393
460
|
const safeTools = [
|
|
@@ -480,7 +547,7 @@ const safeTools = [
|
|
|
480
547
|
{
|
|
481
548
|
name: "z2m_rename_device",
|
|
482
549
|
tier: "safe",
|
|
483
|
-
annotations: mutating("Rename device"),
|
|
550
|
+
annotations: mutating("Rename device", { destructive: true }),
|
|
484
551
|
description: "Rename a device's friendly_name. Renaming changes its MQTT topic, so anything referencing the old " +
|
|
485
552
|
"name (automations, dashboards, scripts) breaks until updated — this is reversible only by renaming " +
|
|
486
553
|
"back. Set homeassistant_rename to also rename the Home Assistant entity. " +
|
|
@@ -572,12 +639,13 @@ const safeTools = [
|
|
|
572
639
|
{
|
|
573
640
|
name: "z2m_manage_group",
|
|
574
641
|
tier: "safe",
|
|
575
|
-
annotations: mutating("Manage groups"),
|
|
642
|
+
annotations: mutating("Manage groups", { destructive: true }),
|
|
576
643
|
description: "Create or remove groups, rename them, and add or remove device members. Groups let a single Zigbee " +
|
|
577
644
|
"multicast control many devices, which is far more responsive than commanding each device in turn. " +
|
|
578
645
|
"Removing a group does not affect the devices themselves, but fails if a member is unreachable unless " +
|
|
579
646
|
"force is set — with force the device keeps the group membership internally. Use z2m_list_groups to " +
|
|
580
|
-
"inspect groups first, and z2m_set_state to control a group once created."
|
|
647
|
+
"inspect groups first, and z2m_set_state to control a group once created. The remove and " +
|
|
648
|
+
"remove_all_members actions discard configuration and need confirm=true.",
|
|
581
649
|
inputSchema: {
|
|
582
650
|
type: "object",
|
|
583
651
|
properties: {
|
|
@@ -590,6 +658,7 @@ const safeTools = [
|
|
|
590
658
|
id: { type: "number", description: "Optional numeric ID for action=add." },
|
|
591
659
|
device: { type: "string", description: "Device for member actions. Append /ENDPOINT to target an endpoint." },
|
|
592
660
|
force: { type: "boolean", description: "Force removal even if a member device is unreachable." },
|
|
661
|
+
confirm: { type: "boolean", description: "Required for action=remove and action=remove_all_members." },
|
|
593
662
|
},
|
|
594
663
|
required: ["action", "group"],
|
|
595
664
|
},
|
|
@@ -602,6 +671,7 @@ const safeTools = [
|
|
|
602
671
|
...(args.id !== undefined ? { id: Number(args.id) } : {}),
|
|
603
672
|
});
|
|
604
673
|
case "remove":
|
|
674
|
+
requireConfirm(args, `Removing group '${group}'`);
|
|
605
675
|
return ctx.client.request("group/remove", { id: group, force: args.force === true });
|
|
606
676
|
case "rename":
|
|
607
677
|
if (!args.new_name)
|
|
@@ -616,6 +686,7 @@ const safeTools = [
|
|
|
616
686
|
throw new Error("device is required for action=remove_member");
|
|
617
687
|
return ctx.client.request("group/members/remove", { group, device: String(args.device) });
|
|
618
688
|
case "remove_all_members":
|
|
689
|
+
requireConfirm(args, `Removing every member of group '${group}'`);
|
|
619
690
|
return ctx.client.request("group/members/remove_all", { group });
|
|
620
691
|
default:
|
|
621
692
|
throw new Error(`Unknown action '${args.action}'`);
|
|
@@ -625,11 +696,12 @@ const safeTools = [
|
|
|
625
696
|
{
|
|
626
697
|
name: "z2m_bind",
|
|
627
698
|
tier: "safe",
|
|
628
|
-
annotations: mutating("Bind or unbind clusters"),
|
|
699
|
+
annotations: mutating("Bind or unbind clusters", { destructive: true }),
|
|
629
700
|
description: "Bind or unbind clusters between two devices, or between a device and a group. Binding lets a remote " +
|
|
630
701
|
"control a light directly over Zigbee without a round trip through the coordinator, so it keeps working " +
|
|
631
702
|
"even if the bridge is down. Reversible with action='unbind'; action='clear' removes all binds from the " +
|
|
632
|
-
"source device at once
|
|
703
|
+
"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 " +
|
|
633
705
|
"z2m_get_device endpoints first. Both devices must be awake.",
|
|
634
706
|
inputSchema: {
|
|
635
707
|
type: "object",
|
|
@@ -642,11 +714,13 @@ const safeTools = [
|
|
|
642
714
|
items: { type: "string" },
|
|
643
715
|
description: "Clusters to bind, e.g. ['genOnOff','genLevelCtrl']. Omit to bind all supported clusters.",
|
|
644
716
|
},
|
|
717
|
+
confirm: { type: "boolean", description: "Required for action=clear." },
|
|
645
718
|
},
|
|
646
719
|
required: ["action", "from"],
|
|
647
720
|
},
|
|
648
721
|
handler: async (args, ctx) => {
|
|
649
722
|
if (args.action === "clear") {
|
|
723
|
+
requireConfirm(args, `Clearing every binding from '${String(args.from)}'`);
|
|
650
724
|
return ctx.client.request("device/binds/clear", { id: String(args.from) }, 60_000);
|
|
651
725
|
}
|
|
652
726
|
if (!args.to)
|
|
@@ -807,18 +881,6 @@ const fullTools = [
|
|
|
807
881
|
return ctx.client.request("options", { options: args.options }, 30_000);
|
|
808
882
|
},
|
|
809
883
|
},
|
|
810
|
-
{
|
|
811
|
-
name: "z2m_coordinator_check",
|
|
812
|
-
tier: "full",
|
|
813
|
-
annotations: mutating("Check coordinator memory", { idempotent: true }),
|
|
814
|
-
description: "Check whether any routers are missing from the coordinator's memory, which causes pairing failures and " +
|
|
815
|
-
"devices dropping off. Changes nothing, but queries the coordinator directly. Only supported on Texas " +
|
|
816
|
-
"Instruments adapters (CC2652/CC1352); other adapters return an error — z2m_bridge_info reports whether " +
|
|
817
|
-
"yours qualifies under capabilities.coordinator_check. Returns {missing_routers[]}; an empty list is " +
|
|
818
|
-
"healthy. Use z2m_network_map for a topology view on any adapter.",
|
|
819
|
-
inputSchema: EMPTY,
|
|
820
|
-
handler: async (_args, ctx) => ctx.client.request("coordinator_check", {}, 60_000),
|
|
821
|
-
},
|
|
822
884
|
{
|
|
823
885
|
name: "z2m_touchlink",
|
|
824
886
|
tier: "full",
|
package/dist/topics.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const AVAILABILITY_SUFFIX = "/availability";
|
|
2
|
+
const RESPONSE_PREFIX = "bridge/response/";
|
|
3
|
+
const COMMAND = /\/(set|get)(\/|$)/;
|
|
4
|
+
export function classifyTopic(baseTopic, topic) {
|
|
5
|
+
const prefix = `${baseTopic}/`;
|
|
6
|
+
if (!topic.startsWith(prefix))
|
|
7
|
+
return { kind: "foreign" };
|
|
8
|
+
const rest = topic.slice(prefix.length);
|
|
9
|
+
if (rest.startsWith(RESPONSE_PREFIX)) {
|
|
10
|
+
return { kind: "response", subTopic: rest.slice(RESPONSE_PREFIX.length) };
|
|
11
|
+
}
|
|
12
|
+
if (rest === "bridge/logging")
|
|
13
|
+
return { kind: "logging" };
|
|
14
|
+
if (rest === "bridge/event")
|
|
15
|
+
return { kind: "event" };
|
|
16
|
+
if (rest.startsWith("bridge/"))
|
|
17
|
+
return { kind: "bridge", name: rest.slice("bridge/".length) };
|
|
18
|
+
// Friendly names may contain '/', so match on the suffix rather than splitting.
|
|
19
|
+
if (rest.endsWith(AVAILABILITY_SUFFIX)) {
|
|
20
|
+
return { kind: "availability", device: rest.slice(0, -AVAILABILITY_SUFFIX.length) };
|
|
21
|
+
}
|
|
22
|
+
if (COMMAND.test(rest))
|
|
23
|
+
return { kind: "command" };
|
|
24
|
+
return { kind: "state", device: rest };
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=topics.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zigbee2mqtt-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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": [
|
|
@@ -40,6 +40,7 @@
|
|
|
40
40
|
"build": "tsc",
|
|
41
41
|
"watch": "tsc --watch",
|
|
42
42
|
"start": "node dist/index.js",
|
|
43
|
+
"test": "tsc -p tsconfig.test.json && cd dist-test && node --test",
|
|
43
44
|
"prepublishOnly": "npm run build"
|
|
44
45
|
},
|
|
45
46
|
"dependencies": {
|