@orellbuehler/homeassistant-mcp 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +142 -39
  2. package/bin/homeassistant-mcp.js +51 -0
  3. package/binaries/darwin-arm64/homeassistant-mcp +0 -0
  4. package/binaries/darwin-x64/homeassistant-mcp +0 -0
  5. package/binaries/linux-arm64/homeassistant-mcp +0 -0
  6. package/binaries/linux-x64/homeassistant-mcp +0 -0
  7. package/binaries/win32-x64/homeassistant-mcp.exe +0 -0
  8. package/package.json +5 -38
  9. package/dist/config.js +0 -26
  10. package/dist/hass/format.js +0 -38
  11. package/dist/hass/rest.js +0 -50
  12. package/dist/hass/ws.js +0 -80
  13. package/dist/index.js +0 -17
  14. package/dist/server.js +0 -9
  15. package/dist/tools/auth.js +0 -191
  16. package/dist/tools/automations.js +0 -62
  17. package/dist/tools/backup.js +0 -375
  18. package/dist/tools/control.js +0 -133
  19. package/dist/tools/dashboards.js +0 -206
  20. package/dist/tools/diagnostics.js +0 -537
  21. package/dist/tools/energy.js +0 -235
  22. package/dist/tools/entities.js +0 -57
  23. package/dist/tools/hacs.js +0 -52
  24. package/dist/tools/helpers.js +0 -98
  25. package/dist/tools/history.js +0 -57
  26. package/dist/tools/integrations.js +0 -538
  27. package/dist/tools/lists.js +0 -216
  28. package/dist/tools/organization.js +0 -548
  29. package/dist/tools/raw.js +0 -41
  30. package/dist/tools/registry.js +0 -195
  31. package/dist/tools/reload.js +0 -40
  32. package/dist/tools/resources.js +0 -56
  33. package/dist/tools/scripts.js +0 -206
  34. package/dist/tools/services.js +0 -33
  35. package/dist/tools/statistics.js +0 -363
  36. package/dist/tools/system.js +0 -57
  37. package/dist/tools/templates.js +0 -21
  38. package/dist/tools/trace.js +0 -74
  39. package/dist/tools/zha.js +0 -121
  40. package/dist/toolsets.js +0 -356
