@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.
- package/README.md +142 -39
- package/bin/homeassistant-mcp.js +51 -0
- package/binaries/darwin-arm64/homeassistant-mcp +0 -0
- package/binaries/darwin-x64/homeassistant-mcp +0 -0
- package/binaries/linux-arm64/homeassistant-mcp +0 -0
- package/binaries/linux-x64/homeassistant-mcp +0 -0
- package/binaries/win32-x64/homeassistant-mcp.exe +0 -0
- package/package.json +5 -38
- package/dist/config.js +0 -26
- package/dist/hass/format.js +0 -38
- package/dist/hass/rest.js +0 -50
- package/dist/hass/ws.js +0 -80
- package/dist/index.js +0 -17
- package/dist/server.js +0 -9
- package/dist/tools/auth.js +0 -191
- package/dist/tools/automations.js +0 -62
- package/dist/tools/backup.js +0 -375
- package/dist/tools/control.js +0 -133
- package/dist/tools/dashboards.js +0 -206
- package/dist/tools/diagnostics.js +0 -537
- package/dist/tools/energy.js +0 -235
- package/dist/tools/entities.js +0 -57
- package/dist/tools/hacs.js +0 -52
- package/dist/tools/helpers.js +0 -98
- package/dist/tools/history.js +0 -57
- package/dist/tools/integrations.js +0 -538
- package/dist/tools/lists.js +0 -216
- package/dist/tools/organization.js +0 -548
- package/dist/tools/raw.js +0 -41
- package/dist/tools/registry.js +0 -195
- package/dist/tools/reload.js +0 -40
- package/dist/tools/resources.js +0 -56
- package/dist/tools/scripts.js +0 -206
- package/dist/tools/services.js +0 -33
- package/dist/tools/statistics.js +0 -363
- package/dist/tools/system.js +0 -57
- package/dist/tools/templates.js +0 -21
- package/dist/tools/trace.js +0 -74
- package/dist/tools/zha.js +0 -121
- package/dist/toolsets.js +0 -356
package/dist/tools/statistics.js
DELETED
|
@@ -1,363 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/tools/system.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import { ok, err } from "../hass/format.js";
|
|
3
|
-
export function registerSystemTools(server, client) {
|
|
4
|
-
server.tool("get_config", "Get the running Home Assistant configuration: version, location, unit system, time zone, currency, config directory, and the list of loaded components/integrations. Also serves as a connectivity/token check.", {}, async () => {
|
|
5
|
-
try {
|
|
6
|
-
return ok(await client.fetch("/api/config"));
|
|
7
|
-
}
|
|
8
|
-
catch (e) {
|
|
9
|
-
return err(e);
|
|
10
|
-
}
|
|
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
|
-
});
|
|
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 () => {
|
|
30
|
-
try {
|
|
31
|
-
return ok(await client.fetch("/api/config/core/check_config", { method: "POST" }));
|
|
32
|
-
}
|
|
33
|
-
catch (e) {
|
|
34
|
-
return err(e);
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
server.tool("get_error_log", "Get the Home Assistant error log as plain text. Returns the most recent lines (default 100). Useful for diagnosing why a config or automation failed to load.", {
|
|
38
|
-
lines: z
|
|
39
|
-
.number()
|
|
40
|
-
.int()
|
|
41
|
-
.min(0)
|
|
42
|
-
.optional()
|
|
43
|
-
.describe("Number of trailing lines to return (default 100; use 0 for the full log)"),
|
|
44
|
-
}, async ({ lines }) => {
|
|
45
|
-
try {
|
|
46
|
-
const text = await client.fetchText("/api/error_log");
|
|
47
|
-
const n = lines ?? 100;
|
|
48
|
-
if (n > 0) {
|
|
49
|
-
return ok(text.split("\n").slice(-n).join("\n"));
|
|
50
|
-
}
|
|
51
|
-
return ok(text);
|
|
52
|
-
}
|
|
53
|
-
catch (e) {
|
|
54
|
-
return err(e);
|
|
55
|
-
}
|
|
56
|
-
});
|
|
57
|
-
}
|
package/dist/tools/templates.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import { ok, err } from "../hass/format.js";
|
|
3
|
-
export function registerTemplateTools(server, client) {
|
|
4
|
-
server.tool("render_template", "Render a Home Assistant Jinja2 template against live state and return the result as text (POST /api/template). Use this to develop and debug template sensors, template conditions, and automation templates, e.g. \"{{ states('sensor.temperature') | float > 20 }}\". Read-only: HA renders without side effects.", {
|
|
5
|
-
template: z
|
|
6
|
-
.string()
|
|
7
|
-
.describe("Jinja2 template string, e.g. \"{{ states('sensor.temperature') }}\""),
|
|
8
|
-
variables: z
|
|
9
|
-
.record(z.unknown())
|
|
10
|
-
.optional()
|
|
11
|
-
.describe("Optional variables made available to the template"),
|
|
12
|
-
}, async ({ template, variables }) => {
|
|
13
|
-
try {
|
|
14
|
-
const body = JSON.stringify(variables ? { template, variables } : { template });
|
|
15
|
-
return ok(await client.fetchText("/api/template", { method: "POST", body }));
|
|
16
|
-
}
|
|
17
|
-
catch (e) {
|
|
18
|
-
return err(e);
|
|
19
|
-
}
|
|
20
|
-
});
|
|
21
|
-
}
|
package/dist/tools/trace.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import { ok, err, domainOf } from "../hass/format.js";
|
|
3
|
-
async function resolveTarget(entityId, client) {
|
|
4
|
-
const domain = domainOf(entityId);
|
|
5
|
-
if (domain !== "automation" && domain !== "script") {
|
|
6
|
-
throw new Error(`Traces are only available for automation.* or script.* entities, got ${entityId}`);
|
|
7
|
-
}
|
|
8
|
-
const objectId = entityId.slice(domain.length + 1);
|
|
9
|
-
if (!objectId) {
|
|
10
|
-
throw new Error(`Invalid ${domain} entity id: ${entityId}`);
|
|
11
|
-
}
|
|
12
|
-
if (domain === "script") {
|
|
13
|
-
return { domain, item_id: objectId };
|
|
14
|
-
}
|
|
15
|
-
const state = (await client.fetch(`/api/states/${encodeURIComponent(entityId)}`));
|
|
16
|
-
const id = state.attributes?.id;
|
|
17
|
-
if (id === undefined || id === null || id === "") {
|
|
18
|
-
throw new Error(`Automation ${entityId} has no 'id' attribute, so Home Assistant stores no traces for it`);
|
|
19
|
-
}
|
|
20
|
-
return { domain, item_id: String(id) };
|
|
21
|
-
}
|
|
22
|
-
function startMs(t) {
|
|
23
|
-
const s = t.timestamp?.start;
|
|
24
|
-
const n = s ? Date.parse(s) : 0;
|
|
25
|
-
return Number.isNaN(n) ? 0 : n;
|
|
26
|
-
}
|
|
27
|
-
export function registerTraceTools(server, ws, client) {
|
|
28
|
-
server.tool("list_traces", "List recent execution traces (newest first) for an automation or script via the WebSocket trace API — to debug whether and how it ran. Each summary has run_id, state, script_execution (finished/error/aborted/cancelled/…), last_step, timestamp and any error. Use get_trace with a run_id for the full step-by-step trace.", { entity_id: z.string().describe("An automation.* or script.* entity id") }, async ({ entity_id }) => {
|
|
29
|
-
try {
|
|
30
|
-
const { domain, item_id } = await resolveTarget(entity_id, client);
|
|
31
|
-
const list = ((await ws.command("trace/list", { domain, item_id })) ??
|
|
32
|
-
[]);
|
|
33
|
-
const traces = [...list]
|
|
34
|
-
.sort((a, b) => startMs(b) - startMs(a))
|
|
35
|
-
.map((t) => {
|
|
36
|
-
const row = {
|
|
37
|
-
run_id: t.run_id,
|
|
38
|
-
state: t.state,
|
|
39
|
-
script_execution: t.script_execution,
|
|
40
|
-
last_step: t.last_step,
|
|
41
|
-
timestamp: t.timestamp,
|
|
42
|
-
};
|
|
43
|
-
if (t.error !== undefined)
|
|
44
|
-
row.error = t.error;
|
|
45
|
-
return row;
|
|
46
|
-
});
|
|
47
|
-
return ok({ entity_id, domain, item_id, count: traces.length, traces });
|
|
48
|
-
}
|
|
49
|
-
catch (e) {
|
|
50
|
-
return err(e);
|
|
51
|
-
}
|
|
52
|
-
});
|
|
53
|
-
server.tool("get_trace", "Get the full execution trace for one run of an automation or script: the per-step path with each step's result, the config, variables, context and any error. Find run_id with list_traces.", {
|
|
54
|
-
entity_id: z.string().describe("An automation.* or script.* entity id"),
|
|
55
|
-
run_id: z.string().describe("Run id from list_traces"),
|
|
56
|
-
}, async ({ entity_id, run_id }) => {
|
|
57
|
-
try {
|
|
58
|
-
const { domain, item_id } = await resolveTarget(entity_id, client);
|
|
59
|
-
return ok(await ws.command("trace/get", { domain, item_id, run_id }));
|
|
60
|
-
}
|
|
61
|
-
catch (e) {
|
|
62
|
-
return err(e);
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
server.tool("get_trace_contexts", "Map Home Assistant context ids to the trace run that produced them for an automation or script (trace/contexts) — useful for tracing causality, e.g. which automation run triggered another.", { entity_id: z.string().describe("An automation.* or script.* entity id") }, async ({ entity_id }) => {
|
|
66
|
-
try {
|
|
67
|
-
const { domain, item_id } = await resolveTarget(entity_id, client);
|
|
68
|
-
return ok(await ws.command("trace/contexts", { domain, item_id }));
|
|
69
|
-
}
|
|
70
|
-
catch (e) {
|
|
71
|
-
return err(e);
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
|
-
}
|
package/dist/tools/zha.js
DELETED
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import { ok, err } from "../hass/format.js";
|
|
3
|
-
// An entity_id can be listed either on the groupable endpoint itself or, on some
|
|
4
|
-
// HA versions where the endpoint list comes back empty/null, only under the
|
|
5
|
-
// device. Check both.
|
|
6
|
-
function endpointHasEntity(ep, entityId) {
|
|
7
|
-
const onEndpoint = ep.entities?.some((e) => e?.entity_id === entityId);
|
|
8
|
-
const onDevice = ep.device?.entities?.some((e) => e?.entity_id === entityId);
|
|
9
|
-
return Boolean(onEndpoint || onDevice);
|
|
10
|
-
}
|
|
11
|
-
function endpointEntityIds(ep) {
|
|
12
|
-
const refs = [...(ep.entities ?? []), ...(ep.device?.entities ?? [])];
|
|
13
|
-
return [
|
|
14
|
-
...new Set(refs.filter((e) => !!e?.entity_id).map((e) => e.entity_id)),
|
|
15
|
-
];
|
|
16
|
-
}
|
|
17
|
-
const memberSchema = z.union([
|
|
18
|
-
z.string(),
|
|
19
|
-
z.object({
|
|
20
|
-
ieee: z.string(),
|
|
21
|
-
endpoint_id: z.number().int().nonnegative(),
|
|
22
|
-
}),
|
|
23
|
-
]);
|
|
24
|
-
async function resolveMembers(ws, members) {
|
|
25
|
-
const needLookup = members.some((m) => typeof m === "string");
|
|
26
|
-
let groupable = [];
|
|
27
|
-
if (needLookup) {
|
|
28
|
-
groupable = (await ws.command("zha/devices/groupable"));
|
|
29
|
-
}
|
|
30
|
-
return members.map((m) => {
|
|
31
|
-
if (typeof m !== "string")
|
|
32
|
-
return { ieee: m.ieee, endpoint_id: m.endpoint_id };
|
|
33
|
-
const hit = groupable.find((ep) => endpointHasEntity(ep, m));
|
|
34
|
-
if (!hit) {
|
|
35
|
-
throw new Error(`'${m}' is not a groupable ZHA entity. A ZHA group member must be a ZHA entity on an endpoint that supports the Zigbee Groups cluster (see list_zha_groupable). Non-ZHA entities (Wi-Fi/Shelly/Hue-bridge/etc.) cannot join a ZHA group.`);
|
|
36
|
-
}
|
|
37
|
-
return { ieee: hit.device.ieee, endpoint_id: hit.endpoint_id };
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
export function registerZhaTools(server, ws) {
|
|
41
|
-
server.tool("list_zha_groups", "List existing ZHA (Zigbee) groups via the WebSocket API (zha/groups). Each group has a group_id, name and its members. A ZHA group lives on the Zigbee coordinator and is exposed to HA as a single group entity (e.g. one light.* that drives all members together via Zigbee multicast).", {}, async () => {
|
|
42
|
-
try {
|
|
43
|
-
return ok(await ws.command("zha/groups"));
|
|
44
|
-
}
|
|
45
|
-
catch (e) {
|
|
46
|
-
return err(e);
|
|
47
|
-
}
|
|
48
|
-
});
|
|
49
|
-
server.tool("list_zha_groupable", "List ZHA device endpoints that can be added to a ZHA group (zha/devices/groupable) — endpoints whose device supports the Zigbee Groups cluster. Returns, per endpoint, its ieee + endpoint_id and the entities on it, so you can choose group members by entity_id. Use this to see what create_zha_group / add_zha_group_members accept.", {}, async () => {
|
|
50
|
-
try {
|
|
51
|
-
const eps = (await ws.command("zha/devices/groupable"));
|
|
52
|
-
const endpoints = eps.map((ep) => ({
|
|
53
|
-
ieee: ep.device?.ieee ?? null,
|
|
54
|
-
endpoint_id: ep.endpoint_id,
|
|
55
|
-
device_name: ep.device?.user_given_name ?? ep.device?.name ?? null,
|
|
56
|
-
entities: endpointEntityIds(ep),
|
|
57
|
-
}));
|
|
58
|
-
return ok({ count: endpoints.length, endpoints });
|
|
59
|
-
}
|
|
60
|
-
catch (e) {
|
|
61
|
-
return err(e);
|
|
62
|
-
}
|
|
63
|
-
});
|
|
64
|
-
server.tool("create_zha_group", "Create a ZHA (Zigbee) group on the coordinator (zha/group/add) and return the new group (group_id, name, members). This is configuration authoring — it does not switch anything; it tells the Zigbee network to treat the members as one group, and HA then exposes a single group entity (e.g. light.<name>) that controls them together via Zigbee multicast. 'members' is optional and accepts entity_ids (resolved to ieee+endpoint via list_zha_groupable) and/or explicit {ieee, endpoint_id} objects; only groupable ZHA entities are valid. The HA group entity is created asynchronously and may not be in this response — read its entity_id from the entity registry afterwards.", {
|
|
65
|
-
name: z.string().describe("Friendly name for the new group, e.g. 'Iris TV'"),
|
|
66
|
-
members: z
|
|
67
|
-
.array(memberSchema)
|
|
68
|
-
.optional()
|
|
69
|
-
.describe("Initial members: entity_ids (e.g. 'light.philips_iris_tv_left') and/or {ieee, endpoint_id} objects. Omit to create an empty group and add members later."),
|
|
70
|
-
}, async ({ name, members }) => {
|
|
71
|
-
try {
|
|
72
|
-
const payload = { group_name: name };
|
|
73
|
-
if (members && members.length)
|
|
74
|
-
payload.members = await resolveMembers(ws, members);
|
|
75
|
-
return ok(await ws.command("zha/group/add", payload));
|
|
76
|
-
}
|
|
77
|
-
catch (e) {
|
|
78
|
-
return err(e);
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
server.tool("add_zha_group_members", "Add members to an existing ZHA group (zha/group/members/add). 'members' accepts entity_ids (resolved via list_zha_groupable) and/or {ieee, endpoint_id} objects. Returns the updated group.", {
|
|
82
|
-
group_id: z.number().int().describe("Target group_id (from list_zha_groups)"),
|
|
83
|
-
members: z
|
|
84
|
-
.array(memberSchema)
|
|
85
|
-
.min(1)
|
|
86
|
-
.describe("Members to add: entity_ids and/or {ieee, endpoint_id} objects"),
|
|
87
|
-
}, async ({ group_id, members }) => {
|
|
88
|
-
try {
|
|
89
|
-
const resolved = await resolveMembers(ws, members);
|
|
90
|
-
return ok(await ws.command("zha/group/members/add", { group_id, members: resolved }));
|
|
91
|
-
}
|
|
92
|
-
catch (e) {
|
|
93
|
-
return err(e);
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
server.tool("remove_zha_group_members", "Remove members from an existing ZHA group (zha/group/members/remove). 'members' accepts entity_ids (resolved via list_zha_groupable) and/or {ieee, endpoint_id} objects. Returns the updated group.", {
|
|
97
|
-
group_id: z.number().int().describe("Target group_id (from list_zha_groups)"),
|
|
98
|
-
members: z
|
|
99
|
-
.array(memberSchema)
|
|
100
|
-
.min(1)
|
|
101
|
-
.describe("Members to remove: entity_ids and/or {ieee, endpoint_id} objects"),
|
|
102
|
-
}, async ({ group_id, members }) => {
|
|
103
|
-
try {
|
|
104
|
-
const resolved = await resolveMembers(ws, members);
|
|
105
|
-
return ok(await ws.command("zha/group/members/remove", { group_id, members: resolved }));
|
|
106
|
-
}
|
|
107
|
-
catch (e) {
|
|
108
|
-
return err(e);
|
|
109
|
-
}
|
|
110
|
-
});
|
|
111
|
-
server.tool("remove_zha_group", "Delete one or more ZHA groups by id (zha/group/remove). This removes the group from the Zigbee coordinator and its HA group entity; the member devices themselves are untouched. Returns the remaining groups.", {
|
|
112
|
-
group_ids: z.array(z.number().int()).min(1).describe("group_id(s) to delete"),
|
|
113
|
-
}, async ({ group_ids }) => {
|
|
114
|
-
try {
|
|
115
|
-
return ok(await ws.command("zha/group/remove", { group_ids }));
|
|
116
|
-
}
|
|
117
|
-
catch (e) {
|
|
118
|
-
return err(e);
|
|
119
|
-
}
|
|
120
|
-
});
|
|
121
|
-
}
|