@orellbuehler/homeassistant-mcp 0.9.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,25 +5,36 @@
5
5
  [![CI](https://github.com/OrellBuehler/homeassistant-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/OrellBuehler/homeassistant-mcp/actions/workflows/ci.yml)
6
6
  [![node](https://img.shields.io/node/v/@orellbuehler/homeassistant-mcp.svg)](https://nodejs.org)
7
7
  [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
8
+ [![HA API drift](https://github.com/OrellBuehler/homeassistant-mcp/actions/workflows/ha-api-drift.yml/badge.svg)](https://github.com/OrellBuehler/homeassistant-mcp/actions/workflows/ha-api-drift.yml)
8
9
 
9
- A [Model Context Protocol](https://modelcontextprotocol.io/) server that turns your
10
- [Home Assistant](https://www.home-assistant.io/) instance into a safe workbench for AI agents —
11
- built to **author and validate configuration and automations**, not to control your home.
10
+ **[Website](https://orellbuehler.github.io/homeassistant-mcp/)** ·
11
+ **[Tool reference](TOOLS.md)** ·
12
+ **[Compared with the built-in MCP server](#compared-with-home-assistants-built-in-mcp-server)**
12
13
 
13
- Point Claude (or any MCP client) at it and the agent can:
14
+ A [Model Context Protocol](https://modelcontextprotocol.io/) server that gives AI agents the
15
+ [Home Assistant](https://www.home-assistant.io/) admin surface — built to **author, validate and
16
+ debug your setup**, not just to flip switches.
14
17
 
15
- - **See what exists, live** — entities, services, events, areas, devices, labels, state history,
16
- logbook.
17
- - **Author configuration** — create/edit automations, configure the Energy dashboard, manage
18
- Zigbee (ZHA) groups, register Lovelace resources, prune HACS repositories, rename entities,
19
- reload YAML domains.
20
- - **Validate its own work** — render Jinja2 templates against live state, run HA's config check,
21
- read the error log, and inspect step-by-step execution traces of automations it wrote.
22
- - **Never touch your devices** — there is deliberately no `call_service`, no `set_state`, and no
23
- `fire_event`. The agent writes config; it cannot turn anything on or off.
18
+ Point Claude (or any MCP client) at it and the agent can:
24
19
 
25
- 43 tools, zero install (`npx`), works with Claude Code, Claude Desktop, Cursor, and any other MCP
26
- client.
20
+ - **See what exists, live** — entities, services, devices, areas, floors, labels, integrations,
21
+ state history, logbook, long-term statistics.
22
+ - **Author configuration** — automations, scripts, scenes, helpers, dashboards, blueprints, the
23
+ Energy dashboard, Zigbee (ZHA) groups; set up and reconfigure integrations through their config
24
+ flows.
25
+ - **Organise the home** — rename devices and entities, assign areas, floors, labels and
26
+ categories, enable/disable entities, remove orphaned registry entries.
27
+ - **Validate and debug its own work** — render Jinja2 templates against live state, validate
28
+ trigger/condition/action snippets, run HA's config check, read logs and repairs, and step through
29
+ automation traces.
30
+ - **Stay inside the surface you choose** — every tool group is a toolset behind a
31
+ [feature flag](#toolsets-and-feature-flags). Device control (`call_service`, `set_state`,
32
+ `fire_event`) and the raw API passthrough are **off by default**; a read-only mode removes every
33
+ write tool.
34
+
35
+ 216 tools in 25 toolsets (172 enabled by default), zero install (`npx`), works with Claude
36
+ Code, Claude Desktop, Cursor, and any other MCP client. The tools are
37
+ [checked against every Home Assistant release](#api-drift-detection).
27
38
 
28
39
  ## Example prompts
29
40
 
@@ -42,6 +53,36 @@ client.
42
53
 
43
54
  > "I uninstalled a HACS card — find and remove the dangling Lovelace resource."
44
55
 
56
+ > "The new lamp shows up as 'Licht WC'. Rename the device, fix its entity ids and put it in the
57
+ > basement area."
58
+
59
+ > "The Shelly integration failed to load after the update — find out why and reload it."
60
+
61
+ ## Compared with Home Assistant's built-in MCP server
62
+
63
+ Home Assistant ships its own [MCP server integration](https://www.home-assistant.io/integrations/mcp_server/).
64
+ It is built for **using** the home (read state, call actions); this project is built for
65
+ **changing how the home is set up**. They work well side by side.
66
+
67
+ | Capability | Built-in `mcp_server` | `homeassistant-mcp` |
68
+ | --------------------------------------------------- | --------------------------------------------------- | ----------------------------------------------------------- |
69
+ | Read states, history, logs, render templates | yes | yes |
70
+ | Call actions and control devices | yes (its main purpose) | opt-in (`control` toolset, off by default) |
71
+ | List and reload integrations | yes | yes, plus config flows, enable/disable, delete, diagnostics |
72
+ | Write automations, scripts and scenes | no | yes |
73
+ | Debug with automation traces | no | yes |
74
+ | Rename, enable, remove entities and devices | no | yes |
75
+ | Areas, floors, labels, categories | no | yes |
76
+ | Helpers, dashboards, Lovelace resources, blueprints | no | yes |
77
+ | Check config, Energy dashboard, ZHA groups, HACS | no | yes |
78
+ | Limit access to entities exposed to Assist | yes (Device control set) | no (sees what the token's user sees) |
79
+ | Choose which tools the agent gets | per tool set, plus read-only mode | per toolset and per tool, plus read-only mode |
80
+ | Connection | HTTP at `/api/mcp`, OAuth (Claude Code needs HTTPS) | local stdio via `npx`, long-lived token |
81
+
82
+ Compared against the built-in tool sets as of Home Assistant 2026.11.3. Use the built-in server for an
83
+ assistant that operates the home, scoped to the entities you expose to voice assistants. Use this
84
+ one for an agent that maintains it — most of that work has no action to call, only an admin API.
85
+
45
86
  ## Install
46
87
 
47
88
  The package is published as
@@ -72,11 +113,14 @@ user with the access you want and generate the token as that user.
72
113
 
73
114
  ## Configuration
74
115
 
75
- | Variable | Required | Description |
76
- | ------------- | -------- | --------------------------------------------------------------------------------- |
77
- | `HASS_URL` | yes\* | Base URL of your instance, e.g. `http://homeassistant.local:8123`. `https` works. |
78
- | `HASS_SERVER` | no | Alias for `HASS_URL` (compatible with `hass-cli`). Used if `HASS_URL` is unset. |
79
- | `HASS_TOKEN` | yes | Long-lived access token. |
116
+ | Variable | Required | Description |
117
+ | --------------------- | -------- | ------------------------------------------------------------------------------------------ |
118
+ | `HASS_URL` | yes\* | Base URL of your instance, e.g. `http://homeassistant.local:8123`. `https` works. |
119
+ | `HASS_SERVER` | no | Alias for `HASS_URL` (compatible with `hass-cli`). Used if `HASS_URL` is unset. |
120
+ | `HASS_TOKEN` | yes | Long-lived access token. |
121
+ | `HASS_TOOLSETS` | no | Which toolsets to register. See [Toolsets and feature flags](#toolsets-and-feature-flags). |
122
+ | `HASS_READ_ONLY` | no | `true` removes every tool that changes anything in Home Assistant. |
123
+ | `HASS_DISABLED_TOOLS` | no | Comma-separated tool names to hide. |
80
124
 
81
125
  \* Either `HASS_URL` or `HASS_SERVER` must be set. The WebSocket URL is derived automatically
82
126
  (`http`→`ws`, `https`→`wss`, plus `/api/websocket`).
@@ -105,11 +149,61 @@ If you built from source instead, use `"command": "node"` with
105
149
  available immediately. Verify with `claude mcp list` (should show `homeassistant ✓ connected`) or
106
150
  `/mcp` inside a session.
107
151
 
152
+ ## Toolsets and feature flags
153
+
154
+ Tools are grouped into toolsets. Config authoring and inspection are on by default; device control,
155
+ the raw API passthrough, backups, user management and household lists are opt-in.
156
+
157
+ | Toolset | Default | Tools | What it covers |
158
+ | --------------------------------------- | ------- | ----- | ------------------------------------------------------------------------------- |
159
+ | [`entities`](TOOLS.md#entities) | on | 3 | Entity states and domains |
160
+ | [`services`](TOOLS.md#services) | on | 2 | Service and event catalog |
161
+ | [`system`](TOOLS.md#system) | on | 5 | Core config, config check, error log |
162
+ | [`templates`](TOOLS.md#templates) | on | 1 | Jinja2 template rendering |
163
+ | [`history`](TOOLS.md#history) | on | 2 | State history and logbook |
164
+ | [`reload`](TOOLS.md#reload) | on | 1 | Reload YAML config domains |
165
+ | [`automations`](TOOLS.md#automations) | on | 3 | Automation config authoring |
166
+ | [`registry`](TOOLS.md#registry) | on | 8 | Entity, device, area and label registries |
167
+ | [`energy`](TOOLS.md#energy) | on | 7 | Energy dashboard preferences |
168
+ | [`trace`](TOOLS.md#trace) | on | 3 | Automation and script traces |
169
+ | [`zha`](TOOLS.md#zha) | on | 6 | ZHA Zigbee groups |
170
+ | [`hacs`](TOOLS.md#hacs) | on | 2 | HACS repositories |
171
+ | [`resources`](TOOLS.md#resources) | on | 4 | Lovelace resources |
172
+ | [`integrations`](TOOLS.md#integrations) | on | 28 | Config entries, config/options flows, manifests, credentials, diagnostics |
173
+ | [`organization`](TOOLS.md#organization) | on | 31 | Areas, floors, labels, categories, full registry entries, voice exposure |
174
+ | [`dashboards`](TOOLS.md#dashboards) | on | 12 | Lovelace dashboards and configs, frontend panels, themes, notifications |
175
+ | [`diagnostics`](TOOLS.md#diagnostics) | on | 27 | System log, repairs, log levels, config validation, targets, device automations |
176
+ | [`statistics`](TOOLS.md#statistics) | on | 12 | Recorder long-term statistics: query, validate, repair |
177
+ | [`backup`](TOOLS.md#backup) | opt-in | 12 | Backups: list, create, configure, delete, restore |
178
+ | [`auth`](TOOLS.md#auth) | opt-in | 10 | Users and refresh tokens |
179
+ | [`lists`](TOOLS.md#lists) | opt-in | 13 | Household data: calendars, to-do lists, shopping list |
180
+ | [`helpers`](TOOLS.md#helpers) | on | 4 | UI-managed helpers: input\_\*, counter, timer, schedule, zone, person, tag |
181
+ | [`scripts`](TOOLS.md#scripts) | on | 11 | Script and scene config authoring, blueprints |
182
+ | [`control`](TOOLS.md#control) | opt-in | 7 | Device control: call services, set states, fire events |
183
+ | [`raw`](TOOLS.md#raw) | opt-in | 2 | Unrestricted REST and WebSocket passthrough |
184
+
185
+ `HASS_TOOLSETS` is a comma-separated list. `default` stands for the default toolsets, `all` for
186
+ every toolset, a name adds that toolset and `-name` removes it. Unset means `default`.
187
+
188
+ ```bash
189
+ HASS_TOOLSETS=default,control # the defaults plus device control
190
+ HASS_TOOLSETS=all,-raw # everything except the raw passthrough
191
+ HASS_TOOLSETS=-zha,-hacs # the defaults without ZHA and HACS
192
+ HASS_TOOLSETS=entities,templates,automations,trace # only these four
193
+ HASS_READ_ONLY=true # drop every write tool from the selected toolsets
194
+ HASS_DISABLED_TOOLS=delete_automation,remove_entity # hide individual tools
195
+ ```
196
+
197
+ A smaller surface also means fewer tool definitions in the agent's context — worth trimming if you
198
+ only need a few groups.
199
+
108
200
  ## Tools
109
201
 
110
- 43 tools in 12 groups. REST tools go through the
202
+ The complete list of all 216 tools, generated from the code, is in **[TOOLS.md](TOOLS.md)** and
203
+ searchable on the [website](https://orellbuehler.github.io/homeassistant-mcp/#tools). The sections
204
+ below describe the original core groups in more detail. REST tools go through the
111
205
  [Home Assistant REST API](https://www.home-assistant.io/integrations/api/); WebSocket tools use the
112
- config registries that are not exposed over REST.
206
+ admin commands that are not exposed over REST.
113
207
 
114
208
  **Entities & state** (REST)
115
209
 
@@ -274,28 +368,25 @@ integration you still reference in YAML will break that config, so check usage f
274
368
 
275
369
  ## Safety boundary
276
370
 
277
- - **No device control.** There is no generic `call_service`, no `set_state`, and no `fire_event`.
278
- The server cannot turn things on/off.
371
+ - **No device control by default.** `call_service`, `set_state`, `fire_event`, `execute_script` and
372
+ the conversation/intent tools live in the `control` toolset, which is off unless you add it to
373
+ `HASS_TOOLSETS`. Without it the server cannot turn anything on or off directly.
374
+ - **No unrestricted API access by default.** `ws_command` and `rest_request` (the `raw` toolset)
375
+ can send any command the token allows and are opt-in.
376
+ - **Written config does run.** An automation, script or scene the agent writes executes its actions
377
+ when triggered — that is the point of authoring them. Review what gets written.
378
+ - **Some default tools are destructive.** Deleting config entries, devices, areas, dashboards or
379
+ registry entries cannot be undone, and removing a device can unpair it from its integration (for
380
+ example Matter). Use `HASS_READ_ONLY=true` or `HASS_DISABLED_TOOLS` to take them away.
279
381
  - **`reload` is restricted** to a fixed allowlist of `*.reload` / `homeassistant.reload_*` services.
280
- It restarts reloadable domains (e.g. re-reads `automations.yaml`) but cannot control devices.
281
- - **Automation configs are writable** via the `/api/config/automation` REST API
282
- (`upsert_automation` / `delete_automation`). This is the server's core purpose — authoring
283
- automations — and needs an admin token. Be aware that an automation, once written, runs its
284
- actions whenever its triggers fire, so review configs before writing. The server still cannot run
285
- services directly: no `call_service`, `set_state`, or `fire_event`.
286
- - **Energy dashboard config is writable** via `energy/save_prefs` (the `*_energy_*` tools). This is
287
- configuration authoring — the dashboard's sources and Individual-devices list — not device control,
288
- and it needs an admin token. No `call_service`, `set_state`, or `fire_event` is added.
289
- - **ZHA groups are writable** via `zha/group/*` (the `*_zha_group*` tools). Creating/editing a Zigbee
290
- group changes which group entities exist (config authoring), not any device's on/off state, and it
291
- needs an admin token. Still no `call_service`, `set_state`, or `fire_event`.
292
- - **Lovelace resources are writable** via `lovelace/resources/*` (the `*_lovelace_resource` tools) —
293
- which JS/CSS bundles load into dashboards. Config authoring, admin token, storage-mode only.
294
- - **HACS repositories are removable** via `hacs/repository/remove` (`remove_hacs_repository`). This
295
- uninstalls a plugin/integration/theme and deletes its files (admin token); there is no install tool
296
- (the server never downloads third-party code). Still no `call_service`, `set_state`, or `fire_event`.
382
+ - **Blueprint import fetches a URL from Home Assistant**, and config flows can install an
383
+ integration's requirements. The server itself never downloads code, and there is no HACS install
384
+ tool.
385
+ - **Secrets are not returned.** OAuth client secrets and refresh-token values are stripped from tool
386
+ output.
387
+ - **Writes need an admin token.** Home Assistant rejects them otherwise.
297
388
  - **Read tools expose your home's data** (entity names, states, areas) to the agent/LLM. Use a
298
- scoped HA user if that matters to you.
389
+ dedicated HA user if that matters to you.
299
390
  - Prefer `https` and a trusted network path to your instance.
300
391
 
301
392
  ## Development
@@ -307,6 +398,10 @@ npm test # vitest run
307
398
  npm run typecheck # tsc --noEmit
308
399
  npm run lint # eslint src
309
400
  npm run format:check # prettier --check .
401
+ npm run api:check # every command/route the tools call exists in ha-api/snapshot.json
402
+ npm run api:uncovered # Home Assistant commands/routes no tool uses yet
403
+ npm run docs # regenerate TOOLS.md from the registered tools
404
+ npm run site # write site/tools.json for the website (after a build)
310
405
  ```
311
406
 
312
407
  Run a single test file:
@@ -318,7 +413,11 @@ npx vitest run src/__tests__/entities.test.ts
318
413
  ## CI / Releasing
319
414
 
320
415
  - **CI** (`.github/workflows/ci.yml`) runs on every push to `main` and on pull requests:
321
- `format:check`, `lint`, `typecheck` (once) and `test` + `build` on Node 20 and 22.
416
+ `format:check`, `lint`, `typecheck`, `api:check` (once) and `test` + `build` on Node 20 and 22,
417
+ plus a check that `TOOLS.md` is up to date.
418
+ - **HA API drift** (`.github/workflows/ha-api-drift.yml`) — see [below](#api-drift-detection).
419
+ - **Pages** (`.github/workflows/pages.yml`) builds the tool data and deploys `site/` to GitHub
420
+ Pages on pushes to `main`.
322
421
  - **Publish** (`.github/workflows/publish.yml`) runs when a GitHub Release is published. It builds,
323
422
  tests, and publishes to npm using [trusted publishing](https://docs.npmjs.com/trusted-publishers)
324
423
  (OIDC) — **no `NPM_TOKEN` secret required**, with provenance generated automatically. It skips
@@ -337,6 +436,25 @@ git push --follow-tags
337
436
  gh release create "v$(node -p "require('./package.json').version")" --generate-notes
338
437
  ```
339
438
 
439
+ ## API drift detection
440
+
441
+ Home Assistant's WebSocket API has no published schema, so `scripts/ha-api.mjs` reads it from the
442
+ Home Assistant core source: every WebSocket command with its parameters and every REST route. The
443
+ result is committed as `ha-api/snapshot.json`, pinned to a Home Assistant version.
444
+
445
+ - `npm run api:check` (part of CI) fails if a tool calls a command or route that is not in the
446
+ snapshot. Commands from custom integrations that are not in core (HACS) are listed in
447
+ `ha-api/allow.json`.
448
+ - The weekly **HA API drift** workflow compares the snapshot with the latest Home Assistant release.
449
+ When something changed it opens a pull request that updates the snapshot and lists added, removed
450
+ and changed commands, and it fails if a command this server uses was removed or changed. It needs
451
+ _Settings → Actions → General → Allow GitHub Actions to create and approve pull requests_; without
452
+ it the report is filed as an issue instead.
453
+ - Run it for a specific version from the Actions tab (`workflow_dispatch`, input `version`).
454
+
455
+ The extraction is static, so commands whose names are built at runtime can be missed, and a changed
456
+ parameter type shows up only as "schema body changed".
457
+
340
458
  ## License
341
459
 
342
460
  [MIT](./LICENSE) © Orell Bühler
package/dist/index.js CHANGED
@@ -2,7 +2,11 @@
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { client, wsClient } from "./config.js";
4
4
  import { createServer } from "./server.js";
5
- const server = createServer(client, wsClient);
5
+ import { parseToolOptions } from "./toolsets.js";
6
+ const options = parseToolOptions(process.env);
7
+ for (const warning of options.warnings)
8
+ console.error(warning);
9
+ const server = createServer(client, wsClient, options);
6
10
  const transport = new StdioServerTransport();
7
11
  try {
8
12
  await server.connect(transport);
package/dist/server.js CHANGED
@@ -1,31 +1,9 @@
1
+ import { createRequire } from "node:module";
1
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { registerEntityTools } from "./tools/entities.js";
3
- import { registerServiceTools } from "./tools/services.js";
4
- import { registerSystemTools } from "./tools/system.js";
5
- import { registerTemplateTools } from "./tools/templates.js";
6
- import { registerHistoryTools } from "./tools/history.js";
7
- import { registerReloadTools } from "./tools/reload.js";
8
- import { registerAutomationTools } from "./tools/automations.js";
9
- import { registerRegistryTools } from "./tools/registry.js";
10
- import { registerEnergyTools } from "./tools/energy.js";
11
- import { registerTraceTools } from "./tools/trace.js";
12
- import { registerZhaTools } from "./tools/zha.js";
13
- import { registerHacsTools } from "./tools/hacs.js";
14
- import { registerResourceTools } from "./tools/resources.js";
15
- export function createServer(client, wsClient) {
16
- const server = new McpServer({ name: "homeassistant-mcp", version: "0.7.0" });
17
- registerEntityTools(server, client);
18
- registerServiceTools(server, client);
19
- registerSystemTools(server, client);
20
- registerTemplateTools(server, client);
21
- registerHistoryTools(server, client);
22
- registerReloadTools(server, client);
23
- registerAutomationTools(server, client);
24
- registerRegistryTools(server, wsClient);
25
- registerEnergyTools(server, wsClient, client);
26
- registerTraceTools(server, wsClient, client);
27
- registerZhaTools(server, wsClient);
28
- registerHacsTools(server, wsClient);
29
- registerResourceTools(server, wsClient);
3
+ import { parseToolOptions, registerToolsets } from "./toolsets.js";
4
+ const { version } = createRequire(import.meta.url)("../package.json");
5
+ export function createServer(client, wsClient, options = parseToolOptions({})) {
6
+ const server = new McpServer({ name: "homeassistant-mcp", version });
7
+ registerToolsets(server, client, wsClient, options);
30
8
  return server;
31
9
  }
@@ -0,0 +1,191 @@
1
+ import { z } from "zod";
2
+ import { ok, err } from "../hass/format.js";
3
+ const SECRET_KEYS = new Set([
4
+ "token",
5
+ "access_token",
6
+ "refresh_token",
7
+ "jwt_key",
8
+ "password",
9
+ "client_secret",
10
+ ]);
11
+ const groupIds = z
12
+ .array(z.enum(["system-admin", "system-users", "system-read-only"]))
13
+ .describe("Permission groups: 'system-admin' (administrator), 'system-users' (regular user), 'system-read-only' (read-only)");
14
+ function stripSecrets(value) {
15
+ if (Array.isArray(value))
16
+ return value.map(stripSecrets);
17
+ if (value !== null && typeof value === "object") {
18
+ return Object.fromEntries(Object.entries(value)
19
+ .filter(([key]) => !SECRET_KEYS.has(key))
20
+ .map(([key, inner]) => [key, stripSecrets(inner)]));
21
+ }
22
+ return value;
23
+ }
24
+ export function registerAuthTools(server, ws) {
25
+ server.tool("get_current_user", "Get the Home Assistant user this server authenticates as via the WebSocket API (auth/current_user): id, name, is_owner, is_admin, the login credentials it has (auth_provider_type/id) and its multi-factor modules. Use it to confirm the token's identity and whether it is an administrator before attempting config writes.", {}, async () => {
26
+ try {
27
+ return ok(stripSecrets(await ws.command("auth/current_user")));
28
+ }
29
+ catch (e) {
30
+ return err(e);
31
+ }
32
+ });
33
+ server.tool("list_users", "List all Home Assistant users via the WebSocket API (config/auth/list): id, username (null if the user has no username/password login), name, is_owner, is_active, local_only (may only log in from the local network), system_generated (Supervisor, add-on and other internal users), group_ids and credentials types. Passwords and tokens are never part of it. Requires an admin token.", {}, async () => {
34
+ try {
35
+ const list = (stripSecrets(await ws.command("config/auth/list")) ?? []);
36
+ return ok({ count: list.length, users: list });
37
+ }
38
+ catch (e) {
39
+ return err(e);
40
+ }
41
+ });
42
+ server.tool("create_user", "Create a Home Assistant user via the WebSocket API (config/auth/create) with a name, optional permission groups and an optional local-only restriction. The new user has NO login credentials yet, so it cannot sign in until a username/password (or another login method) is added in the Home Assistant UI — this server cannot set passwords. Granting 'system-admin' makes the user an administrator. Returns { user }. Requires an admin token.", {
43
+ name: z.string().describe("Display name of the new user"),
44
+ group_ids: groupIds
45
+ .optional()
46
+ .describe("Permission groups; normally set one (default: none)"),
47
+ local_only: z
48
+ .boolean()
49
+ .optional()
50
+ .describe("Only allow this user to log in from the local network"),
51
+ }, async ({ name, group_ids, local_only }) => {
52
+ try {
53
+ const payload = { name };
54
+ if (group_ids !== undefined)
55
+ payload.group_ids = group_ids;
56
+ if (local_only !== undefined)
57
+ payload.local_only = local_only;
58
+ return ok(stripSecrets(await ws.command("config/auth/create", payload)));
59
+ }
60
+ catch (e) {
61
+ return err(e);
62
+ }
63
+ });
64
+ server.tool("update_user", "Update a Home Assistant user via the WebSocket API (config/auth/update): rename, activate/deactivate (is_active), change permission groups or the local-only restriction. Only the given fields change. Refuses system-generated users, deactivating the owner, and — to avoid locking this server out — changing is_active, group_ids or local_only of the account this server authenticates as (see get_current_user); renaming that account is fine. Returns { user }. Requires an admin token.", {
65
+ user_id: z.string().describe("User id from list_users"),
66
+ name: z.string().optional().describe("New display name"),
67
+ is_active: z
68
+ .boolean()
69
+ .optional()
70
+ .describe("false deactivates (blocks login), true reactivates"),
71
+ group_ids: groupIds.optional().describe("Replaces the user's permission groups"),
72
+ local_only: z.boolean().optional().describe("Only allow login from the local network"),
73
+ }, async ({ user_id, name, is_active, group_ids, local_only }) => {
74
+ try {
75
+ if (name === undefined &&
76
+ is_active === undefined &&
77
+ group_ids === undefined &&
78
+ local_only === undefined) {
79
+ throw new Error("Provide at least one of 'name', 'is_active', 'group_ids' or 'local_only' to update");
80
+ }
81
+ if (is_active !== undefined || group_ids !== undefined || local_only !== undefined) {
82
+ const me = (await ws.command("auth/current_user"));
83
+ if (me?.id === user_id) {
84
+ throw new Error("Refusing to change is_active, group_ids or local_only of the account this server authenticates as — that could lock it out. Change it in the Home Assistant UI instead.");
85
+ }
86
+ }
87
+ const payload = { user_id };
88
+ if (name !== undefined)
89
+ payload.name = name;
90
+ if (is_active !== undefined)
91
+ payload.is_active = is_active;
92
+ if (group_ids !== undefined)
93
+ payload.group_ids = group_ids;
94
+ if (local_only !== undefined)
95
+ payload.local_only = local_only;
96
+ return ok(stripSecrets(await ws.command("config/auth/update", payload)));
97
+ }
98
+ catch (e) {
99
+ return err(e);
100
+ }
101
+ });
102
+ server.tool("delete_user", "DELETE a Home Assistant user via the WebSocket API (config/auth/delete) together with its credentials and all of its refresh/long-lived tokens, so everything signed in as that user is logged out. Cannot be undone. Home Assistant refuses to delete your own account, the owner and system-generated users. A linked person entry is kept but unlinked from the user. Requires an admin token.", { user_id: z.string().describe("User id from list_users") }, async ({ user_id }) => {
103
+ try {
104
+ await ws.command("config/auth/delete", { user_id });
105
+ return ok({ deleted: user_id });
106
+ }
107
+ catch (e) {
108
+ return err(e);
109
+ }
110
+ });
111
+ server.tool("list_refresh_tokens", "List the refresh and long-lived access tokens of the user this server authenticates as via the WebSocket API (auth/refresh_tokens) — metadata only: id, type (normal/long_lived_access_token/system), client_name, client_id, client_icon, created_at, last_used_at, last_used_ip, expire_at, auth_provider_type and is_current (true for the token this server itself uses). The token secrets are never returned. Only the calling user's own tokens are listed, not other users'.", {}, async () => {
112
+ try {
113
+ const list = (stripSecrets(await ws.command("auth/refresh_tokens")) ?? []);
114
+ return ok({ count: list.length, tokens: list });
115
+ }
116
+ catch (e) {
117
+ return err(e);
118
+ }
119
+ });
120
+ server.tool("delete_refresh_token", "Revoke one refresh or long-lived access token of the user this server authenticates as via the WebSocket API (auth/delete_refresh_token): whatever uses it (a browser session, the companion app, an integration) is logged out and must sign in again; it cannot be undone. Refuses the token this server itself uses (is_current in list_refresh_tokens) because that would lock it out. Get the id from list_refresh_tokens.", {
121
+ refresh_token_id: z.string().describe("The token's 'id' from list_refresh_tokens"),
122
+ }, async ({ refresh_token_id }) => {
123
+ try {
124
+ const tokens = ((await ws.command("auth/refresh_tokens")) ?? []);
125
+ if (tokens.find((t) => t.id === refresh_token_id)?.is_current) {
126
+ throw new Error("Refusing to revoke the token this server authenticates with — that would lock it out. Revoke it from the Home Assistant profile page instead.");
127
+ }
128
+ await ws.command("auth/delete_refresh_token", { refresh_token_id });
129
+ return ok({ deleted: refresh_token_id });
130
+ }
131
+ catch (e) {
132
+ return err(e);
133
+ }
134
+ });
135
+ server.tool("delete_all_refresh_tokens", "Revoke ALL refresh and long-lived access tokens of the user this server authenticates as, EXCEPT the one this server itself uses, via the WebSocket API (auth/delete_all_refresh_tokens with delete_current_token=false). Every other session, the companion apps and integrations using that user's tokens are logged out and must sign in again. Optionally limit it to one token_type. Cannot be undone. Returns { deleted_count, token_type }.", {
136
+ token_type: z
137
+ .enum(["normal", "long_lived_access_token"])
138
+ .optional()
139
+ .describe("Only this type: 'normal' (login sessions and app tokens) or 'long_lived_access_token'"),
140
+ }, async ({ token_type }) => {
141
+ try {
142
+ const tokens = ((await ws.command("auth/refresh_tokens")) ?? []);
143
+ const deleted_count = tokens.filter((t) => !t.is_current && (token_type === undefined || t.type === token_type)).length;
144
+ const payload = { delete_current_token: false };
145
+ if (token_type !== undefined)
146
+ payload.token_type = token_type;
147
+ await ws.command("auth/delete_all_refresh_tokens", payload);
148
+ return ok({ deleted_count, token_type: token_type ?? "all" });
149
+ }
150
+ catch (e) {
151
+ return err(e);
152
+ }
153
+ });
154
+ server.tool("set_refresh_token_expiry", "Enable or disable automatic expiry of a refresh/long-lived token of the user this server authenticates as via the WebSocket API (auth/refresh_token_set_expiry). Enabling makes the token expire 90 days after it was last used (an existing expiry is kept); disabling removes the expiry so it never expires. Get the id from list_refresh_tokens (expire_at shows the current state).", {
155
+ refresh_token_id: z.string().describe("The token's 'id' from list_refresh_tokens"),
156
+ enable_expiry: z
157
+ .boolean()
158
+ .describe("true to let it expire after 90 days unused, false to never expire"),
159
+ }, async ({ refresh_token_id, enable_expiry }) => {
160
+ try {
161
+ await ws.command("auth/refresh_token_set_expiry", { refresh_token_id, enable_expiry });
162
+ return ok({ refresh_token_id, expiry_enabled: enable_expiry });
163
+ }
164
+ catch (e) {
165
+ return err(e);
166
+ }
167
+ });
168
+ server.tool("update_own_profile", "Update the display name and/or picture of the user this server authenticates as, and of the person entry linked to it, via the WebSocket API (person/update_own_profile). name is trimmed and must not be empty; picture must be an image already uploaded to Home Assistant ('/api/image/serve/<32-hex id>/512x512' style path) or null to remove it, and needs a storage-managed person linked to the user. Returns { user_name, person }. Not allowed for system-generated users.", {
169
+ name: z.string().optional().describe("New display name"),
170
+ picture: z
171
+ .string()
172
+ .nullable()
173
+ .optional()
174
+ .describe("Uploaded image path such as '/api/image/serve/<id>/512x512', or null to remove"),
175
+ }, async ({ name, picture }) => {
176
+ try {
177
+ if (name === undefined && picture === undefined) {
178
+ throw new Error("Provide at least one of 'name' or 'picture' to update");
179
+ }
180
+ const payload = {};
181
+ if (name !== undefined)
182
+ payload.name = name;
183
+ if (picture !== undefined)
184
+ payload.picture = picture;
185
+ return ok(await ws.command("person/update_own_profile", payload));
186
+ }
187
+ catch (e) {
188
+ return err(e);
189
+ }
190
+ });
191
+ }