@@ -1,537 +0,0 @@
1
- import { z } from "zod";
2
- import { ok, err, domainOf } from "../hass/format.js";
3
- const LEVEL_NAMES = {
4
- 0: "NOTSET",
5
- 10: "DEBUG",
6
- 20: "INFO",
7
- 30: "WARNING",
8
- 40: "ERROR",
9
- 50: "CRITICAL",
10
- };
11
- const TARGET_KEYS = ["entity_id", "device_id", "area_id", "floor_id", "label_id"];
12
- const idList = () => z.union([z.string(), z.array(z.string())]);
13
- const targetIds = () => ({
14
- entity_id: idList().optional().describe("entity_id or list of entity_ids"),
15
- device_id: idList().optional().describe("device registry id or list (see list_devices)"),
16
- area_id: idList().optional().describe("area_id or list (see list_areas)"),
17
- floor_id: idList().optional().describe("floor_id or list"),
18
- label_id: idList().optional().describe("label_id or list (see list_labels)"),
19
- });
20
- const targetSchema = () => z
21
- .object({
22
- ...targetIds(),
23
- exclude: z
24
- .object(targetIds())
25
- .optional()
26
- .describe("Same keys; entities these resolve to are removed from the target"),
27
- })
28
- .describe("Target selection as used in an action's 'target:' block: entity_id, device_id, area_id, floor_id and/or label_id");
29
- const logLevelSchema = z
30
- .enum(["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"])
31
- .describe("Log level; NOTSET removes the override so the logger inherits its parent's level");
32
- const persistenceSchema = z
33
- .enum(["none", "once", "permanent"])
34
- .optional()
35
- .describe("How long the level lasts: 'none' (default) until Home Assistant restarts, 'once' for the next restart only, 'permanent' across all restarts");
36
- const capabilitiesAutomation = z
37
- .record(z.unknown())
38
- .describe("One item exactly as returned by list_device_automations (platform/domain/device_id/type/...)");
39
- function iso(seconds) {
40
- if (typeof seconds !== "number" || Number.isNaN(seconds))
41
- return null;
42
- return new Date(seconds * 1000).toISOString();
43
- }
44
- function requireTarget(target) {
45
- const present = TARGET_KEYS.some((key) => {
46
- const value = target[key];
47
- return Array.isArray(value) ? value.length > 0 : typeof value === "string" && value !== "";
48
- });
49
- if (!present) {
50
- throw new Error("target needs at least one of entity_id, device_id, area_id, floor_id or label_id");
51
- }
52
- }
53
- function targetPayload(target, expand_group, primary_entities_only) {
54
- requireTarget(target);
55
- const payload = { target };
56
- if (expand_group !== undefined)
57
- payload.expand_group = expand_group;
58
- if (primary_entities_only !== undefined)
59
- payload.primary_entities_only = primary_entities_only;
60
- return payload;
61
- }
62
- export function registerDiagnosticsTools(server, ws) {
63
- server.tool("list_system_log", "List the Home Assistant system log via the WebSocket API (system_log/list): de-duplicated WARNING-and-above entries since the last restart, newest first (HA keeps 50 distinct entries by default). Each entry has the logger name, level, up to 5 distinct message texts, source [file, line], count, first_occurred, timestamp and has_exception. Structured alternative to get_error_log — good first stop for why an integration or automation misbehaves. Tracebacks are only included with include_exceptions. Requires an admin token.", {
64
- level: z
65
- .enum(["WARNING", "ERROR", "CRITICAL"])
66
- .optional()
67
- .describe("Only entries of exactly this level"),
68
- search: z
69
- .string()
70
- .optional()
71
- .describe("Case-insensitive text to find in the logger name, messages or source file"),
72
- limit: z
73
- .number()
74
- .int()
75
- .min(1)
76
- .optional()
77
- .describe("Max entries to return (default 20, newest first)"),
78
- include_exceptions: z
79
- .boolean()
80
- .optional()
81
- .describe("Include the full traceback text of each entry (can be long)"),
82
- }, async ({ level, search, limit, include_exceptions }) => {
83
- try {
84
- const list = ((await ws.command("system_log/list")) ?? []);
85
- const needle = search?.toLowerCase();
86
- const matched = list.filter((e) => {
87
- if (level && e.level !== level)
88
- return false;
89
- if (!needle)
90
- return true;
91
- const haystack = [e.name ?? "", ...(e.message ?? []), String(e.source?.[0] ?? "")];
92
- return haystack.some((part) => part.toLowerCase().includes(needle));
93
- });
94
- const entries = matched.slice(0, limit ?? 20).map((e) => {
95
- const row = {
96
- name: e.name,
97
- level: e.level,
98
- message: e.message,
99
- source: e.source,
100
- count: e.count,
101
- first_occurred: iso(e.first_occurred),
102
- timestamp: iso(e.timestamp),
103
- has_exception: Boolean(e.exception),
104
- };
105
- if (include_exceptions && e.exception)
106
- row.exception = e.exception;
107
- return row;
108
- });
109
- return ok({ count: entries.length, total: matched.length, entries });
110
- }
111
- catch (e) {
112
- return err(e);
113
- }
114
- });
115
- server.tool("list_repairs", "List the active issues on Home Assistant's Repairs dashboard via the WebSocket API (repairs/list_issues): domain, issue_id, severity (critical/error/warning), translation_key and translation_placeholders (what the issue is about), is_fixable, ignored, breaks_in_ha_version, learn_more_url and created. Check this after upgrades or when an integration misbehaves. Use get_repair_issue_data for an issue's payload.", {
116
- include_ignored: z
117
- .boolean()
118
- .optional()
119
- .describe("Include issues the user has ignored (default true)"),
120
- }, async ({ include_ignored }) => {
121
- try {
122
- const res = (await ws.command("repairs/list_issues"));
123
- let issues = res?.issues ?? [];
124
- if (include_ignored === false)
125
- issues = issues.filter((i) => !i.ignored);
126
- return ok({ count: issues.length, issues });
127
- }
128
- catch (e) {
129
- return err(e);
130
- }
131
- });
132
- server.tool("get_repair_issue_data", "Get the data payload attached to one repair issue via the WebSocket API (repairs/get_issue_data) — the integration-specific details behind an entry from list_repairs. Returns { issue_data } (null when the integration attached none). Errors with unknown_issue if the domain/issue_id pair does not exist.", {
133
- domain: z.string().describe("The issue's 'domain' from list_repairs"),
134
- issue_id: z.string().describe("The issue's 'issue_id' from list_repairs"),
135
- }, async ({ domain, issue_id }) => {
136
- try {
137
- return ok(await ws.command("repairs/get_issue_data", { domain, issue_id }));
138
- }
139
- catch (e) {
140
- return err(e);
141
- }
142
- });
143
- server.tool("ignore_repair", "Ignore or un-ignore a repair issue via the WebSocket API (repairs/ignore_issue). Ignoring only hides the issue from the Repairs dashboard (it records the current HA version as dismissed_version); it does not fix the underlying problem, and ignore=false restores it. Get domain and issue_id from list_repairs.", {
144
- domain: z.string().describe("The issue's 'domain' from list_repairs"),
145
- issue_id: z.string().describe("The issue's 'issue_id' from list_repairs"),
146
- ignore: z
147
- .boolean()
148
- .optional()
149
- .describe("true to ignore (default), false to un-ignore the issue"),
150
- }, async ({ domain, issue_id, ignore }) => {
151
- try {
152
- const value = ignore ?? true;
153
- await ws.command("repairs/ignore_issue", { domain, issue_id, ignore: value });
154
- return ok({ domain, issue_id, ignored: value });
155
- }
156
- catch (e) {
157
- return err(e);
158
- }
159
- });
160
- server.tool("list_log_levels", "List the effective log level of every loaded or discovered integration via the WebSocket API (logger/log_info), sorted by domain. level is the numeric Python level and level_name its name (DEBUG 10, INFO 20, WARNING 30, ERROR 40, CRITICAL 50). Use before set_integration_log_level to see what is already verbose.", {
161
- search: z
162
- .string()
163
- .optional()
164
- .describe("Case-insensitive text to find in the integration domain"),
165
- }, async ({ search }) => {
166
- try {
167
- const list = ((await ws.command("logger/log_info")) ?? []);
168
- const needle = search?.toLowerCase();
169
- const integrations = list
170
- .filter((row) => !needle || row.domain.toLowerCase().includes(needle))
171
- .map((row) => ({
172
- domain: row.domain,
173
- level: row.level,
174
- level_name: LEVEL_NAMES[row.level] ?? String(row.level),
175
- }))
176
- .sort((a, b) => a.domain.localeCompare(b.domain));
177
- return ok({ count: integrations.length, integrations });
178
- }
179
- catch (e) {
180
- return err(e);
181
- }
182
- });
183
- server.tool("set_integration_log_level", "Set the log level of an integration (all of its loggers) at runtime via the WebSocket API (logger/integration_log_level) — the equivalent of the Enable debug logging button. Set DEBUG, reproduce the problem, then read the output with get_error_log or list_system_log and set it back (NOTSET removes the override). Changes logging only, not device state. Requires an admin token; errors if the integration does not exist.", {
184
- integration: z.string().describe("Integration domain, e.g. 'zha', 'hue', 'mqtt'"),
185
- level: logLevelSchema,
186
- persistence: persistenceSchema,
187
- }, async ({ integration, level, persistence }) => {
188
- try {
189
- const value = persistence ?? "none";
190
- await ws.command("logger/integration_log_level", {
191
- integration,
192
- level,
193
- persistence: value,
194
- });
195
- return ok({ integration, level, persistence: value });
196
- }
197
- catch (e) {
198
- return err(e);
199
- }
200
- });
201
- server.tool("set_module_log_level", "Set the log level of a single Python logger/module at runtime via the WebSocket API (logger/log_level), e.g. 'homeassistant.components.mqtt.client' or a third-party library name — finer grained than set_integration_log_level. Changes logging only, not device state; use NOTSET to remove the override. Requires an admin token.", {
202
- module: z.string().describe("Logger name, e.g. 'homeassistant.components.zha.core.gateway'"),
203
- level: logLevelSchema,
204
- persistence: persistenceSchema,
205
- }, async ({ module, level, persistence }) => {
206
- try {
207
- const value = persistence ?? "none";
208
- await ws.command("logger/log_level", { module, level, persistence: value });
209
- return ok({ module, level, persistence: value });
210
- }
211
- catch (e) {
212
- return err(e);
213
- }
214
- });
215
- server.tool("get_hardware_info", "Get information about the hardware Home Assistant runs on via the WebSocket API (hardware/info): entries with name, board (hassio_board_id, manufacturer, model, revision), dongle (USB vid, pid, serial_number, manufacturer, description), config_entries and url — e.g. a Raspberry Pi/Green/Yellow board or a Zigbee/Z-Wave stick. Returns { hardware: [...] }, empty on generic installs. Requires the hardware integration (part of default_config).", {}, async () => {
216
- try {
217
- return ok(await ws.command("hardware/info"));
218
- }
219
- catch (e) {
220
- return err(e);
221
- }
222
- });
223
- server.tool("get_network_config", "Get Home Assistant's network adapters and which of them are configured for discovery and local services via the WebSocket API (network): { adapters: [{ name, index, enabled, auto, default, ipv4, ipv6 }], configured_adapters }. Read-only. Requires an admin token.", {}, async () => {
224
- try {
225
- return ok(await ws.command("network"));
226
- }
227
- catch (e) {
228
- return err(e);
229
- }
230
- });
231
- server.tool("get_network_urls", "Get the URLs Home Assistant considers its own via the WebSocket API (network/url): { internal, external, cloud }, each a URL or null when not available. Useful when generating links or checking that the Home Assistant URL settings are correct.", {}, async () => {
232
- try {
233
- return ok(await ws.command("network/url"));
234
- }
235
- catch (e) {
236
- return err(e);
237
- }
238
- });
239
- server.tool("list_labs_features", "List Home Assistant Labs preview features for the loaded integrations via the WebSocket API (labs/list): preview_feature, domain, enabled, is_built_in and the feedback/learn_more/report_issue URLs. Read-only — this server does not toggle them. Requires an admin token.", {
240
- enabled: z
241
- .boolean()
242
- .optional()
243
- .describe("Only features that are enabled (true) or disabled (false)"),
244
- }, async ({ enabled }) => {
245
- try {
246
- const res = (await ws.command("labs/list"));
247
- let features = res?.features ?? [];
248
- if (enabled !== undefined)
249
- features = features.filter((f) => f.enabled === enabled);
250
- return ok({ count: features.length, features });
251
- }
252
- catch (e) {
253
- return err(e);
254
- }
255
- });
256
- server.tool("get_update_release_notes", "Get the full release notes of an update entity via the WebSocket API (update/release_notes) — e.g. to read what changes before updating a core, add-on or HACS item. Only update.* entities that advertise release-notes support and are available; otherwise Home Assistant returns an error. Returns { entity_id, release_notes } (usually Markdown). Requires an admin token.", {
257
- entity_id: z
258
- .string()
259
- .describe("An update.* entity id, e.g. 'update.home_assistant_core_update'"),
260
- }, async ({ entity_id }) => {
261
- try {
262
- if (domainOf(entity_id) !== "update") {
263
- throw new Error(`Release notes are only available for update.* entities, got ${entity_id}`);
264
- }
265
- const notes = await ws.command("update/release_notes", { entity_id });
266
- return ok({ entity_id, release_notes: notes ?? null });
267
- }
268
- catch (e) {
269
- return err(e);
270
- }
271
- });
272
- server.tool("get_analytics_preferences", "Get Home Assistant's analytics settings via the WebSocket API (analytics): { preferences: { base, usage, statistics, diagnostics }, onboarded } — which anonymous data categories are shared with the Home Assistant project. Read-only. Requires an admin token.", {}, async () => {
273
- try {
274
- return ok(await ws.command("analytics"));
275
- }
276
- catch (e) {
277
- return err(e);
278
- }
279
- });
280
- server.tool("get_recorder_info", "Get the status of the recorder (the database behind history and statistics) via the WebSocket API (recorder/info): recording, thread_running, backlog and max_backlog (events queued for the database), migration_in_progress, migration_is_live and db_in_default_location. A growing backlog or recording=false explains missing history.", {}, async () => {
281
- try {
282
- return ok(await ws.command("recorder/info"));
283
- }
284
- catch (e) {
285
- return err(e);
286
- }
287
- });
288
- server.tool("validate_automation_config", "Validate trigger, condition and/or action snippets against Home Assistant's own schemas via the WebSocket API (validate_config) WITHOUT saving or running anything. Pass any of triggers, conditions, actions in the same shape as in automations.yaml (a single item or a list); sections you omit are not checked. Returns { valid, triggers?, conditions?, actions? } where each section is { valid, error } and error is HA's message (unknown option, bad template, invalid device trigger, ...). Run this before upsert_automation.", {
289
- triggers: z
290
- .unknown()
291
- .optional()
292
- .describe("Trigger(s), e.g. [{ trigger: 'state', entity_id: 'light.kitchen', to: 'on' }]"),
293
- conditions: z
294
- .unknown()
295
- .optional()
296
- .describe("Condition(s), e.g. [{ condition: 'state', entity_id: 'light.kitchen', state: 'on' }]"),
297
- actions: z
298
- .unknown()
299
- .optional()
300
- .describe("Action(s), e.g. [{ action: 'light.turn_on', target: { entity_id: 'light.kitchen' } }]"),
301
- }, async ({ triggers, conditions, actions }) => {
302
- try {
303
- const payload = {};
304
- if (triggers !== undefined)
305
- payload.triggers = triggers;
306
- if (conditions !== undefined)
307
- payload.conditions = conditions;
308
- if (actions !== undefined)
309
- payload.actions = actions;
310
- if (Object.keys(payload).length === 0) {
311
- throw new Error("Provide at least one of 'triggers', 'conditions' or 'actions' to validate");
312
- }
313
- const result = ((await ws.command("validate_config", payload)) ?? {});
314
- const valid = Object.values(result).every((section) => section.valid);
315
- return ok({ valid, ...result });
316
- }
317
- catch (e) {
318
- return err(e);
319
- }
320
- });
321
- server.tool("test_condition", "Evaluate ONE condition against live Home Assistant state right now via the WebSocket API (test_condition) and return { result: true|false, template_errors? }. Nothing is executed or changed — use it to check whether a state/numeric_state/template/time/sun/zone/and/or/not condition would pass at this moment, or why a template condition errors. Optional variables are exposed to templates (e.g. a mock 'trigger' object). Invalid conditions return HA's validation error. Requires an admin token.", {
322
- condition: z
323
- .record(z.unknown())
324
- .describe("A single condition, e.g. { condition: 'numeric_state', entity_id: 'sensor.temp', above: 20 }"),
325
- variables: z
326
- .record(z.unknown())
327
- .optional()
328
- .describe("Variables available to templates in the condition"),
329
- }, async ({ condition, variables }) => {
330
- try {
331
- const payload = { condition };
332
- if (variables !== undefined)
333
- payload.variables = variables;
334
- return ok(await ws.command("test_condition", payload));
335
- }
336
- catch (e) {
337
- return err(e);
338
- }
339
- });
340
- server.tool("get_entity_sources", "Find which integration provides each entity via the WebSocket API (entity/source): rows of { entity_id, integration }. Covers entities set up through an integration platform, including ones missing from the entity registry. Filter by entity_ids or integration, otherwise every entity is returned.", {
341
- entity_ids: z.array(z.string()).optional().describe("Only these entity_ids"),
342
- integration: z
343
- .string()
344
- .optional()
345
- .describe("Only entities provided by this integration domain, e.g. 'template', 'mqtt'"),
346
- }, async ({ entity_ids, integration }) => {
347
- try {
348
- const sources = ((await ws.command("entity/source")) ?? {});
349
- const wanted = entity_ids ? new Set(entity_ids) : undefined;
350
- const entities = Object.entries(sources)
351
- .map(([entity_id, source]) => ({ entity_id, integration: source?.domain ?? null }))
352
- .filter((row) => !wanted || wanted.has(row.entity_id))
353
- .filter((row) => !integration || row.integration === integration);
354
- return ok({ count: entities.length, entities });
355
- }
356
- catch (e) {
357
- return err(e);
358
- }
359
- });
360
- server.tool("list_target_components", "List which triggers, conditions or services can be used with the entities in a target, via the WebSocket API (get_triggers_for_target / get_conditions_for_target / get_services_for_target). Resolves the target (entities, devices, areas, floors, labels) like an action's target: block and returns the sorted ids of every component that applies to at least one resulting entity, e.g. 'light.turn_on'. Use it to find valid trigger/condition/action types when authoring automations for an area or device.", {
361
- kind: z.enum(["triggers", "conditions", "services"]).describe("What to list"),
362
- target: targetSchema(),
363
- expand_group: z
364
- .boolean()
365
- .optional()
366
- .describe("Expand group entities into their members (HA default true)"),
367
- }, async ({ kind, target, expand_group }) => {
368
- try {
369
- const payload = targetPayload(target, expand_group);
370
- let result;
371
- if (kind === "triggers") {
372
- result = await ws.command("get_triggers_for_target", payload);
373
- }
374
- else if (kind === "conditions") {
375
- result = await ws.command("get_conditions_for_target", payload);
376
- }
377
- else {
378
- result = await ws.command("get_services_for_target", payload);
379
- }
380
- const items = [...(result ?? [])].sort();
381
- return ok({ kind, count: items.length, items });
382
- }
383
- catch (e) {
384
- return err(e);
385
- }
386
- });
387
- server.tool("resolve_target", "Resolve a target to the concrete entities, devices and areas it refers to via the WebSocket API (extract_from_target) — what an action's target: block would actually hit. Returns referenced_entities, referenced_devices, referenced_areas and missing_devices/missing_areas/missing_floors/missing_labels (ids that do not exist). Use explain_target to see which part of the target contributes which entities.", {
388
- target: targetSchema(),
389
- expand_group: z
390
- .boolean()
391
- .optional()
392
- .describe("Expand group entities into their members (HA default false)"),
393
- primary_entities_only: z
394
- .boolean()
395
- .optional()
396
- .describe("Skip config/diagnostic entities reached through a device or area (HA default true)"),
397
- }, async ({ target, expand_group, primary_entities_only }) => {
398
- try {
399
- return ok(await ws.command("extract_from_target", targetPayload(target, expand_group, primary_entities_only)));
400
- }
401
- catch (e) {
402
- return err(e);
403
- }
404
- });
405
- server.tool("explain_target", "Explain how a target resolves via the WebSocket API (explain_target): for each included item (entity, device, area, floor, label) the entities it contributes, and for each exclude the entities it removed. Returns { includes: [{ type, id, entities, referenced_areas, referenced_devices }], excludes: [{ type, id, removed }] }. An exclude whose removed list is empty has no effect. Useful for debugging why an action hits too many or too few entities.", {
406
- target: targetSchema(),
407
- expand_group: z
408
- .boolean()
409
- .optional()
410
- .describe("Expand group entities into their members (HA default true)"),
411
- primary_entities_only: z
412
- .boolean()
413
- .optional()
414
- .describe("Skip config/diagnostic entities reached through a device or area (HA default true)"),
415
- }, async ({ target, expand_group, primary_entities_only }) => {
416
- try {
417
- return ok(await ws.command("explain_target", targetPayload(target, expand_group, primary_entities_only)));
418
- }
419
- catch (e) {
420
- return err(e);
421
- }
422
- });
423
- server.tool("slugify_text", "Slugify text exactly the way Home Assistant does via the WebSocket API (slugify): lowercase, transliterated, non-alphanumerics to underscores. Returns { slug }. Use it to predict the entity_id of a UI-created automation, script or helper from its name (e.g. 'Kitchen Light On' -> automation.kitchen_light_on) before referencing it.", { text: z.string().describe("Text to slugify, e.g. an automation alias") }, async ({ text }) => {
424
- try {
425
- return ok(await ws.command("slugify", { text }));
426
- }
427
- catch (e) {
428
- return err(e);
429
- }
430
- });
431
- server.tool("list_device_automations", "List the device triggers, conditions or actions an integration offers for a device via the WebSocket API (device_automation/trigger|condition|action/list). Each item is a ready-to-use device trigger/condition/action config (domain, device_id, type, entity_id where applicable, plus metadata). Use get_device_automation_capabilities for the extra options an item accepts. Errors if the device does not exist.", {
432
- kind: z.enum(["trigger", "condition", "action"]).describe("Which kind of device automation"),
433
- device_id: z.string().describe("Device registry id, as returned by list_devices"),
434
- }, async ({ kind, device_id }) => {
435
- try {
436
- let result;
437
- if (kind === "trigger") {
438
- result = await ws.command("device_automation/trigger/list", { device_id });
439
- }
440
- else if (kind === "condition") {
441
- result = await ws.command("device_automation/condition/list", { device_id });
442
- }
443
- else {
444
- result = await ws.command("device_automation/action/list", { device_id });
445
- }
446
- const automations = (result ?? []);
447
- return ok({ device_id, kind, count: automations.length, automations });
448
- }
449
- catch (e) {
450
- return err(e);
451
- }
452
- });
453
- server.tool("get_device_automation_capabilities", "Get the extra options a device trigger, condition or action accepts via the WebSocket API (device_automation/trigger|condition|action/capabilities): returns { extra_fields: [...] } describing additional fields such as 'for' durations or above/below thresholds, or {} if there are none. Pass an item returned by list_device_automations.", {
454
- kind: z.enum(["trigger", "condition", "action"]).describe("Which kind of device automation"),
455
- automation: capabilitiesAutomation,
456
- }, async ({ kind, automation }) => {
457
- try {
458
- if (kind === "trigger") {
459
- return ok(await ws.command("device_automation/trigger/capabilities", { trigger: automation }));
460
- }
461
- if (kind === "condition") {
462
- return ok(await ws.command("device_automation/condition/capabilities", { condition: automation }));
463
- }
464
- return ok(await ws.command("device_automation/action/capabilities", { action: automation }));
465
- }
466
- catch (e) {
467
- return err(e);
468
- }
469
- });
470
- server.tool("get_sensor_convertible_units", "List the units a sensor device class can be converted between via the WebSocket API (sensor/device_class_convertible_units), e.g. energy -> Wh, kWh, MWh, MJ... Returns { device_class, units }; units is empty when the device class has no unit conversion. These are the units a user may pick as a sensor's display unit.", {
471
- device_class: z
472
- .string()
473
- .describe("Sensor device class, e.g. 'energy', 'temperature', 'power'"),
474
- }, async ({ device_class }) => {
475
- try {
476
- const res = (await ws.command("sensor/device_class_convertible_units", {
477
- device_class,
478
- }));
479
- return ok({ device_class, units: res?.units ?? [] });
480
- }
481
- catch (e) {
482
- return err(e);
483
- }
484
- });
485
- server.tool("list_numeric_sensor_device_classes", "List the sensor device classes that report numeric values via the WebSocket API (sensor/numeric_device_classes), sorted. Sensors of these classes can have a state_class and unit_of_measurement; non-numeric ones (enum, date, timestamp, ...) cannot. Returns { count, device_classes }.", {}, async () => {
486
- try {
487
- const res = (await ws.command("sensor/numeric_device_classes"));
488
- const device_classes = [...(res?.numeric_device_classes ?? [])].sort();
489
- return ok({ count: device_classes.length, device_classes });
490
- }
491
- catch (e) {
492
- return err(e);
493
- }
494
- });
495
- server.tool("get_weather_convertible_units", "List the units weather entities can be converted between via the WebSocket API (weather/convertible_units): { units: { pressure_unit, temperature_unit, visibility_unit, precipitation_unit, wind_speed_unit } }, each a sorted list — the valid values for a weather entity's unit options.", {}, async () => {
496
- try {
497
- return ok(await ws.command("weather/convertible_units"));
498
- }
499
- catch (e) {
500
- return err(e);
501
- }
502
- });
503
- server.tool("get_logbook_events", "Get logbook events through the WebSocket API (logbook/get_events). Compared to get_logbook it can also filter by device_ids; context_id finds everything caused by one context (e.g. the automation run or user action behind a state change — take it from a state's context or get_trace_contexts), and cannot be combined with entity_ids/device_ids. Rows have 'when' as an ISO timestamp, the entity_id/domain and state or message, and context_* fields. start_time is required; end_time defaults to now. Unlike get_logbook, entity names are not filled in, and (like get_logbook) state changes of continuous sensors are omitted.", {
504
- start_time: z.string().describe("ISO 8601 start timestamp, e.g. '2026-06-01T00:00:00+02:00'"),
505
- end_time: z.string().optional().describe("ISO 8601 end timestamp (default now)"),
506
- entity_ids: z.array(z.string()).optional().describe("Only events for these entities"),
507
- device_ids: z.array(z.string()).optional().describe("Only events for these device ids"),
508
- context_id: z
509
- .string()
510
- .optional()
511
- .describe("Only events with this context id; not combinable with entity_ids/device_ids"),
512
- }, async ({ start_time, end_time, entity_ids, device_ids, context_id }) => {
513
- try {
514
- if (context_id && (entity_ids?.length || device_ids?.length)) {
515
- throw new Error("context_id cannot be combined with entity_ids or device_ids");
516
- }
517
- const payload = { start_time };
518
- if (end_time !== undefined)
519
- payload.end_time = end_time;
520
- if (entity_ids !== undefined)
521
- payload.entity_ids = entity_ids;
522
- if (device_ids !== undefined)
523
- payload.device_ids = device_ids;
524
- if (context_id !== undefined)
525
- payload.context_id = context_id;
526
- const list = ((await ws.command("logbook/get_events", payload)) ?? []);
527
- const events = list.map((event) => ({
528
- ...event,
529
- when: typeof event.when === "number" ? iso(event.when) : event.when,
530
- }));
531
- return ok({ count: events.length, events });
532
- }
533
- catch (e) {
534
- return err(e);
535
- }
536
- });
537
- }