@orellbuehler/homeassistant-mcp 0.9.0 → 1.0.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.
@@ -0,0 +1,206 @@
1
+ import { z } from "zod";
2
+ import { ok, err } from "../hass/format.js";
3
+ const SCRIPT_PREFIX = "script.";
4
+ async function resolveScriptKey(script, ws) {
5
+ if (!script.startsWith(SCRIPT_PREFIX))
6
+ return script;
7
+ try {
8
+ const entry = (await ws.command("config/entity_registry/get", {
9
+ entity_id: script,
10
+ }));
11
+ if (entry?.unique_id)
12
+ return String(entry.unique_id);
13
+ }
14
+ catch (e) {
15
+ if (e.code !== "not_found")
16
+ throw e;
17
+ }
18
+ return script.slice(SCRIPT_PREFIX.length);
19
+ }
20
+ async function resolveSceneId(scene, client) {
21
+ if (!scene.startsWith("scene."))
22
+ return scene;
23
+ const state = (await client.fetch(`/api/states/${encodeURIComponent(scene)}`));
24
+ const id = state.attributes?.id;
25
+ if (id === undefined || id === null || id === "") {
26
+ throw new Error(`Scene ${scene} has no 'id' attribute, so it is not stored in scenes.yaml and cannot be read or edited via the config API (it is defined elsewhere in YAML without an id, comes from an integration, or was made with scene.create)`);
27
+ }
28
+ return String(id);
29
+ }
30
+ const scriptPath = (key) => `/api/config/script/config/${encodeURIComponent(key)}`;
31
+ const scenePath = (id) => `/api/config/scene/config/${encodeURIComponent(id)}`;
32
+ const blueprintDomain = z
33
+ .enum(["automation", "script", "template"])
34
+ .describe("Blueprint domain: 'automation', 'script' or 'template'");
35
+ const blueprintFile = z
36
+ .string()
37
+ .describe("Blueprint path relative to config/blueprints/<domain>/, including .yaml, e.g. 'homeassistant/motion_light.yaml'");
38
+ export function registerScriptTools(server, client, ws) {
39
+ server.tool("get_script_config", "Get the stored configuration of a script (alias, description, icon, mode, fields, variables, sequence) from scripts.yaml via GET /api/config/script/config/{key} (requires an admin token). Accepts the script.* entity id (its key is resolved through the entity registry) or the script's key itself (the object id, e.g. 'goodnight' for script.goodnight). Only scripts stored in scripts.yaml (UI-created) are accessible; others return 404.", {
40
+ script: z
41
+ .string()
42
+ .describe("script.* entity id, or the script's key (the object id after 'script.')"),
43
+ }, async ({ script }) => {
44
+ try {
45
+ const key = await resolveScriptKey(script, ws);
46
+ return ok(await client.fetch(scriptPath(key)));
47
+ }
48
+ catch (e) {
49
+ return err(e);
50
+ }
51
+ });
52
+ server.tool("upsert_script", "Create a new script or replace an existing one via POST /api/config/script/config/{key} (requires an admin token). Home Assistant validates the config including the sequence's actions, writes it to scripts.yaml and reloads scripts automatically — no separate reload needed. The config REPLACES the stored one entirely, so to edit call get_script_config first and send back the modified object. The key is the script's object id: pass a new key (lowercase letters, digits and underscores, e.g. 'goodnight'; not reload, turn_on, turn_off or toggle) to create script.<key> — it cannot be renamed later — or an existing script.* entity id or key to replace that script. Writing a script does not run it; its sequence runs when an automation, scene or service call invokes it.", {
53
+ script: z
54
+ .string()
55
+ .describe("New script key (e.g. 'goodnight') to create script.<key>, or the script.* entity id / key of an existing script to replace"),
56
+ config: z
57
+ .record(z.unknown())
58
+ .describe("Full script config as stored in scripts.yaml: alias, sequence (list of actions), description?, icon?, mode? (single|restart|queued|parallel), max?, max_exceeded?, fields?, variables? — or a blueprint instance {use_blueprint: {path, input}, alias?, description?}"),
59
+ }, async ({ script, config }) => {
60
+ try {
61
+ const key = await resolveScriptKey(script, ws);
62
+ const result = await client.fetch(scriptPath(key), {
63
+ method: "POST",
64
+ body: JSON.stringify(config),
65
+ });
66
+ return ok({ key, result });
67
+ }
68
+ catch (e) {
69
+ return err(e);
70
+ }
71
+ });
72
+ server.tool("delete_script", "Delete a script from scripts.yaml via DELETE /api/config/script/config/{key} (requires an admin token). Accepts the script.* entity id or the key. Only scripts stored in scripts.yaml can be deleted; Home Assistant then removes the script's entity registry entry. Automations and scenes that call the script are not updated.", {
73
+ script: z
74
+ .string()
75
+ .describe("script.* entity id, or the script's key (the object id after 'script.')"),
76
+ }, async ({ script }) => {
77
+ try {
78
+ const key = await resolveScriptKey(script, ws);
79
+ return ok(await client.fetch(scriptPath(key), { method: "DELETE" }));
80
+ }
81
+ catch (e) {
82
+ return err(e);
83
+ }
84
+ });
85
+ server.tool("get_scene_config", "Get the stored configuration of a scene (id, name, icon, entities, metadata) from scenes.yaml via GET /api/config/scene/config/{id} (requires an admin token). Accepts the scene.* entity id (the internal id is resolved automatically) or the internal id itself. Only scenes with an 'id' (UI-created, stored in scenes.yaml) are accessible.", {
86
+ scene: z
87
+ .string()
88
+ .describe("scene.* entity id, or the scene's internal id (the 'id' attribute)"),
89
+ }, async ({ scene }) => {
90
+ try {
91
+ const id = await resolveSceneId(scene, client);
92
+ return ok(await client.fetch(scenePath(id)));
93
+ }
94
+ catch (e) {
95
+ return err(e);
96
+ }
97
+ });
98
+ server.tool("upsert_scene", "Create a new scene or replace an existing one via POST /api/config/scene/config/{id} (requires an admin token). Home Assistant validates the config, writes it to scenes.yaml and reloads scenes automatically — no separate reload needed. The config REPLACES the stored one entirely, so to edit call get_scene_config first and send back the modified object. Omit 'scene' to create a new one (an id is generated and returned); its entity id becomes scene.<slugified name>. Writing a scene does not activate it.", {
99
+ config: z
100
+ .record(z.unknown())
101
+ .describe("Full scene config as stored in scenes.yaml: name, entities (map of entity_id to a state string such as 'on', or an object {state, ...attributes} such as {state: 'on', brightness: 120}), icon?, metadata? (free-form object). An 'id' key, if present, must equal the scene's id"),
102
+ scene: z
103
+ .string()
104
+ .optional()
105
+ .describe("Existing scene.* entity id or internal id to replace; omit to create a new scene"),
106
+ }, async ({ config, scene }) => {
107
+ try {
108
+ const id = scene ? await resolveSceneId(scene, client) : String(Date.now());
109
+ const result = await client.fetch(scenePath(id), {
110
+ method: "POST",
111
+ body: JSON.stringify(config),
112
+ });
113
+ return ok({ id, created: !scene, result });
114
+ }
115
+ catch (e) {
116
+ return err(e);
117
+ }
118
+ });
119
+ server.tool("delete_scene", "Delete a scene from scenes.yaml via DELETE /api/config/scene/config/{id} (requires an admin token). Accepts the scene.* entity id or the internal id. Only UI-managed scenes (those stored in scenes.yaml) can be deleted; Home Assistant then removes the scene's entity registry entry. Automations and scripts that activate the scene are not updated.", {
120
+ scene: z
121
+ .string()
122
+ .describe("scene.* entity id, or the scene's internal id (the 'id' attribute)"),
123
+ }, async ({ scene }) => {
124
+ try {
125
+ const id = await resolveSceneId(scene, client);
126
+ return ok(await client.fetch(scenePath(id), { method: "DELETE" }));
127
+ }
128
+ catch (e) {
129
+ return err(e);
130
+ }
131
+ });
132
+ server.tool("list_blueprints", "List the installed blueprints of one domain via the WebSocket API (blueprint/list, requires an admin token). Returns an object keyed by blueprint path relative to config/blueprints/<domain>/, e.g. 'homeassistant/motion_light.yaml' — use that exact path, including .yaml, as use_blueprint.path in an automation or script and in delete_blueprint / substitute_blueprint. Each value is {metadata: {name, description, domain, input, source_url, ...}} or {error: '...'} for a file that failed to load.", { domain: blueprintDomain }, async ({ domain }) => {
133
+ try {
134
+ return ok(await ws.command("blueprint/list", { domain }));
135
+ }
136
+ catch (e) {
137
+ return err(e);
138
+ }
139
+ });
140
+ server.tool("import_blueprint", "Fetch a blueprint from a URL via the WebSocket API (blueprint/import, requires an admin token) WITHOUT saving it. Home Assistant itself downloads and validates the YAML (community forum topics, GitHub file and gist URLs, home-assistant.io blueprint URLs, or any URL that returns blueprint YAML; 10 second timeout). Returns suggested_filename (e.g. 'homeassistant/motion_light', without .yaml), raw_data (the YAML text), blueprint.metadata (name, domain, inputs), validation_errors (null when this Home Assistant supports the blueprint, otherwise a list of reasons) and exists (true when that filename is already installed). To install it, review raw_data and call save_blueprint with domain = blueprint.metadata.domain, path = suggested_filename, yaml = raw_data and source_url = this url.", {
141
+ url: z
142
+ .string()
143
+ .describe("URL of the blueprint, e.g. a GitHub file URL or a Home Assistant community topic"),
144
+ }, async ({ url }) => {
145
+ try {
146
+ return ok(await ws.command("blueprint/import", { url }));
147
+ }
148
+ catch (e) {
149
+ return err(e);
150
+ }
151
+ });
152
+ server.tool("save_blueprint", "Save a blueprint file to config/blueprints/<domain>/<path> via the WebSocket API (blueprint/save, requires an admin token). Home Assistant parses and validates the YAML as a blueprint of that domain (a different blueprint.domain is rejected), rewrites it in its own normalized YAML (comments are dropped) and records source_url in the metadata when given. Fails with 'already_exists' unless allow_override is true; overriding an existing blueprint reloads the automations/scripts that use it. '.yaml' is appended to the path when missing. Saving only makes the blueprint available — it creates no automation or script. Returns {domain, path, overrides_existing}.", {
153
+ domain: blueprintDomain,
154
+ path: z
155
+ .string()
156
+ .describe("Path relative to config/blueprints/<domain>/, e.g. 'homeassistant/motion_light' (the suggested_filename from import_blueprint); '.yaml' is appended when missing"),
157
+ yaml: z.string().describe("The blueprint YAML text (raw_data from import_blueprint)"),
158
+ source_url: z
159
+ .string()
160
+ .optional()
161
+ .describe("URL the blueprint came from; stored in its metadata so the UI can offer re-import"),
162
+ allow_override: z
163
+ .boolean()
164
+ .optional()
165
+ .describe("Overwrite an existing blueprint at this path (default false: fail if it exists)"),
166
+ }, async ({ domain, path, yaml, source_url, allow_override }) => {
167
+ try {
168
+ const payload = { domain, path, yaml };
169
+ if (source_url !== undefined)
170
+ payload.source_url = source_url;
171
+ if (allow_override !== undefined)
172
+ payload.allow_override = allow_override;
173
+ const result = (await ws.command("blueprint/save", payload));
174
+ return ok({ domain, path: path.endsWith(".yaml") ? path : `${path}.yaml`, ...result });
175
+ }
176
+ catch (e) {
177
+ return err(e);
178
+ }
179
+ });
180
+ server.tool("delete_blueprint", "Delete a blueprint file via the WebSocket API (blueprint/delete, requires an admin token). Home Assistant refuses with 'Blueprint in use' while an automation, script or template still uses it. Use the exact path from list_blueprints, including .yaml.", {
181
+ domain: blueprintDomain,
182
+ path: blueprintFile,
183
+ }, async ({ domain, path }) => {
184
+ try {
185
+ await ws.command("blueprint/delete", { domain, path });
186
+ return ok({ domain, path, deleted: true });
187
+ }
188
+ catch (e) {
189
+ return err(e);
190
+ }
191
+ });
192
+ server.tool("substitute_blueprint", "Preview the configuration a blueprint instance generates via the WebSocket API (blueprint/substitute, requires an admin token) without saving or changing anything. Returns {substituted_config}: the automation/script/template config with the blueprint's !input placeholders filled in from 'input' (defaults fill the rest; a missing required input fails). Use it to inspect or hand-edit a blueprint-based automation: take use_blueprint.path and use_blueprint.input from get_automation_config and pass them here.", {
193
+ domain: blueprintDomain,
194
+ path: blueprintFile,
195
+ input: z
196
+ .record(z.unknown())
197
+ .describe("Blueprint input values by input name, as in use_blueprint.input"),
198
+ }, async ({ domain, path, input }) => {
199
+ try {
200
+ return ok(await ws.command("blueprint/substitute", { domain, path, input }));
201
+ }
202
+ catch (e) {
203
+ return err(e);
204
+ }
205
+ });
206
+ }
@@ -0,0 +1,363 @@
1
+ import { z } from "zod";
2
+ import { ok, err } from "../hass/format.js";
3
+ const unitsSchema = z
4
+ .record(z.string())
5
+ .optional()
6
+ .describe("Convert results to these units, keyed by unit class, e.g. { energy: 'kWh', temperature: '°C' }. Default is the statistic's display unit");
7
+ const durationSchema = () => z.object({
8
+ days: z.number().optional(),
9
+ hours: z.number().optional(),
10
+ minutes: z.number().optional(),
11
+ seconds: z.number().optional(),
12
+ milliseconds: z.number().optional(),
13
+ });
14
+ function summarize(meta) {
15
+ return {
16
+ statistic_id: meta.statistic_id,
17
+ name: meta.name ?? null,
18
+ source: meta.source ?? null,
19
+ statistics_unit_of_measurement: meta.statistics_unit_of_measurement ?? null,
20
+ display_unit_of_measurement: meta.display_unit_of_measurement ?? null,
21
+ unit_class: meta.unit_class ?? null,
22
+ mean_type: meta.mean_type ?? 0,
23
+ has_sum: meta.has_sum ?? false,
24
+ };
25
+ }
26
+ export function registerStatisticsTools(server, ws) {
27
+ server.tool("list_statistic_ids", "List the long-term statistics HA records via the WebSocket API (recorder/list_statistic_ids): sensors with a state_class plus external statistics such as imported energy data. Each row has statistic_id, name, source ('recorder' for entities, otherwise the integration), statistics_unit_of_measurement (the unit the values are STORED in), display_unit_of_measurement, unit_class, mean_type (0 none, 1 arithmetic, 2 circular) and has_sum. Includes statistics of entities that no longer exist, which is how orphaned data is found.", {
28
+ statistic_type: z
29
+ .enum(["mean", "sum"])
30
+ .optional()
31
+ .describe("Only statistics that track a mean (min/max/mean) or a sum (counters, energy)"),
32
+ search: z
33
+ .string()
34
+ .optional()
35
+ .describe("Case-insensitive text to find in the statistic_id or name"),
36
+ }, async ({ statistic_type, search }) => {
37
+ try {
38
+ const payload = {};
39
+ if (statistic_type !== undefined)
40
+ payload.statistic_type = statistic_type;
41
+ const list = ((await ws.command("recorder/list_statistic_ids", payload)) ??
42
+ []);
43
+ const needle = search?.toLowerCase();
44
+ const statistics = list
45
+ .filter((m) => !needle ||
46
+ m.statistic_id.toLowerCase().includes(needle) ||
47
+ (m.name ?? "").toLowerCase().includes(needle))
48
+ .map(summarize);
49
+ return ok({ count: statistics.length, statistics });
50
+ }
51
+ catch (e) {
52
+ return err(e);
53
+ }
54
+ });
55
+ server.tool("get_statistics_metadata", "Get the metadata of specific statistics via the WebSocket API (recorder/get_statistics_metadata): statistic_id, name, source, statistics_unit_of_measurement (stored unit), display_unit_of_measurement, unit_class, mean_type and has_sum. Omit statistic_ids for all of them (same result as list_statistic_ids). Unknown ids are simply left out.", {
56
+ statistic_ids: z
57
+ .array(z.string())
58
+ .optional()
59
+ .describe("statistic_ids to look up, e.g. ['sensor.energy_total']"),
60
+ }, async ({ statistic_ids }) => {
61
+ try {
62
+ const payload = {};
63
+ if (statistic_ids !== undefined)
64
+ payload.statistic_ids = statistic_ids;
65
+ const list = ((await ws.command("recorder/get_statistics_metadata", payload)) ??
66
+ []);
67
+ const statistics = list.map(summarize);
68
+ return ok({ count: statistics.length, statistics });
69
+ }
70
+ catch (e) {
71
+ return err(e);
72
+ }
73
+ });
74
+ server.tool("get_statistics", "Get long-term statistics time series for one or more statistic_ids via the WebSocket API (recorder/statistics_during_period) — aggregates HA keeps far longer than state history, e.g. daily energy use over a year. Returns { count, statistics: { <statistic_id>: [rows] } }; rows have start, end (and last_reset) as epoch MILLISECONDS plus the requested types: mean/min/max (measurement sensors), state/sum/change (total and total_increasing sensors such as energy), last_reset. period is the bucket size: '5minute' data only exists for the recorder's purge_keep_days (10 by default), the rest is kept indefinitely. Large ranges with fine periods are big — prefer 'day' or coarser, and restrict types.", {
75
+ start_time: z
76
+ .string()
77
+ .describe("ISO 8601 start of the range, e.g. '2026-06-01T00:00:00+02:00'"),
78
+ end_time: z.string().optional().describe("ISO 8601 end of the range (default: now)"),
79
+ statistic_ids: z
80
+ .array(z.string())
81
+ .min(1)
82
+ .describe("statistic_ids to fetch, e.g. ['sensor.energy_total']"),
83
+ period: z
84
+ .enum(["5minute", "hour", "day", "week", "month", "year"])
85
+ .describe("Bucket size of each row"),
86
+ types: z
87
+ .array(z.enum(["change", "last_reset", "max", "mean", "min", "state", "sum"]))
88
+ .optional()
89
+ .describe("Which values to return per row (default: all that apply)"),
90
+ units: unitsSchema,
91
+ }, async ({ start_time, end_time, statistic_ids, period, types, units }) => {
92
+ try {
93
+ const payload = { start_time, statistic_ids, period };
94
+ if (end_time !== undefined)
95
+ payload.end_time = end_time;
96
+ if (types !== undefined)
97
+ payload.types = types;
98
+ if (units !== undefined)
99
+ payload.units = units;
100
+ const statistics = ((await ws.command("recorder/statistics_during_period", payload)) ??
101
+ {});
102
+ return ok({ count: Object.keys(statistics).length, statistics });
103
+ }
104
+ catch (e) {
105
+ return err(e);
106
+ }
107
+ });
108
+ server.tool("get_statistic_summary", "Get ONE aggregate (max, mean, min and/or change) of a single statistic over a period via the WebSocket API (recorder/statistic_during_period) — e.g. 'energy used this month' or 'average temperature of the last 24 hours'. Choose the period with at most one of calendar (current or offset hour/day/week/month/year in local time), fixed_period (explicit start/end) or rolling_window (a duration back from now); with none, the whole recorded history is used. 'change' is the increase of a sum-type statistic (energy, counters). Returns { statistic_id, max?, mean?, min?, change? } or found: false for an unknown statistic_id.", {
109
+ statistic_id: z.string().describe("The statistic_id, e.g. 'sensor.energy_total'"),
110
+ types: z
111
+ .array(z.enum(["max", "mean", "min", "change"]))
112
+ .optional()
113
+ .describe("Which aggregates to return (default all four)"),
114
+ units: unitsSchema,
115
+ calendar: z
116
+ .object({
117
+ period: z.enum(["hour", "day", "week", "month", "year"]),
118
+ offset: z
119
+ .number()
120
+ .int()
121
+ .optional()
122
+ .describe("Whole periods from the current one; -1 is the previous period"),
123
+ first_weekday: z
124
+ .enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"])
125
+ .optional()
126
+ .describe("Week start for period 'week' (default mon)"),
127
+ })
128
+ .optional()
129
+ .describe("A calendar period in local time, e.g. { period: 'month', offset: -1 }"),
130
+ fixed_period: z
131
+ .object({
132
+ start_time: z.string().optional().describe("ISO 8601 start; omit for the beginning"),
133
+ end_time: z.string().optional().describe("ISO 8601 end; omit for now"),
134
+ })
135
+ .optional()
136
+ .describe("An explicit time range"),
137
+ rolling_window: z
138
+ .object({
139
+ duration: durationSchema().describe("Window length, e.g. { hours: 24 }"),
140
+ offset: durationSchema()
141
+ .optional()
142
+ .describe("Shift the window, e.g. { days: -7 } for the same window a week ago"),
143
+ })
144
+ .optional()
145
+ .describe("A window of the given length ending now (shifted by offset)"),
146
+ }, async ({ statistic_id, types, units, calendar, fixed_period, rolling_window }) => {
147
+ try {
148
+ const periods = [calendar, fixed_period, rolling_window].filter((p) => p !== undefined);
149
+ if (periods.length > 1) {
150
+ throw new Error("Provide at most one of 'calendar', 'fixed_period' or 'rolling_window'");
151
+ }
152
+ const payload = { statistic_id };
153
+ if (types !== undefined)
154
+ payload.types = types;
155
+ if (units !== undefined)
156
+ payload.units = units;
157
+ if (calendar !== undefined)
158
+ payload.calendar = calendar;
159
+ if (fixed_period !== undefined)
160
+ payload.fixed_period = fixed_period;
161
+ if (rolling_window !== undefined)
162
+ payload.rolling_window = rolling_window;
163
+ const result = (await ws.command("recorder/statistic_during_period", payload));
164
+ if (!result || Object.keys(result).length === 0) {
165
+ return ok({ statistic_id, found: false });
166
+ }
167
+ return ok({ statistic_id, ...result });
168
+ }
169
+ catch (e) {
170
+ return err(e);
171
+ }
172
+ });
173
+ server.tool("validate_statistics", "Check the recorded statistics for problems via the WebSocket API (recorder/validate_statistics) — e.g. a sensor whose unit, mean type or state_class changed since statistics were recorded (issue types units_changed, mean_type_changed, state_class_removed), one the recorder filter stopped or never recorded (entity_no_longer_recorded, entity_not_recorded) or one whose sensor is gone (no_state). Returns { count, issues: { <statistic_id>: [{ type, data }] } } where count is the number of affected statistics; an empty result means all is well. Fix unit problems with update_statistics_metadata or change_statistics_unit, and orphaned ones with clear_statistics.", {}, async () => {
174
+ try {
175
+ const issues = ((await ws.command("recorder/validate_statistics")) ?? {});
176
+ return ok({ count: Object.keys(issues).length, issues });
177
+ }
178
+ catch (e) {
179
+ return err(e);
180
+ }
181
+ });
182
+ server.tool("refresh_statistics_issues", "Recompute the statistics problems shown on the Repairs dashboard via the WebSocket API (recorder/update_statistics_issues): the same checks as validate_statistics, but they create or clear the matching repair issues in Home Assistant (see list_repairs). Run it after fixing statistics so stale repair entries disappear.", {}, async () => {
183
+ try {
184
+ await ws.command("recorder/update_statistics_issues");
185
+ return ok({ refreshed: true });
186
+ }
187
+ catch (e) {
188
+ return err(e);
189
+ }
190
+ });
191
+ server.tool("clear_statistics", "DELETE long-term statistics via the WebSocket API (recorder/clear_statistics), cannot be undone. With no time range ALL rows and the metadata of each statistic_id are removed; with start_time AND end_time only the 5-minute and hourly rows overlapping that range are removed and the metadata is kept. Use it for statistics of deleted entities or to discard bad data; statistics of entities that still exist start recording again from new states. State history is not touched. Waits up to 10 seconds for the recorder to finish. Requires an admin token.", {
192
+ statistic_ids: z
193
+ .array(z.string())
194
+ .min(1)
195
+ .describe("statistic_ids to clear, e.g. ['sensor.old_meter']"),
196
+ start_time: z
197
+ .string()
198
+ .optional()
199
+ .describe("ISO 8601 start of the range to clear; requires end_time"),
200
+ end_time: z
201
+ .string()
202
+ .optional()
203
+ .describe("ISO 8601 end of the range to clear; requires start_time"),
204
+ }, async ({ statistic_ids, start_time, end_time }) => {
205
+ try {
206
+ if ((start_time === undefined) !== (end_time === undefined)) {
207
+ throw new Error("start_time and end_time must be provided together");
208
+ }
209
+ const payload = { statistic_ids };
210
+ if (start_time !== undefined)
211
+ payload.start_time = start_time;
212
+ if (end_time !== undefined)
213
+ payload.end_time = end_time;
214
+ await ws.command("recorder/clear_statistics", payload);
215
+ return ok({ cleared: statistic_ids, ...(start_time ? { start_time, end_time } : {}) });
216
+ }
217
+ catch (e) {
218
+ return err(e);
219
+ }
220
+ });
221
+ server.tool("update_statistics_metadata", "Change the unit stored for a statistic WITHOUT converting its values, via the WebSocket API (recorder/update_statistics_metadata) — for when the recorded numbers are already correct but labelled with the wrong unit. To rescale existing values to another unit use change_statistics_unit instead. unit_class (e.g. 'energy', 'power', null for none) selects the conversion family; if omitted HA derives it from the unit, and the unit must be valid for the class. Requires an admin token.", {
222
+ statistic_id: z.string().describe("The statistic_id to update"),
223
+ unit_of_measurement: z
224
+ .string()
225
+ .nullable()
226
+ .describe("The unit the stored values are in, or null for unitless"),
227
+ unit_class: z
228
+ .string()
229
+ .nullable()
230
+ .optional()
231
+ .describe("Unit conversion class, e.g. 'energy'; null for none. Omit to let HA derive it"),
232
+ }, async ({ statistic_id, unit_of_measurement, unit_class }) => {
233
+ try {
234
+ const payload = { statistic_id, unit_of_measurement };
235
+ if (unit_class !== undefined)
236
+ payload.unit_class = unit_class;
237
+ await ws.command("recorder/update_statistics_metadata", payload);
238
+ return ok({
239
+ statistic_id,
240
+ unit_of_measurement,
241
+ ...(unit_class !== undefined ? { unit_class } : {}),
242
+ });
243
+ }
244
+ catch (e) {
245
+ return err(e);
246
+ }
247
+ });
248
+ server.tool("change_statistics_unit", "Convert all stored values of a statistic from one unit to another via the WebSocket API (recorder/change_statistics_unit), e.g. Wh to kWh, and relabel it. old_unit_of_measurement must equal the statistic's current stored unit (statistics_unit_of_measurement in list_statistic_ids) and the two units must be convertible, otherwise HA errors. Only statistics with source 'recorder' (entity statistics) are converted; a mismatch is skipped by the recorder with a log warning and still reports success. The recorder applies the change in the background after the call returns, and it cannot be undone except by converting back. Requires an admin token.", {
249
+ statistic_id: z.string().describe("The statistic_id to convert"),
250
+ old_unit_of_measurement: z
251
+ .string()
252
+ .nullable()
253
+ .describe("The unit the values are currently stored in"),
254
+ new_unit_of_measurement: z.string().nullable().describe("The unit to convert to"),
255
+ }, async ({ statistic_id, old_unit_of_measurement, new_unit_of_measurement }) => {
256
+ try {
257
+ await ws.command("recorder/change_statistics_unit", {
258
+ statistic_id,
259
+ new_unit_of_measurement,
260
+ old_unit_of_measurement,
261
+ });
262
+ return ok({ statistic_id, old_unit_of_measurement, new_unit_of_measurement, queued: true });
263
+ }
264
+ catch (e) {
265
+ return err(e);
266
+ }
267
+ });
268
+ server.tool("import_statistics", "Insert or overwrite hourly long-term statistics via the WebSocket API (recorder/import_statistics) — e.g. to backfill energy history from another system. statistic_id is either an entity id ('sensor.x', source must be 'recorder') or an external statistic 'domain:name' (source must equal the domain, e.g. 'my_import:grid'). Each stats row needs 'start' on the hour with a timezone; rows that already exist for the same start are overwritten and the metadata is replaced. Sum-type (energy) rows normally carry state and sum; measurement rows mean/min/max with mean_type 1. The recorder writes in the background after the call returns. Requires an admin token.", {
269
+ metadata: z
270
+ .object({
271
+ statistic_id: z
272
+ .string()
273
+ .describe("'sensor.x' for an entity or 'domain:name' for external"),
274
+ source: z.string().describe("'recorder' for entity ids, otherwise the domain of the id"),
275
+ name: z.string().nullable().optional().describe("Display name; null for none"),
276
+ unit_of_measurement: z
277
+ .string()
278
+ .nullable()
279
+ .describe("Unit of the values, null for unitless"),
280
+ has_sum: z.boolean().describe("true if rows carry a sum/state (counters, energy)"),
281
+ mean_type: z
282
+ .union([z.literal(0), z.literal(1), z.literal(2)])
283
+ .optional()
284
+ .describe("0 none (default), 1 arithmetic mean, 2 circular mean (e.g. wind direction)"),
285
+ unit_class: z
286
+ .string()
287
+ .nullable()
288
+ .optional()
289
+ .describe("Unit conversion class, e.g. 'energy'; omit to let HA derive it"),
290
+ })
291
+ .describe("Describes the statistic the rows belong to"),
292
+ stats: z
293
+ .array(z.object({
294
+ start: z.string().describe("Hour start, ISO 8601 with timezone, minutes/seconds 0"),
295
+ mean: z.number().optional(),
296
+ min: z.number().optional(),
297
+ max: z.number().optional(),
298
+ last_reset: z.string().nullable().optional().describe("ISO 8601 with timezone"),
299
+ state: z.number().optional(),
300
+ sum: z.number().optional(),
301
+ }))
302
+ .min(1)
303
+ .describe("The hourly rows to write"),
304
+ }, async ({ metadata, stats }) => {
305
+ try {
306
+ const { statistic_id, source } = metadata;
307
+ const separator = statistic_id.indexOf(":");
308
+ if (separator >= 0) {
309
+ const domain = statistic_id.slice(0, separator);
310
+ if (source !== domain) {
311
+ throw new Error(`source must be '${domain}' for the external statistic '${statistic_id}' (got '${source}')`);
312
+ }
313
+ }
314
+ else if (source !== "recorder") {
315
+ throw new Error(`source must be 'recorder' for the entity statistic '${statistic_id}' (got '${source}')`);
316
+ }
317
+ await ws.command("recorder/import_statistics", {
318
+ metadata: { ...metadata, name: metadata.name ?? null },
319
+ stats,
320
+ });
321
+ return ok({ statistic_id, rows: stats.length, queued: true });
322
+ }
323
+ catch (e) {
324
+ return err(e);
325
+ }
326
+ });
327
+ server.tool("adjust_sum_statistics", "Add a constant to the sum of a statistic from a point in time onwards via the WebSocket API (recorder/adjust_sum_statistics) — the fix for a counter or energy meter that reset or jumped and left a spike or negative step in the totals. Every hourly and 5-minute row at or after start_time gets sum += adjustment. adjustment_unit_of_measurement must be the statistic's stored unit or one convertible to it (null for unitless). The recorder applies it in the background after the call returns. Requires an admin token.", {
328
+ statistic_id: z.string().describe("The statistic_id to adjust"),
329
+ start_time: z.string().describe("ISO 8601 time from which the adjustment applies"),
330
+ adjustment: z.number().describe("Amount to add to the sum (negative to subtract)"),
331
+ adjustment_unit_of_measurement: z
332
+ .string()
333
+ .nullable()
334
+ .describe("Unit of 'adjustment'; null for unitless statistics"),
335
+ }, async ({ statistic_id, start_time, adjustment, adjustment_unit_of_measurement }) => {
336
+ try {
337
+ await ws.command("recorder/adjust_sum_statistics", {
338
+ statistic_id,
339
+ start_time,
340
+ adjustment,
341
+ adjustment_unit_of_measurement,
342
+ });
343
+ return ok({
344
+ statistic_id,
345
+ start_time,
346
+ adjustment,
347
+ adjustment_unit_of_measurement,
348
+ queued: true,
349
+ });
350
+ }
351
+ catch (e) {
352
+ return err(e);
353
+ }
354
+ });
355
+ server.tool("get_recorder_entity_options", "Check whether the recorder records an entity via the WebSocket API (recorder/entity_options/get): returns { recording_disabled_by } — 'user' when the entity is excluded by the recorder's include/exclude configuration, null when it is recorded. Explains why an entity has no history or statistics. Requires an admin token.", { entity_id: z.string().describe("The entity_id to check, e.g. 'sensor.power'") }, async ({ entity_id }) => {
356
+ try {
357
+ return ok(await ws.command("recorder/entity_options/get", { entity_id }));
358
+ }
359
+ catch (e) {
360
+ return err(e);
361
+ }
362
+ });
363
+ }
@@ -9,6 +9,23 @@ export function registerSystemTools(server, client) {
9
9
  return err(e);
10
10
  }
