@orellbuehler/homeassistant-mcp 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +142 -39
  2. package/bin/homeassistant-mcp.js +51 -0
  3. package/binaries/darwin-arm64/homeassistant-mcp +0 -0
  4. package/binaries/darwin-x64/homeassistant-mcp +0 -0
  5. package/binaries/linux-arm64/homeassistant-mcp +0 -0
  6. package/binaries/linux-x64/homeassistant-mcp +0 -0
  7. package/binaries/win32-x64/homeassistant-mcp.exe +0 -0
  8. package/package.json +5 -38
  9. package/dist/config.js +0 -26
  10. package/dist/hass/format.js +0 -38
  11. package/dist/hass/rest.js +0 -50
  12. package/dist/hass/ws.js +0 -80
  13. package/dist/index.js +0 -17
  14. package/dist/server.js +0 -9
  15. package/dist/tools/auth.js +0 -191
  16. package/dist/tools/automations.js +0 -62
  17. package/dist/tools/backup.js +0 -375
  18. package/dist/tools/control.js +0 -133
  19. package/dist/tools/dashboards.js +0 -206
  20. package/dist/tools/diagnostics.js +0 -537
  21. package/dist/tools/energy.js +0 -235
  22. package/dist/tools/entities.js +0 -57
  23. package/dist/tools/hacs.js +0 -52
  24. package/dist/tools/helpers.js +0 -98
  25. package/dist/tools/history.js +0 -57
  26. package/dist/tools/integrations.js +0 -538
  27. package/dist/tools/lists.js +0 -216
  28. package/dist/tools/organization.js +0 -548
  29. package/dist/tools/raw.js +0 -41
  30. package/dist/tools/registry.js +0 -195
  31. package/dist/tools/reload.js +0 -40
  32. package/dist/tools/resources.js +0 -56
  33. package/dist/tools/scripts.js +0 -206
  34. package/dist/tools/services.js +0 -33
  35. package/dist/tools/statistics.js +0 -363
  36. package/dist/tools/system.js +0 -57
  37. package/dist/tools/templates.js +0 -21
  38. package/dist/tools/trace.js +0 -74
  39. package/dist/tools/zha.js +0 -121
  40. package/dist/toolsets.js +0 -356
