forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools_config_automations.py
More file actions
670 lines (577 loc) · 27.7 KB
/
Copy pathtools_config_automations.py
File metadata and controls
670 lines (577 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
"""
Configuration management tools for Home Assistant automations.
This module provides tools for retrieving, creating, updating, and removing
Home Assistant automation configurations.
"""
import logging
from typing import Annotated, Any, cast
from fastmcp.exceptions import ToolError
from pydantic import Field
from ..errors import (
create_config_error,
create_resource_not_found_error,
create_validation_error,
)
from .best_practice_checker import (
check_automation_config as _check_best_practices,
)
from .best_practice_checker import (
get_skill_prefix as _get_skill_prefix,
)
from .helpers import exception_to_structured_error, log_tool_usage, raise_tool_error
from .util_helpers import (
apply_entity_category,
coerce_bool_param,
fetch_entity_category,
parse_json_param,
wait_for_entity_registered,
wait_for_entity_removed,
)
logger = logging.getLogger(__name__)
def _normalize_automation_config(
config: Any,
parent_key: str | None = None,
in_choose_or_if: bool = False,
is_root: bool = True,
) -> Any:
"""
Recursively normalize automation config field names to HA API format.
Home Assistant accepts both singular ('trigger', 'action', 'condition')
and plural ('triggers', 'actions', 'conditions') field names in YAML,
but the API expects singular forms at the root level.
IMPORTANT: 'triggers' → 'trigger' and 'actions' → 'action' normalization
is ONLY applied at the root level. Deeper in the tree these keys are either
invalid or semantically different, and normalizing them can produce keys
that Home Assistant rejects (e.g., 'action' inside a delay object).
IMPORTANT: Inside 'choose' and 'if' action blocks, the 'conditions' key
(plural) is required by the HA schema and should NOT be normalized to
'condition' (singular).
IMPORTANT: Inside compound condition blocks ('or', 'and', 'not'), the
'conditions' key (plural) is required and should NOT be normalized to
'condition' (singular).
Args:
config: Automation configuration (dict, list, or primitive)
parent_key: The parent dictionary key (for context tracking)
in_choose_or_if: Whether we're inside a choose/if option that requires
'conditions' (plural) to remain unchanged
is_root: Whether this is the root-level automation config dict.
Only root level gets 'triggers'→'trigger' and
'actions'→'action' normalization.
Returns:
Normalized configuration with singular field names at root level,
but preserving 'conditions' (plural) inside choose/if blocks and
compound condition blocks (or/and/not)
"""
# Handle lists - recursively process each item
if isinstance(config, list):
# If parent is 'choose' or 'if', items are options that need 'conditions' preserved
is_option_list = parent_key in ("choose", "if")
return [
_normalize_automation_config(
item, parent_key, is_option_list, is_root=False
)
for item in config
]
# Handle primitives (strings, numbers, etc.)
if not isinstance(config, dict):
return config
# Process dictionary
normalized = config.copy()
# Check if this dict is a compound condition block (or/and/not)
# that needs its nested 'conditions' key preserved
is_compound_condition_block = normalized.get("condition") in ("or", "and", "not")
# Build field mappings based on context
field_mappings: dict[str, str] = {}
# 'triggers' → 'trigger' and 'actions' → 'action' ONLY at root level.
# Deeper in the tree these keys are invalid and normalizing them produces
# keys HA rejects (e.g., 'action' inside a delay object — see issue #498).
if is_root:
field_mappings["triggers"] = "trigger"
field_mappings["actions"] = "action"
# 'sequences' → 'sequence' is safe at any level (only meaningful in choose options)
field_mappings["sequences"] = "sequence"
# Only add 'conditions' mapping if NOT inside a choose/if option
# AND NOT a compound condition block (or/and/not)
if not in_choose_or_if and not is_compound_condition_block:
field_mappings["conditions"] = "condition"
# Apply field mapping to current level
for plural, singular in field_mappings.items():
if plural in normalized and singular not in normalized:
normalized[singular] = normalized.pop(plural)
elif plural in normalized and singular in normalized:
# Both exist - prefer singular, remove plural
del normalized[plural]
# Recursively process all values in the dictionary
for key, value in normalized.items():
normalized[key] = _normalize_automation_config(value, key, is_root=False)
return normalized
def _normalize_trigger_keys(triggers: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""
Normalize trigger objects for round-trip compatibility.
Home Assistant GET API returns triggers with 'trigger' key for the platform type,
but the SET API expects 'platform' key. This function converts between formats.
Args:
triggers: List of trigger configuration dicts
Returns:
List of triggers with 'platform' key instead of 'trigger' key
"""
normalized_triggers = []
for trigger in triggers:
normalized_trigger = trigger.copy()
# Convert 'trigger' key to 'platform' if present and 'platform' is not
if "trigger" in normalized_trigger and "platform" not in normalized_trigger:
normalized_trigger["platform"] = normalized_trigger.pop("trigger")
normalized_triggers.append(normalized_trigger)
return normalized_triggers
def _normalize_config_for_roundtrip(config: dict[str, Any]) -> dict[str, Any]:
"""
Normalize automation config from GET response for direct use in SET.
This ensures a config retrieved via ha_config_get_automation can be
directly passed to ha_config_set_automation without modification.
Transformations:
1. Field names: triggers -> trigger, actions -> action, conditions -> condition
2. Trigger keys: trigger -> platform (inside each trigger object)
Args:
config: Raw automation configuration from HA API
Returns:
Normalized configuration compatible with SET API
"""
# First normalize field names (plural -> singular)
normalized = _normalize_automation_config(config)
# Then normalize trigger keys (trigger -> platform)
if "trigger" in normalized and isinstance(normalized["trigger"], list):
normalized["trigger"] = _normalize_trigger_keys(normalized["trigger"])
return cast(dict[str, Any], normalized)
def _strip_empty_automation_fields(config: dict[str, Any]) -> dict[str, Any]:
"""
Strip empty trigger/action/condition arrays from automation config.
Blueprint-based automations should not have trigger/action/condition fields
since these come from the blueprint itself. If empty arrays are present,
they override the blueprint's configuration and break the automation.
Args:
config: Automation configuration dict
Returns:
Configuration with empty trigger/action/condition arrays removed
"""
cleaned = config.copy()
# Remove empty arrays for blueprint automations
for field in ["trigger", "action", "condition"]:
if field in cleaned and cleaned[field] == []:
del cleaned[field]
return cleaned
def register_config_automation_tools(mcp: Any, client: Any, **kwargs: Any) -> None:
"""Register Home Assistant automation configuration tools."""
async def _resolve_automation_entity_id(identifier: str) -> str | None:
"""Resolve an automation identifier to its entity_id.
If identifier is already an entity_id (starts with "automation."),
returns it directly. Otherwise, searches states to find the entity
whose unique_id matches the identifier.
"""
if identifier.startswith("automation."):
return identifier
try:
states = await client.get_states()
for state in states:
if (
state.get("entity_id", "").startswith("automation.")
and state.get("attributes", {}).get("id") == identifier
):
return str(state["entity_id"])
except Exception as e:
logger.debug(f"Failed to resolve entity_id for automation {identifier}: {e}")
return None
@mcp.tool(
tags={"Automations"},
annotations={
"idempotentHint": True,
"readOnlyHint": True,
"title": "Get Automation Config"
}
)
@log_tool_usage
async def ha_config_get_automation(
identifier: Annotated[
str,
Field(
description="Automation entity_id (e.g., 'automation.morning_routine') or unique_id"
),
],
) -> dict[str, Any]:
"""
Retrieve Home Assistant automation configuration.
Returns the complete configuration including triggers, conditions, actions, and mode settings.
EXAMPLES:
- Get automation: ha_config_get_automation("automation.morning_routine")
- Get by unique_id: ha_config_get_automation("my_unique_automation_id")
For comprehensive automation documentation, use ha_get_skill_home_assistant_best_practices.
"""
try:
config_result = await client.get_automation_config(identifier)
# Normalize config for round-trip compatibility (GET → SET)
normalized_config = _normalize_config_for_roundtrip(config_result)
# Resolve entity_id and fetch category from entity registry
entity_id = await _resolve_automation_entity_id(identifier)
if entity_id:
cat_id = await fetch_entity_category(client, entity_id, "automation")
if cat_id:
normalized_config["category"] = cat_id
return {
"success": True,
"action": "get",
"identifier": identifier,
"config": normalized_config,
}
except Exception as e:
# Handle 404 errors gracefully (often used to verify deletion)
error_str = str(e)
if (
"404" in error_str
or "not found" in error_str.lower()
or "entity not found" in error_str.lower()
):
logger.debug(
f"Automation {identifier} not found (expected for deletion verification)"
)
error_response = create_resource_not_found_error(
"Automation",
identifier,
details=f"Automation '{identifier}' does not exist in Home Assistant",
)
error_response["action"] = "get"
error_response["reason"] = "not_found"
raise_tool_error(error_response)
logger.error(f"Error getting automation: {e}")
exception_to_structured_error(
e,
context={"identifier": identifier, "action": "get"},
suggestions=[
"Verify automation exists using ha_search_entities(domain_filter='automation')",
"Check Home Assistant connection",
"Use ha_get_skill_home_assistant_best_practices for help",
],
)
@mcp.tool(
tags={"Automations"},
annotations={
"destructiveHint": True,
"title": "Create or Update Automation"
}
)
@log_tool_usage
async def ha_config_set_automation(
config: Annotated[
str | dict[str, Any],
Field(
description="Complete automation configuration with required fields: 'alias', 'trigger', 'action'. Optional: 'description', 'condition', 'mode', 'max', 'initial_state', 'variables'"
),
],
identifier: Annotated[
str | None,
Field(
description="Automation entity_id or unique_id for updates. Omit to create new automation with generated unique_id.",
default=None,
),
] = None,
category: Annotated[
str | None,
Field(
description="Category ID to assign to this automation. Use ha_config_get_category(scope='automation') to list available categories, or ha_config_set_category() to create one.",
default=None,
),
] = None,
wait: Annotated[
bool | str,
Field(
description="Wait for automation to be queryable before returning. Default: True. Set to False for bulk operations.",
default=True,
),
] = True,
) -> dict[str, Any]:
"""
Create or update a Home Assistant automation.
Creates a new automation (if identifier omitted) or updates existing automation with provided configuration.
AUTOMATION TYPES:
1. Regular Automations - Define triggers and actions directly
2. Blueprint Automations - Use pre-built templates with customizable inputs
REQUIRED FIELDS (Regular Automations):
- alias: Human-readable automation name
- trigger: List of trigger conditions (time, state, event, etc.)
- action: List of actions to execute
REQUIRED FIELDS (Blueprint Automations):
- alias: Human-readable automation name
- use_blueprint: Blueprint configuration
- path: Blueprint file path (e.g., "motion_light.yaml")
- input: Dictionary of input values for the blueprint
OPTIONAL CONFIG FIELDS (Regular Automations):
- description: Detailed description of the user's intent (RECOMMENDED: helps safely modify implementation later)
- category: Category ID for organization (use ha_config_get_category to list, ha_config_set_category to create)
- condition: Additional conditions that must be met
- mode: 'single' (default), 'restart', 'queued', 'parallel'
- max: Maximum concurrent executions (for queued/parallel modes)
- initial_state: Whether automation starts enabled (true/false)
- variables: Variables for use in automation
BASIC EXAMPLES:
Simple time-based automation:
ha_config_set_automation({
"alias": "Morning Lights",
"description": "Turn on bedroom lights at 7 AM to help wake up",
"trigger": [{"platform": "time", "at": "07:00:00"}],
"action": [{"service": "light.turn_on", "target": {"area_id": "bedroom"}}]
})
Motion-activated lighting with condition:
ha_config_set_automation({
"alias": "Motion Light",
"trigger": [{"platform": "state", "entity_id": "binary_sensor.motion", "to": "on"}],
"condition": [{"condition": "sun", "after": "sunset"}],
"action": [
{"service": "light.turn_on", "target": {"entity_id": "light.hallway"}},
{"delay": {"minutes": 5}},
{"service": "light.turn_off", "target": {"entity_id": "light.hallway"}}
],
"mode": "restart"
})
Update existing automation:
ha_config_set_automation(
identifier="automation.morning_routine",
config={
"alias": "Updated Morning Routine",
"trigger": [{"platform": "time", "at": "06:30:00"}],
"action": [
{"service": "light.turn_on", "target": {"area_id": "bedroom"}},
{"service": "climate.set_temperature", "target": {"entity_id": "climate.bedroom"}, "data": {"temperature": 22}}
]
}
)
BLUEPRINT AUTOMATION EXAMPLES:
Create automation from blueprint:
ha_config_set_automation({
"alias": "Motion Light Kitchen",
"use_blueprint": {
"path": "homeassistant/motion_light.yaml",
"input": {
"motion_entity": "binary_sensor.kitchen_motion",
"light_target": {"entity_id": "light.kitchen"},
"no_motion_wait": 120
}
}
})
Update blueprint automation inputs:
ha_config_set_automation(
identifier="automation.motion_light_kitchen",
config={
"alias": "Motion Light Kitchen",
"use_blueprint": {
"path": "homeassistant/motion_light.yaml",
"input": {
"motion_entity": "binary_sensor.kitchen_motion",
"light_target": {"entity_id": "light.kitchen"},
"no_motion_wait": 300
}
}
}
})
PREFER NATIVE SOLUTIONS OVER TEMPLATES:
Before using template triggers/conditions/actions, check if a native option exists:
- Use `condition: state` with `state: [list]` instead of template for multiple states
- Use `condition: state` with `attribute:` instead of template for attribute checks
- Use `condition: numeric_state` instead of template for number comparisons
- Use `wait_for_trigger` instead of `wait_template` when waiting for state changes
- Use `choose` action instead of template-based service names
TRIGGER TYPES: time, time_pattern, sun, state, numeric_state, event, device, zone, template, and more
CONDITION TYPES: state, numeric_state, time, sun, template, device, zone, and more
ACTION TYPES: service calls, delays, wait_for_trigger, wait_template, if/then/else, choose, repeat, parallel
For comprehensive automation documentation with all trigger/condition/action types and advanced examples:
- Use: ha_get_skill_home_assistant_best_practices
- Or visit: https://www.home-assistant.io/docs/automation/
TROUBLESHOOTING:
- Use ha_get_state() to verify entity_ids exist
- Use ha_search_entities() to find correct entity_ids
- Use ha_eval_template() to test Jinja2 templates before using in automations
- Use ha_search_entities(domain_filter='automation') to find existing automations
"""
bp_warnings: list[str] = []
try:
# Parse JSON config if provided as string
try:
parsed_config = parse_json_param(config, "config")
except ValueError as e:
raise_tool_error(create_validation_error(
f"Invalid config parameter: {e}",
parameter="config",
invalid_json=True,
))
# Ensure config is a dict
if parsed_config is None or not isinstance(parsed_config, dict):
raise_tool_error(create_validation_error(
"Config parameter must be a JSON object",
parameter="config",
details=f"Received type: {type(parsed_config).__name__}",
))
config_dict = cast(dict[str, Any], parsed_config)
# Extract category before sending to HA REST API (which rejects unknown keys).
# Parameter takes precedence over config dict value.
config_category = config_dict.pop("category", None)
effective_category = category if category is not None else config_category
# Normalize field names (triggers -> trigger, actions -> action, etc.)
config_dict = _normalize_automation_config(config_dict)
# Validate required fields based on automation type
# Blueprint automations only need alias, regular automations need trigger and action
if "use_blueprint" in config_dict:
required_fields = ["alias"]
# Strip empty trigger/action/condition arrays that would override blueprint
config_dict = _strip_empty_automation_fields(config_dict)
else:
required_fields = ["alias", "trigger", "action"]
missing_fields = [f for f in required_fields if f not in config_dict]
if missing_fields:
raise_tool_error(create_config_error(
f"Missing required fields: {', '.join(missing_fields)}",
identifier=identifier,
missing_fields=missing_fields,
))
# Prevent duplicate creation when config contains an existing automation id
if identifier is None and "id" in config_dict:
existing_id = config_dict["id"]
raise_tool_error(create_validation_error(
f"Config contains 'id' field ('{existing_id}') but no identifier was provided. "
"This would create a duplicate automation instead of updating the existing one.",
parameter="identifier",
details=f"To update, pass identifier='{existing_id}' (or the automation's entity_id). "
"To create a genuinely new automation, remove the 'id' field from the config.",
))
# Pre-check for best-practice issues (used for both success
# warnings and error enrichment if the API call fails).
# Pre-check for best-practice issues.
bp_warnings = _check_best_practices(
config_dict, skill_prefix=_get_skill_prefix()
)
result = await client.upsert_automation_config(config_dict, identifier)
# If the client could not verify the entity was registered, warn but don't hard-fail.
# The automation may have been created but not yet visible (slow hardware, reload needed).
if result.get("entity_not_verified"):
result["warning"] = (
"Automation was submitted to Home Assistant but the entity was not found "
"after polling. The automation may still have been created — check Home "
"Assistant logs and try reloading automations. Common causes: "
"automations.yaml vs automation.yaml filename mismatch, invalid config "
"that HA accepted but failed to load, or slow hardware."
)
result.pop("entity_not_verified", None)
# Wait for automation to be queryable
wait_bool = coerce_bool_param(wait, "wait", default=True)
entity_id = result.get("entity_id")
# On updates, entity_id may not be in the result — derive from identifier
if not entity_id and identifier and identifier.startswith("automation."):
entity_id = identifier
if wait_bool and entity_id:
try:
registered = await wait_for_entity_registered(client, entity_id)
if not registered:
result["warning"] = f"Automation created but {entity_id} not yet queryable. It may take a moment to become available."
except Exception as e:
result["warning"] = f"Automation created but verification failed: {e}"
# Apply category to entity registry if provided
if effective_category and entity_id:
await apply_entity_category(
client, entity_id, effective_category, "automation", result, "automation"
)
if bp_warnings:
result["best_practice_warnings"] = bp_warnings
return {
"success": True,
**result,
}
except ToolError:
raise
except Exception as e:
logger.error(f"Error upserting automation: {e}")
suggestions = [
"Check automation configuration format",
"Ensure required fields: alias, trigger, action",
"Use entity_id format: automation.morning_routine or unique_id",
"Use ha_search_entities(domain_filter='automation') to find automations",
"Use ha_get_skill_home_assistant_best_practices for help",
]
if bp_warnings:
suggestions.append(
"Config had best-practice issues that may be related: "
+ "; ".join(bp_warnings)
)
exception_to_structured_error(
e,
context={"identifier": identifier},
suggestions=suggestions,
)
@mcp.tool(
tags={"Automations"},
annotations={
"destructiveHint": True,
"idempotentHint": True,
"title": "Remove Automation"
}
)
@log_tool_usage
async def ha_config_remove_automation(
identifier: Annotated[
str,
Field(
description="Automation entity_id (e.g., 'automation.old_automation') or unique_id to delete"
),
],
wait: Annotated[
bool | str,
Field(
description="Wait for automation to be fully removed before returning. Default: True.",
default=True,
),
] = True,
) -> dict[str, Any]:
"""
Delete a Home Assistant automation.
EXAMPLES:
- Delete automation: ha_config_remove_automation("automation.old_automation")
- Delete by unique_id: ha_config_remove_automation("my_unique_id")
**WARNING:** Deleting an automation removes it permanently from your Home Assistant configuration.
"""
try:
# Resolve entity_id for wait verification (identifier may be a unique_id)
entity_id_for_wait = await _resolve_automation_entity_id(identifier)
if not entity_id_for_wait:
logger.warning(
f"Could not resolve unique_id '{identifier}' to entity_id — wait verification will be skipped"
)
result = await client.delete_automation_config(identifier)
# Wait for entity to be removed
wait_bool = coerce_bool_param(wait, "wait", default=True)
if wait_bool and entity_id_for_wait:
try:
removed = await wait_for_entity_removed(client, entity_id_for_wait)
if not removed:
result["warning"] = f"Deletion confirmed by API but {entity_id_for_wait} may still appear briefly."
except Exception as e:
result["warning"] = f"Deletion confirmed but removal verification failed: {e}"
return {"success": True, "action": "delete", **result}
except Exception as e:
logger.error(f"Error deleting automation: {e}")
error_str = str(e).lower()
if "404" in error_str or "not found" in error_str:
error_response = create_resource_not_found_error(
"Automation",
identifier,
details=f"Automation '{identifier}' does not exist",
)
else:
error_response = exception_to_structured_error(
e,
context={"identifier": identifier},
raise_error=False,
)
error_response["action"] = "delete"
# Add automation-specific suggestions
if "error" in error_response and isinstance(error_response["error"], dict):
error_response["error"]["suggestions"] = [
"Verify automation exists using ha_search_entities(domain_filter='automation')",
"Use entity_id format: automation.morning_routine or unique_id",
"Check Home Assistant connection",
]
raise_tool_error(error_response)