11
11
  });
12
+ server.tool("get_core_state", "Get the Home Assistant core run state (GET /api/core/state): { state: 'RUNNING' | 'STARTING' | 'NOT_RUNNING' | ..., recorder_state: { migration_in_progress, migration_is_live } }. A lightweight way to check whether HA has finished starting, e.g. after a restart.", {}, async () => {
13
+ try {
14
+ return ok(await client.fetch("/api/core/state"));
15
+ }
16
+ catch (e) {
17
+ return err(e);
18
+ }
19
+ });
20
+ server.tool("list_components", "List the currently loaded components (GET /api/components), including platform entries such as 'sensor.template'. Use it to check whether an integration is loaded.", {}, async () => {
21
+ try {
22
+ const components = (await client.fetch("/api/components"));
23
+ return ok({ count: components.length, components: [...components].sort() });
24
+ }
25
+ catch (e) {
26
+ return err(e);
27
+ }
28
+ });
12
29
  server.tool("check_config", "Validate the Home Assistant YAML configuration currently on the server (POST /api/config/core/check_config). Returns { result: 'valid' | 'invalid', errors }. Requires the 'config' integration (included in default_config). Run this after editing YAML and before reloading or restarting.", {}, async () => {
13
30
  try {
14
31
  return ok(await client.fetch("/api/config/core/check_config", { method: "POST" }));