@@ -1,235 +0,0 @@
1
- import { z } from "zod";
2
- import { ok, err } from "../hass/format.js";
3
- const ENERGY_UNITS = new Set([
4
- "Wh",
5
- "kWh",
6
- "MWh",
7
- "GWh",
8
- "TWh",
9
- "mWh",
10
- "J",
11
- "kJ",
12
- "MJ",
13
- "GJ",
14
- "cal",
15
- "kcal",
16
- "Mcal",
17
- "Gcal",
18
- ]);
19
- const show = (v) => (v === undefined || v === null ? "missing" : String(v));
20
- async function getPrefs(ws) {
21
- try {
22
- return (await ws.command("energy/get_prefs"));
23
- }
24
- catch (e) {
25
- const code = e.code;
26
- if (code === "ERR_NOT_FOUND" || /no prefs/i.test(String(e))) {
27
- return { energy_sources: [], device_consumption: [] };
28
- }
29
- throw e;
30
- }
31
- }
32
- function eligibilityReasons(state, id) {
33
- if (!state)
34
- return [`${id} not found in current states`];
35
- const a = (state.attributes ?? {});
36
- const reasons = [];
37
- if (a.device_class !== "energy") {
38
- reasons.push(`device_class is ${show(a.device_class)} (expected energy)`);
39
- }
40
- if (a.state_class !== "total" && a.state_class !== "total_increasing") {
41
- reasons.push(`state_class is ${show(a.state_class)} (expected total or total_increasing)`);
42
- }
43
- const unit = a.unit_of_measurement;
44
- if (typeof unit !== "string" || !ENERGY_UNITS.has(unit)) {
45
- reasons.push(`unit is ${show(unit)} (expected an energy unit such as kWh)`);
46
- }
47
- return reasons;
48
- }
49
- export function registerEnergyTools(server, ws, client) {
50
- server.tool("get_energy_prefs", "Get the current Energy dashboard preferences (EnergyPreferences) over the WebSocket API: energy_sources (grid/solar/battery/gas/water) and the device_consumption list shown under 'Individual devices'. Returns an empty object if energy has not been configured yet.", {}, async () => {
51
- try {
52
- return ok(await getPrefs(ws));
53
- }
54
- catch (e) {
55
- return err(e);
56
- }
57
- });
58
- server.tool("save_energy_prefs", "Overwrite Energy dashboard preferences via energy/save_prefs (requires an admin token). Each provided key (energy_sources, device_consumption, device_consumption_water) replaces that key server-side; omitted keys are left untouched. Prefer get_energy_prefs first and send back a modified object (read-modify-write). For the common cases use add_energy_devices / remove_energy_devices / set_energy_grid_source / set_energy_solar_source instead.", {
59
- prefs: z
60
- .object({
61
- energy_sources: z.array(z.record(z.unknown())).optional(),
62
- device_consumption: z.array(z.record(z.unknown())).optional(),
63
- device_consumption_water: z.array(z.record(z.unknown())).optional(),
64
- })
65
- .describe("Partial or full EnergyPreferences object to write"),
66
- }, async ({ prefs }) => {
67
- try {
68
- return ok(await ws.command("energy/save_prefs", prefs));
69
- }
70
- catch (e) {
71
- return err(e);
72
- }
73
- });
74
- server.tool("add_energy_devices", "Append entities to the Energy dashboard 'Individual devices' list (device_consumption), deduping by stat_consumption and preserving energy_sources. Optionally warns about entities that are not valid energy statistics (need device_class energy, state_class total/total_increasing and an energy unit) but still adds them. Returns the added/skipped ids, any warnings, and the resulting device_consumption.", {
75
- entity_ids: z
76
- .array(z.string())
77
- .describe("Entity ids to add as device_consumption stats, e.g. ['sensor.fridge_energy']"),
78
- names: z
79
- .array(z.string())
80
- .optional()
81
- .describe("Optional display names, aligned by index with entity_ids"),
82
- }, async ({ entity_ids, names }) => {
83
- try {
84
- const prefs = await getPrefs(ws);
85
- const existing = prefs.device_consumption ?? [];
86
- const present = new Set(existing.map((d) => d.stat_consumption));
87
- let statesById = null;
88
- try {
89
- const states = (await client.fetch("/api/states"));
90
- statesById = new Map(states.map((s) => [s.entity_id, s]));
91
- }
92
- catch {
93
- statesById = null;
94
- }
95
- const warnings = [];
96
- if (statesById) {
97
- for (const id of entity_ids) {
98
- const reasons = eligibilityReasons(statesById.get(id), id);
99
- if (reasons.length)
100
- warnings.push({ entity_id: id, reasons });
101
- }
102
- }
103
- const added = [];
104
- const skipped = [];
105
- const next = [...existing];
106
- entity_ids.forEach((id, i) => {
107
- if (present.has(id)) {
108
- skipped.push(id);
109
- return;
110
- }
111
- present.add(id);
112
- const entry = { stat_consumption: id };
113
- const name = names?.[i];
114
- if (name)
115
- entry.name = name;
116
- next.push(entry);
117
- added.push(id);
118
- });
119
- const updated = (await ws.command("energy/save_prefs", {
120
- device_consumption: next,
121
- }));
122
- return ok({ added, skipped, warnings, device_consumption: updated.device_consumption });
123
- }
124
- catch (e) {
125
- return err(e);
126
- }
127
- });
128
- server.tool("remove_energy_devices", "Remove entities from the Energy dashboard 'Individual devices' list (device_consumption) by matching stat_consumption, preserving energy_sources. Returns the removed ids and the resulting device_consumption.", {
129
- entity_ids: z.array(z.string()).describe("Entity ids to remove from device_consumption"),
130
- }, async ({ entity_ids }) => {
131
- try {
132
- const prefs = await getPrefs(ws);
133
- const remove = new Set(entity_ids);
134
- const existing = prefs.device_consumption ?? [];
135
- const removed = existing
136
- .filter((d) => remove.has(d.stat_consumption))
137
- .map((d) => d.stat_consumption);
138
- const next = existing.filter((d) => !remove.has(d.stat_consumption));
139
- const updated = (await ws.command("energy/save_prefs", {
140
- device_consumption: next,
141
- }));
142
- return ok({ removed, device_consumption: updated.device_consumption });
143
- }
144
- catch (e) {
145
- return err(e);
146
- }
147
- });
148
- server.tool("validate_energy_prefs", "Run Home Assistant's energy/validate against the current preferences and return per-item issues. device_consumption, device_consumption_water and energy_sources issues are correlated with their stat_consumption / source so you can see which entity each issue belongs to. Includes the raw validation result.", {}, async () => {
149
- try {
150
- const prefs = await getPrefs(ws);
151
- const result = (await ws.command("energy/validate"));
152
- const device_consumption = (result.device_consumption ?? [])
153
- .map((issues, i) => ({
154
- stat_consumption: prefs.device_consumption?.[i]?.stat_consumption ?? null,
155
- issues,
156
- }))
157
- .filter((d) => Array.isArray(d.issues) && d.issues.length > 0);
158
- const device_consumption_water = (result.device_consumption_water ?? [])
159
- .map((issues, i) => ({
160
- stat_consumption: prefs.device_consumption_water?.[i]?.stat_consumption ?? null,
161
- issues,
162
- }))
163
- .filter((d) => Array.isArray(d.issues) && d.issues.length > 0);
164
- const energy_sources = (result.energy_sources ?? [])
165
- .map((issues, i) => ({ source: prefs.energy_sources?.[i] ?? null, issues }))
166
- .filter((s) => Array.isArray(s.issues) && s.issues.length > 0);
167
- return ok({ device_consumption, device_consumption_water, energy_sources, raw: result });
168
- }
169
- catch (e) {
170
- return err(e);
171
- }
172
- });
173
- server.tool("set_energy_grid_source", "Set the single grid source of the Energy dashboard (unified model: import/export stats plus optional cost/price stats), merging onto the existing grid source (unspecified fields are kept) and preserving all other energy_sources and device_consumption. Adds a grid source if none exists; cost_adjustment_day defaults to 0. To clear a field, use save_energy_prefs.", {
174
- stat_energy_from: z
175
- .string()
176
- .optional()
177
- .describe("Statistic for energy imported from the grid"),
178
- stat_energy_to: z.string().optional().describe("Statistic for energy returned to the grid"),
179
- stat_cost: z.string().optional().describe("Statistic tracking import cost"),
180
- entity_energy_price: z.string().optional().describe("Entity providing the import price"),
181
- number_energy_price: z.number().optional().describe("Fixed import price per unit"),
182
- stat_compensation: z.string().optional().describe("Statistic tracking export compensation"),
183
- entity_energy_price_export: z
184
- .string()
185
- .optional()
186
- .describe("Entity providing the export price"),
187
- number_energy_price_export: z.number().optional().describe("Fixed export price per unit"),
188
- cost_adjustment_day: z.number().optional().describe("Daily cost adjustment (default 0)"),
189
- stat_rate: z.string().optional().describe("Statistic tracking the current grid energy rate"),
190
- power_config: z
191
- .object({
192
- stat_rate: z.string().optional(),
193
- stat_rate_inverted: z.string().optional(),
194
- stat_rate_from: z.string().optional(),
195
- stat_rate_to: z.string().optional(),
196
- })
197
- .optional()
198
- .describe("Live power-flow config; provide exactly one method"),
199
- }, async (args) => {
200
- try {
201
- const prefs = await getPrefs(ws);
202
- const sources = prefs.energy_sources ?? [];
203
- const idx = sources.findIndex((s) => s.type === "grid");
204
- const grid = { ...(idx >= 0 ? sources[idx] : {}), ...args, type: "grid" };
205
- if (grid.cost_adjustment_day === undefined || grid.cost_adjustment_day === null) {
206
- grid.cost_adjustment_day = 0;
207
- }
208
- const next = idx >= 0 ? sources.map((s, i) => (i === idx ? grid : s)) : [...sources, grid];
209
- return ok(await ws.command("energy/save_prefs", { energy_sources: next }));
210
- }
211
- catch (e) {
212
- return err(e);
213
- }
214
- });
215
- server.tool("set_energy_solar_source", "Add or update a solar production source on the Energy dashboard, upserting by stat_energy_from (unspecified fields on an existing source are kept) and preserving all other energy_sources and device_consumption.", {
216
- stat_energy_from: z.string().describe("Statistic for solar energy production"),
217
- config_entry_solar_forecast: z
218
- .array(z.string())
219
- .optional()
220
- .describe("Config entry ids providing a solar production forecast"),
221
- stat_rate: z.string().optional().describe("Statistic tracking the current solar energy rate"),
222
- }, async (args) => {
223
- try {
224
- const prefs = await getPrefs(ws);
225
- const sources = prefs.energy_sources ?? [];
226
- const idx = sources.findIndex((s) => s.type === "solar" && s.stat_energy_from === args.stat_energy_from);
227
- const solar = { ...(idx >= 0 ? sources[idx] : {}), ...args, type: "solar" };
228
- const next = idx >= 0 ? sources.map((s, i) => (i === idx ? solar : s)) : [...sources, solar];
229
- return ok(await ws.command("energy/save_prefs", { energy_sources: next }));
230
- }
231
- catch (e) {
232
- return err(e);
233
- }
234
- });
235
- }
@@ -1,57 +0,0 @@
1
- import { z } from "zod";
2
- import { ok, err, summarizeState, domainOf } from "../hass/format.js";
3
- export function registerEntityTools(server, client) {
4
- server.tool("list_entities", "List entities with their current state as a compact summary (entity_id, state, friendly_name, device_class, unit). Use get_entity for full attributes. Optionally filter by domain and/or a search substring matched against entity_id and friendly_name.", {
5
- domain: z
6
- .string()
7
- .optional()
8
- .describe("Only entities in this domain, e.g. 'light', 'sensor', 'binary_sensor'"),
9
- search: z
10
- .string()
11
- .optional()
12
- .describe("Case-insensitive substring matched against entity_id and friendly_name"),
13
- }, async ({ domain, search }) => {
14
- try {
15
- const states = (await client.fetch("/api/states"));
16
- let rows = states;
17
- if (domain)
18
- rows = rows.filter((s) => domainOf(s.entity_id) === domain);
19
- if (search) {
20
- const q = search.toLowerCase();
21
- rows = rows.filter((s) => s.entity_id.toLowerCase().includes(q) ||
22
- String(s.attributes?.friendly_name ?? "")
23
- .toLowerCase()
24
- .includes(q));
25
- }
26
- return ok({ count: rows.length, entities: rows.map(summarizeState) });
27
- }
28
- catch (e) {
29
- return err(e);
30
- }
31
- });
32
- server.tool("get_entity", "Get the full state object for a single entity, including all attributes, last_changed and last_updated.", { entity_id: z.string().describe("Entity ID, e.g. 'light.kitchen'") }, async ({ entity_id }) => {
33
- try {
34
- return ok(await client.fetch(`/api/states/${encodeURIComponent(entity_id)}`));
35
- }
36
- catch (e) {
37
- return err(e);
38
- }
39
- });
40
- server.tool("list_domains", "List the distinct entity domains present on this instance with a count of entities in each. Useful for discovering what kinds of entities exist before drilling in with list_entities.", {}, async () => {
41
- try {
42
- const states = (await client.fetch("/api/states"));
43
- const counts = new Map();
44
- for (const s of states) {
45
- const d = domainOf(s.entity_id);
46
- counts.set(d, (counts.get(d) ?? 0) + 1);
47
- }
48
- const domains = [...counts.entries()]
49
- .map(([domain, count]) => ({ domain, count }))
50
- .sort((a, b) => a.domain.localeCompare(b.domain));
51
- return ok({ count: domains.length, domains });
52
- }
53
- catch (e) {
54
- return err(e);
55
- }
56
- });
57
- }
@@ -1,52 +0,0 @@
1
- import { z } from "zod";
2
- import { ok, err } from "../hass/format.js";
3
- function summarize(r) {
4
- return {
5
- id: r.id,
6
- name: r.name,
7
- full_name: r.full_name,
8
- category: r.category,
9
- installed_version: r.installed_version,
10
- available_version: r.available_version,
11
- pending_upgrade: r.pending_upgrade,
12
- local_path: r.local_path,
13
- file_name: r.file_name,
14
- domain: r.domain,
15
- };
16
- }
17
- export function registerHacsTools(server, ws) {
18
- server.tool("list_hacs_repositories", "List HACS repositories (hacs/repositories/list) — the frontend plugins, integrations and themes HACS manages. Defaults to installed-only, trimmed to the useful fields (id, name, full_name, category, versions, local_path, file_name, domain). Use the returned id with remove_hacs_repository. For a frontend plugin, local_path/file_name tell you which /hacsfiles/… Lovelace resource points at it (see list_lovelace_resources), so you can delete the dangling resource after removing the plugin.", {
19
- installed_only: z
20
- .boolean()
21
- .optional()
22
- .describe("Only repositories that are installed. Default true; set false to include the whole known store (large)."),
23
- category: z
24
- .string()
25
- .optional()
26
- .describe("Filter by HACS category, e.g. 'integration', 'plugin', 'theme'. Omit for all categories."),
27
- }, async ({ installed_only, category }) => {
28
- try {
29
- const payload = category ? { categories: [category] } : {};
30
- const repos = (await ws.command("hacs/repositories/list", payload));
31
- const filtered = installed_only === false ? repos : repos.filter((r) => r.installed);
32
- const repositories = filtered.map(summarize);
33
- return ok({ count: repositories.length, repositories });
34
- }
35
- catch (e) {
36
- return err(e);
37
- }
38
- });
39
- server.tool("remove_hacs_repository", "Uninstall a HACS repository by id (hacs/repository/remove) — deletes its downloaded files from the config (for a plugin, the JS under www/community/…) and unregisters it from HACS. Requires an admin token. When HACS manages resources (storage mode) it also removes the plugin's /hacsfiles/… Lovelace resource for you; verify with list_lovelace_resources and use delete_lovelace_resource only if one is left behind. Get the id from list_hacs_repositories. Removing an installed integration you still reference in YAML will break that config, so confirm nothing uses it first.", {
40
- repository_id: z
41
- .string()
42
- .describe("The repository id from list_hacs_repositories (a numeric string, e.g. '172733314')."),
43
- }, async ({ repository_id }) => {
44
- try {
45
- await ws.command("hacs/repository/remove", { repository: repository_id });
46
- return ok({ repository_id, removed: true });
47
- }
48
- catch (e) {
49
- return err(e);
50
- }
51
- });
52
- }
@@ -1,98 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { z } from "zod";
3
- import { ok, err } from "../hass/format.js";
4
- const HELPER_DOMAINS = [
5
- "input_boolean",
6
- "input_number",
7
- "input_text",
8
- "input_select",
9
- "input_datetime",
10
- "input_button",
11
- "counter",
12
- "timer",
13
- "schedule",
14
- "zone",
15
- "person",
16
- "tag",
17
- ];
18
- const FIELDS = [
19
- "input_boolean: name*, initial (bool), icon",
20
- "input_button: name*, icon",
21
- "input_text: name*, min (0-255, default 0), max (1-255, default 100), initial, pattern (regex), mode ('text'|'password'), unit_of_measurement, icon",
22
- "input_number: name*, min*, max* (min < max), initial, step (default 1), mode ('slider'|'box'), unit_of_measurement, device_class, icon",
23
- "input_select: name*, options* (non-empty list of unique strings), initial (one of options), icon",
24
- "input_datetime: name*, has_date, has_time (default false; at least one must be true), initial (string), icon",
25
- "counter: name*, initial (int, default 0), minimum, maximum (int or null), step (positive int, default 1), restore (default true), icon",
26
- "timer: name*, duration ('HH:MM:SS' or seconds, default 0), restore (default false), icon",
27
- "schedule: name*, icon, and monday..sunday: a list of {from: 'HH:MM[:SS]', to: 'HH:MM[:SS]' ('24:00:00' allowed), data?: {key: bool|string|number}} ranges that must not overlap",
28
- "zone: name*, latitude*, longitude*, radius (metres, default 100), passive (default false), icon",
29
- "person: name*, user_id (HA user id or null), device_trackers (list of device_tracker.* entity ids), picture",
30
- "tag: tag_id (any unique string, e.g. the NFC tag's id; a UUID is generated if omitted), name, description, last_scanned (ISO datetime), device_id",
31
- ]
32
- .map((line) => `- ${line}`)
33
- .join("\n");
34
- const NOT_COVERED = "Config-entry based helpers (template, group, utility_meter, derivative, threshold, min_max, ...) are created through config flows and are not covered by these tools.";
35
- const domainSchema = z
36
- .enum(HELPER_DOMAINS)
37
- .describe("Helper domain: input_boolean, input_number, input_text, input_select, input_datetime, input_button, counter, timer, schedule, zone, person or tag");
38
- const idKey = (domain) => `${domain}_id`;
39
- function fieldsOf(config) {
40
- const { id: _id, type: _type, ...fields } = config;
41
- return fields;
42
- }
43
- export function registerHelperTools(server, ws) {
44
- server.tool("list_helpers", `List the UI-managed (storage) helpers of one domain via the WebSocket API (<domain>/list, e.g. input_boolean/list). Each item has an 'id' — the storage id that update_helper and delete_helper take; it is NOT the entity_id, which Home Assistant derives from the name — plus its config fields. Helpers defined in YAML are not listed and cannot be edited through this API (for 'person' the result is {storage: [...], config: [...]} where 'config' holds the read-only YAML persons). ${NOT_COVERED}`, { domain: domainSchema }, async ({ domain }) => {
45
- try {
46
- return ok(await ws.command(`${domain}/list`));
47
- }
48
- catch (e) {
49
- return err(e);
50
- }
51
- });
52
- server.tool("create_helper", `Create a UI-managed helper via the WebSocket API (<domain>/create, requires an admin token). Home Assistant validates the config, stores it and creates the entity automatically; the item id is generated from the name (slugified, suffixed _2, _3 on collision) and returned with the stored config. Config authoring only — it does not control any device. Config fields per domain (* = required, Home Assistant validates the rest):\n${FIELDS}\n${NOT_COVERED}`, {
53
- domain: domainSchema,
54
- config: z
55
- .record(z.unknown())
56
- .describe("Helper config for the chosen domain, e.g. {name: 'Vacation mode', icon: 'mdi:beach'} for input_boolean. 'id' and 'type' keys are ignored."),
57
- }, async ({ domain, config }) => {
58
- try {
59
- const payload = fieldsOf(config);
60
- if (domain === "tag" && payload.tag_id === undefined)
61
- payload.tag_id = randomUUID();
62
- return ok(await ws.command(`${domain}/create`, payload));
63
- }
64
- catch (e) {
65
- return err(e);
66
- }
67
- });
68
- server.tool("update_helper", `Update a UI-managed helper via the WebSocket API (<domain>/update, requires an admin token). The item id cannot change. Update semantics differ by domain: input_*, counter, timer and schedule REPLACE the stored config (required fields must be sent again and omitted optional fields revert to their defaults), so call list_helpers first and send back the full modified config. zone and tag MERGE: only the fields you send change. person merges too, EXCEPT device_trackers, which is reset to [] when omitted — always resend it. Returns the updated item. Config fields per domain (* = required on create):\n${FIELDS}`, {
69
- domain: domainSchema,
70
- id: z
71
- .string()
72
- .describe("The helper's storage id — the 'id' field from list_helpers, not its entity_id"),
73
- config: z
74
- .record(z.unknown())
75
- .describe("Helper config (see the field list; full config for input_*/counter/timer/schedule, changed fields for zone/tag/person). 'id' and 'type' keys are ignored."),
76
- }, async ({ domain, id, config }) => {
77
- try {
78
- return ok(await ws.command(`${domain}/update`, { ...fieldsOf(config), [idKey(domain)]: id }));
79
- }
80
- catch (e) {
81
- return err(e);
82
- }
83
- });
84
- server.tool("delete_helper", "Delete a UI-managed helper via the WebSocket API (<domain>/delete, requires an admin token). Its entity is removed from the entity registry too; automations, scripts and dashboards that reference it are NOT updated. Only helpers listed by list_helpers can be deleted — YAML-defined ones cannot.", {
85
- domain: domainSchema,
86
- id: z
87
- .string()
88
- .describe("The helper's storage id — the 'id' field from list_helpers, not its entity_id"),
89
- }, async ({ domain, id }) => {
90
- try {
91
- await ws.command(`${domain}/delete`, { [idKey(domain)]: id });
92
- return ok({ domain, id, deleted: true });
93
- }
94
- catch (e) {
95
- return err(e);
96
- }
97
- });
98
- }
@@ -1,57 +0,0 @@
1
- import { z } from "zod";
2
- import { buildQS, ok, err } from "../hass/format.js";
3
- export function registerHistoryTools(server, client) {
4
- server.tool("get_history", "Get state history for one or more entities (GET /api/history/period). Returns arrays of past state changes — useful for understanding how an entity behaves before writing triggers and conditions.", {
5
- entity_id: z
6
- .string()
7
- .describe("Entity ID, or a comma-separated list of entity IDs, to fetch history for"),
8
- start: z
9
- .string()
10
- .optional()
11
- .describe("ISO 8601 start timestamp, e.g. '2026-06-01T00:00:00'. Defaults to 1 day ago on the HA side."),
12
- end: z.string().optional().describe("ISO 8601 end timestamp"),
13
- minimal_response: z
14
- .boolean()
15
- .optional()
16
- .describe("Return only last_changed and state for most entries (smaller payload)"),
17
- significant_changes_only: z
18
- .boolean()
19
- .optional()
20
- .describe("Only return significant state changes"),
21
- no_attributes: z.boolean().optional().describe("Omit attributes from the response"),
22
- }, async ({ entity_id, start, end, minimal_response, significant_changes_only, no_attributes, }) => {
23
- try {
24
- const base = start
25
- ? `/api/history/period/${encodeURIComponent(start)}`
26
- : "/api/history/period";
27
- const qs = buildQS({
28
- filter_entity_id: entity_id,
29
- end_time: end,
30
- minimal_response: minimal_response ? true : undefined,
31
- significant_changes_only: significant_changes_only ? true : undefined,
32
- no_attributes: no_attributes ? true : undefined,
33
- });
34
- return ok(await client.fetch(`${base}${qs}`));
35
- }
36
- catch (e) {
37
- return err(e);
38
- }
39
- });
40
- server.tool("get_logbook", "Get logbook entries — human-readable events such as state changes and automation triggers (GET /api/logbook). Useful for seeing what happened and when.", {
41
- entity_id: z.string().optional().describe("Limit to a single entity"),
42
- start: z
43
- .string()
44
- .optional()
45
- .describe("ISO 8601 start timestamp. Defaults to 1 day ago on the HA side."),
46
- end: z.string().optional().describe("ISO 8601 end timestamp"),
47
- }, async ({ entity_id, start, end }) => {
48
- try {
49
- const base = start ? `/api/logbook/${encodeURIComponent(start)}` : "/api/logbook";
50
- const qs = buildQS({ entity: entity_id, end_time: end });
51
- return ok(await client.fetch(`${base}${qs}`));
52
- }
53
- catch (e) {
54
- return err(e);
55
- }
56
- });
57
- }