forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools_config_helpers.py
More file actions
1215 lines (1117 loc) · 52 KB
/
Copy pathtools_config_helpers.py
File metadata and controls
1215 lines (1117 loc) · 52 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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Configuration management tools for Home Assistant helpers.
This module provides tools for listing, creating, updating, and removing
Home Assistant helper entities (input_button, input_boolean, input_select,
input_number, input_text, input_datetime, counter, timer, schedule).
"""
import asyncio
import logging
from typing import Annotated, Any, Literal
from fastmcp.exceptions import ToolError
from pydantic import Field
from ..errors import ErrorCode, create_error_response
from .helpers import exception_to_structured_error, log_tool_usage, raise_tool_error
from .util_helpers import (
coerce_bool_param,
parse_string_list_param,
wait_for_entity_registered,
wait_for_entity_removed,
)
logger = logging.getLogger(__name__)
def _format_schedule_days(
monday: list | None,
tuesday: list | None,
wednesday: list | None,
thursday: list | None,
friday: list | None,
saturday: list | None,
sunday: list | None,
) -> dict[str, list[dict[str, Any]]]:
"""Format schedule day data, ensuring time strings include seconds.
Returns a dict of day_name -> formatted time ranges, only for days
where data was provided (not None).
"""
day_params = {
"monday": monday,
"tuesday": tuesday,
"wednesday": wednesday,
"thursday": thursday,
"friday": friday,
"saturday": saturday,
"sunday": sunday,
}
formatted_days: dict[str, list[dict[str, Any]]] = {}
for day_name, day_schedule in day_params.items():
if day_schedule is not None:
formatted_ranges = []
for time_range in day_schedule:
formatted_range: dict[str, Any] = {}
for key in ["from", "to"]:
if key in time_range:
time_val = time_range[key]
if isinstance(time_val, str) and time_val.count(":") == 1:
time_val = f"{time_val}:00"
formatted_range[key] = time_val
if "data" in time_range:
formatted_range["data"] = time_range["data"]
formatted_ranges.append(formatted_range)
formatted_days[day_name] = formatted_ranges
return formatted_days
def register_config_helper_tools(mcp: Any, client: Any, **kwargs: Any) -> None:
"""Register Home Assistant helper configuration tools."""
@mcp.tool(
tags={"Helper Entities"},
annotations={
"idempotentHint": True,
"readOnlyHint": True,
"title": "List Helpers"
}
)
@log_tool_usage
async def ha_config_list_helpers(
helper_type: Annotated[
Literal[
"input_button",
"input_boolean",
"input_select",
"input_number",
"input_text",
"input_datetime",
"counter",
"timer",
"schedule",
"zone",
"person",
"tag",
],
Field(description="Type of helper entity to list"),
],
) -> dict[str, Any]:
"""
List all Home Assistant helpers of a specific type with their configurations.
Returns complete configuration for all helpers of the specified type including:
- ID, name, icon
- Type-specific settings (min/max for input_number, options for input_select, etc.)
- Area and label assignments
SUPPORTED HELPER TYPES:
- input_button: Virtual buttons for triggering automations
- input_boolean: Toggle switches/checkboxes
- input_select: Dropdown selection lists
- input_number: Numeric sliders/input boxes
- input_text: Text input fields
- input_datetime: Date/time pickers
- counter: Counters with increment/decrement/reset
- timer: Countdown timers with start/pause/cancel
- schedule: Weekly schedules with time ranges (on/off per day)
- zone: Geographical zones for presence detection
- person: Person entities linked to device trackers
- tag: NFC/QR tags for automation triggers
EXAMPLES:
- List all number helpers: ha_config_list_helpers("input_number")
- List all counters: ha_config_list_helpers("counter")
- List all zones: ha_config_list_helpers("zone")
- List all persons: ha_config_list_helpers("person")
- List all tags: ha_config_list_helpers("tag")
**NOTE:** This only returns storage-based helpers (created via UI/API), not YAML-defined helpers.
For detailed helper documentation, use ha_get_skill_home_assistant_best_practices.
"""
try:
# Use the websocket list endpoint for the helper type
message: dict[str, Any] = {
"type": f"{helper_type}/list",
}
result = await client.send_websocket_message(message)
if result.get("success"):
items = result.get("result", [])
return {
"success": True,
"helper_type": helper_type,
"count": len(items),
"helpers": items,
"message": f"Found {len(items)} {helper_type} helper(s)",
}
else:
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to list helpers: {result.get('error', 'Unknown error')}",
context={"helper_type": helper_type},
))
except ToolError:
raise
except Exception as e:
logger.error(f"Error listing helpers: {e}")
exception_to_structured_error(
e,
context={"helper_type": helper_type},
suggestions=[
"Check Home Assistant connection",
"Verify WebSocket connection is active",
"Use ha_search_entities(domain_filter='input_*') as alternative",
],
)
@mcp.tool(
tags={"Helper Entities"},
annotations={
"destructiveHint": True,
"title": "Create or Update Helper"
}
)
@log_tool_usage
async def ha_config_set_helper(
helper_type: Annotated[
Literal[
"input_button",
"input_boolean",
"input_select",
"input_number",
"input_text",
"input_datetime",
"counter",
"timer",
"schedule",
"zone",
"person",
"tag",
],
Field(description="Type of helper entity to create or update"),
],
name: Annotated[str, Field(description="Display name for the helper")],
helper_id: Annotated[
str | None,
Field(
description="Helper ID for updates (e.g., 'my_button' or 'input_button.my_button'). If not provided, creates a new helper.",
default=None,
),
] = None,
icon: Annotated[
str | None,
Field(
description="Material Design Icon (e.g., 'mdi:bell', 'mdi:toggle-switch')",
default=None,
),
] = None,
area_id: Annotated[
str | None,
Field(description="Area/room ID to assign the helper to", default=None),
] = None,
labels: Annotated[
str | list[str] | None,
Field(description="Labels to categorize the helper", default=None),
] = None,
min_value: Annotated[
float | None,
Field(
description="Minimum value (input_number/counter) or minimum length (input_text)",
default=None,
),
] = None,
max_value: Annotated[
float | None,
Field(
description="Maximum value (input_number/counter) or maximum length (input_text)",
default=None,
),
] = None,
step: Annotated[
float | None,
Field(
description="Step/increment value for input_number or counter",
default=None,
),
] = None,
unit_of_measurement: Annotated[
str | None,
Field(
description="Unit of measurement for input_number (e.g., '°C', '%', 'W')",
default=None,
),
] = None,
options: Annotated[
str | list[str] | None,
Field(
description="List of options for input_select (required for input_select)",
default=None,
),
] = None,
initial: Annotated[
str | int | None,
Field(
description="Initial value for the helper (input_select, input_text, input_boolean, input_datetime, counter)",
default=None,
),
] = None,
mode: Annotated[
str | None,
Field(
description="Display mode: 'box'/'slider' for input_number, 'text'/'password' for input_text",
default=None,
),
] = None,
has_date: Annotated[
bool | None,
Field(
description="Include date component for input_datetime", default=None
),
] = None,
has_time: Annotated[
bool | None,
Field(
description="Include time component for input_datetime", default=None
),
] = None,
restore: Annotated[
bool | None,
Field(
description="Restore state after restart (counter, timer). Defaults to True for counter, False for timer",
default=None,
),
] = None,
duration: Annotated[
str | None,
Field(
description="Default duration for timer in format 'HH:MM:SS' or seconds (e.g., '0:05:00' for 5 minutes)",
default=None,
),
] = None,
monday: Annotated[
list[dict[str, Any]] | None,
Field(
description="Schedule time ranges for Monday. List of {'from': 'HH:MM', 'to': 'HH:MM'} dicts. Optional 'data' dict for additional attributes (e.g. {'from': '07:00', 'to': '22:00', 'data': {'mode': 'comfort'}})",
default=None,
),
] = None,
tuesday: Annotated[
list[dict[str, Any]] | None,
Field(
description="Schedule time ranges for Tuesday. List of {'from': 'HH:MM', 'to': 'HH:MM'} dicts. Optional 'data' dict for additional attributes.",
default=None,
),
] = None,
wednesday: Annotated[
list[dict[str, Any]] | None,
Field(
description="Schedule time ranges for Wednesday. List of {'from': 'HH:MM', 'to': 'HH:MM'} dicts. Optional 'data' dict for additional attributes.",
default=None,
),
] = None,
thursday: Annotated[
list[dict[str, Any]] | None,
Field(
description="Schedule time ranges for Thursday. List of {'from': 'HH:MM', 'to': 'HH:MM'} dicts. Optional 'data' dict for additional attributes.",
default=None,
),
] = None,
friday: Annotated[
list[dict[str, Any]] | None,
Field(
description="Schedule time ranges for Friday. List of {'from': 'HH:MM', 'to': 'HH:MM'} dicts. Optional 'data' dict for additional attributes.",
default=None,
),
] = None,
saturday: Annotated[
list[dict[str, Any]] | None,
Field(
description="Schedule time ranges for Saturday. List of {'from': 'HH:MM', 'to': 'HH:MM'} dicts. Optional 'data' dict for additional attributes.",
default=None,
),
] = None,
sunday: Annotated[
list[dict[str, Any]] | None,
Field(
description="Schedule time ranges for Sunday. List of {'from': 'HH:MM', 'to': 'HH:MM'} dicts. Optional 'data' dict for additional attributes.",
default=None,
),
] = None,
latitude: Annotated[
float | None,
Field(
description="Latitude for zone (required for zone)",
default=None,
),
] = None,
longitude: Annotated[
float | None,
Field(
description="Longitude for zone (required for zone)",
default=None,
),
] = None,
radius: Annotated[
float | None,
Field(
description="Radius in meters for zone (default: 100)",
default=None,
),
] = None,
passive: Annotated[
bool | None,
Field(
description="Passive zone (won't trigger state changes for person entities)",
default=None,
),
] = None,
user_id: Annotated[
str | None,
Field(
description="User ID to link to person entity",
default=None,
),
] = None,
device_trackers: Annotated[
list[str] | None,
Field(
description="List of device_tracker entity IDs for person",
default=None,
),
] = None,
picture: Annotated[
str | None,
Field(
description="Picture URL for person entity",
default=None,
),
] = None,
tag_id: Annotated[
str | None,
Field(
description="Tag ID for tag (auto-generated if not provided)",
default=None,
),
] = None,
description: Annotated[
str | None,
Field(
description="Description for tag",
default=None,
),
] = None,
category: Annotated[
str | None,
Field(
description="Category ID to assign to this helper. Use ha_config_get_category() to list available categories.",
default=None,
),
] = None,
wait: Annotated[
bool | str,
Field(
description="Wait for helper entity to be queryable before returning. Default: True. Set to False for bulk operations.",
default=True,
),
] = True,
) -> dict[str, Any]:
"""
Create or update Home Assistant helper entities.
Creates new helper if helper_id is omitted, updates existing if helper_id is provided.
Parameters are validated by Home Assistant - errors return clear messages.
QUICK EXAMPLES:
- ha_config_set_helper("input_boolean", "My Switch", icon="mdi:toggle-switch")
- ha_config_set_helper("counter", "My Counter", initial=0, step=1)
- ha_config_set_helper("timer", "Laundry", duration="0:45:00")
- ha_config_set_helper("zone", "Office", latitude=37.77, longitude=-122.41, radius=100)
- ha_config_set_helper("schedule", "Work", monday=[{"from": "09:00", "to": "17:00"}])
- ha_config_set_helper("schedule", "Light", monday=[{"from": "07:00", "to": "22:00", "data": {"brightness": "100", "mode": "comfort"}}])
TEMPLATE SENSORS AND BINARY SENSORS:
Use ha_set_config_entry_helper(helper_type="template", ...) — not this tool.
Template helpers are managed via the Config Entry Flow API.
Before reaching for a template, check if a simpler built-in exists:
- min_max instead of template for combining sensors
- group instead of template binary sensor for any/all logic
- counter instead of template with math for counting
- input_number instead of template for storing values
- schedule instead of template with weekday checks
Workflow:
1. ha_get_helper_schema("template") → see available sub-types
2. ha_get_helper_schema("template", menu_option="sensor") → see form fields
3. ha_set_config_entry_helper("template", {
"next_step_id": "sensor",
"name": "My Sensor",
"state": "{{ states('sensor.foo') }}",
})
For detailed parameter info, use ha_get_skill_home_assistant_best_practices.
"""
try:
# Parse JSON list parameters if provided as strings
try:
labels = parse_string_list_param(labels, "labels")
options = parse_string_list_param(options, "options")
except ValueError as e:
raise_tool_error(create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
f"Invalid list parameter: {e}",
))
# Determine if this is a create or update based on helper_id
action = "update" if helper_id else "create"
if action == "create":
if not name:
raise_tool_error(create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
"name is required for create action",
context={"helper_type": helper_type},
))
# Build create message based on helper type
message: dict[str, Any] = {
"type": f"{helper_type}/create",
"name": name,
}
# Icon supported by most helpers except person and tag
if icon and helper_type not in ("person", "tag"):
message["icon"] = icon
# Type-specific parameters
if helper_type == "input_select":
if not options:
raise_tool_error(create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
"options list is required for input_select",
context={"helper_type": helper_type},
))
if not isinstance(options, list) or len(options) == 0:
raise_tool_error(create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
"options must be a non-empty list for input_select",
context={"helper_type": helper_type},
))
message["options"] = options
if initial and initial in options:
message["initial"] = initial
elif helper_type == "input_number":
# Validate min_value/max_value range
if (
min_value is not None
and max_value is not None
and min_value > max_value
):
raise_tool_error(create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
f"Minimum value ({min_value}) cannot be greater than maximum value ({max_value})",
context={"min_value": min_value, "max_value": max_value},
))
if min_value is not None:
message["min"] = min_value
if max_value is not None:
message["max"] = max_value
if step is not None:
message["step"] = step
if unit_of_measurement:
message["unit_of_measurement"] = unit_of_measurement
if mode in ["box", "slider"]:
message["mode"] = mode
elif helper_type == "input_text":
if min_value is not None:
message["min"] = int(min_value)
if max_value is not None:
message["max"] = int(max_value)
if mode in ["text", "password"]:
message["mode"] = mode
if initial:
message["initial"] = initial
elif helper_type == "input_boolean":
if initial is not None:
initial_str = str(initial).lower()
message["initial"] = initial_str in [
"true",
"on",
"yes",
"1",
]
elif helper_type == "input_datetime":
# At least one of has_date or has_time must be True
if has_date is None and has_time is None:
# Default to both if not specified
message["has_date"] = True
message["has_time"] = True
elif has_date is None:
message["has_date"] = False
message["has_time"] = has_time
elif has_time is None:
message["has_date"] = has_date
message["has_time"] = False
else:
message["has_date"] = has_date
message["has_time"] = has_time
# Validate that at least one is True
if not message["has_date"] and not message["has_time"]:
raise_tool_error(create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
"At least one of has_date or has_time must be True for input_datetime",
context={"helper_type": helper_type},
))
if initial:
message["initial"] = initial
elif helper_type == "counter":
# Counter parameters: initial, minimum, maximum, step, restore
if initial is not None:
message["initial"] = (
int(initial) if isinstance(initial, str) else initial
)
if min_value is not None:
message["minimum"] = int(min_value)
if max_value is not None:
message["maximum"] = int(max_value)
if step is not None:
message["step"] = int(step)
if restore is not None:
message["restore"] = restore
elif helper_type == "timer":
# Timer parameters: duration, restore
if duration:
message["duration"] = duration
if restore is not None:
message["restore"] = restore
elif helper_type == "schedule":
# Schedule parameters: monday-sunday with time ranges
# Each day is a list of {"from": "HH:MM:SS", "to": "HH:MM:SS"}
# with optional "data" dict for additional attributes
message.update(_format_schedule_days(
monday, tuesday, wednesday, thursday,
friday, saturday, sunday,
))
elif helper_type == "zone":
# Zone parameters - HA validates required fields (latitude, longitude)
if latitude is not None:
message["latitude"] = latitude
if longitude is not None:
message["longitude"] = longitude
if radius is not None:
message["radius"] = radius
if passive is not None:
message["passive"] = passive
elif helper_type == "person":
# Person parameters: user_id, device_trackers, picture
if user_id:
message["user_id"] = user_id
if device_trackers:
message["device_trackers"] = device_trackers
if picture:
message["picture"] = picture
elif helper_type == "tag":
# Tag parameters: tag_id, description
# Note: name goes into entity registry, not tag storage
if tag_id:
message["tag_id"] = tag_id
if description:
message["description"] = description
result = await client.send_websocket_message(message)
if result.get("success"):
helper_data = result.get("result", {})
entity_id = helper_data.get("entity_id")
# Wait for entity to be properly registered before proceeding
wait_bool = coerce_bool_param(wait, "wait", default=True)
if wait_bool and entity_id:
try:
registered = await wait_for_entity_registered(client, entity_id)
if not registered:
helper_data["warning"] = f"Helper created but {entity_id} not yet queryable. It may take a moment to become available."
except Exception as e:
helper_data["warning"] = f"Helper created but verification failed: {e}"
# Update entity registry if area_id, labels, or category specified
if (area_id or labels or category) and entity_id:
update_message: dict[str, Any] = {
"type": "config/entity_registry/update",
"entity_id": entity_id,
}
if area_id:
update_message["area_id"] = area_id
if labels:
update_message["labels"] = labels
if category:
update_message["categories"] = {helper_type: category}
update_result = await client.send_websocket_message(
update_message
)
if update_result.get("success"):
helper_data["area_id"] = area_id
helper_data["labels"] = labels
if category:
helper_data["category"] = category
return {
"success": True,
"action": "create",
"helper_type": helper_type,
"helper_data": helper_data,
"entity_id": entity_id,
"message": f"Successfully created {helper_type}: {name}",
}
else:
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to create helper: {result.get('error', 'Unknown error')}",
context={"helper_type": helper_type, "name": name},
))
elif action == "update":
if not helper_id:
raise_tool_error(create_error_response(
ErrorCode.VALIDATION_INVALID_PARAMETER,
"helper_id is required for update action",
context={"helper_type": helper_type},
))
entity_id = (
helper_id
if helper_id.startswith(helper_type)
else f"{helper_type}.{helper_id}"
)
# Person, zone, and tag store config in separate config stores
# (not just the entity registry). Route updates accordingly.
# Person and zone have entity registry entries with unique_id
# used as the config store identifier. Tags use their own tag
# registry and don't have entity registry entries.
config_store_types = {"person", "zone", "schedule"}
updated_data: dict[str, Any] = {}
if helper_type == "tag":
# Tags use their own registry — no entity registry entries.
# The helper_id IS the tag_id (strip "tag." prefix if present).
tag_update_id = (
helper_id.removeprefix("tag.")
if helper_id.startswith("tag.")
else helper_id
)
update_msg: dict[str, Any] = {
"type": "tag/update",
"tag_id": tag_update_id,
}
if name is not None:
update_msg["name"] = name
if description is not None:
update_msg["description"] = description
result = await client.send_websocket_message(update_msg)
if not result.get("success"):
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to update tag config: {result.get('error', 'Unknown error')}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
updated_data = result.get("result", {})
# Tags don't have entity registry entries, so return directly
# without wait_for_entity_registered (they're not entities).
return {
"success": True,
"action": "update",
"helper_type": helper_type,
"entity_id": entity_id,
"updated_data": updated_data,
"message": f"Successfully updated {helper_type}: {entity_id}",
}
elif helper_type in config_store_types:
# Person and zone: look up unique_id from entity registry
registry_msg: dict[str, Any] = {
"type": "config/entity_registry/get",
"entity_id": entity_id,
}
registry_result = await client.send_websocket_message(
registry_msg
)
if not registry_result.get("success"):
raise_tool_error(create_error_response(
ErrorCode.ENTITY_NOT_FOUND,
f"Could not find {helper_type} entity: {entity_id}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
registry_entry = registry_result.get("result", {})
if not isinstance(registry_entry, dict):
raise_tool_error(create_error_response(
ErrorCode.INTERNAL_ERROR,
f"Unexpected registry response for {entity_id}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
unique_id = registry_entry.get("unique_id")
if not unique_id:
raise_tool_error(create_error_response(
ErrorCode.CONFIG_NOT_FOUND,
f"No unique_id found in entity registry for {entity_id}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
if helper_type == "person":
# Person config API is full-replace (not patch):
# fetch current config, merge with new values, then send.
list_result = await client.send_websocket_message(
{"type": "person/list"}
)
if not list_result.get("success"):
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to fetch person config list: {list_result.get('error', 'Unknown')}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
# person/list returns {"storage": [...], "config": [...]}
# "storage" contains UI-managed (editable) persons
person_result = list_result.get("result", {})
person_list = (
person_result.get("storage", [])
if isinstance(person_result, dict)
else person_result
)
current_config = next(
(
p for p in person_list
if isinstance(p, dict) and p.get("id") == unique_id
),
None,
)
if not current_config:
raise_tool_error(create_error_response(
ErrorCode.CONFIG_NOT_FOUND,
f"Person config not found for id: {unique_id}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
# Merge: use new values if provided, else keep current
update_msg = {
"type": "person/update",
"person_id": unique_id,
"name": name if name is not None else current_config.get("name"),
"user_id": user_id
if user_id is not None
else current_config.get("user_id"),
"device_trackers": device_trackers
if device_trackers is not None
else current_config.get("device_trackers", []),
}
if picture is not None:
update_msg["picture"] = picture
elif current_config.get("picture"):
update_msg["picture"] = current_config["picture"]
result = await client.send_websocket_message(update_msg)
if not result.get("success"):
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to update person config: {result.get('error', 'Unknown error')}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
updated_data = result.get("result", {})
elif helper_type == "zone":
update_msg = {
"type": "zone/update",
"zone_id": unique_id,
}
if name is not None:
update_msg["name"] = name
if latitude is not None:
update_msg["latitude"] = latitude
if longitude is not None:
update_msg["longitude"] = longitude
if radius is not None:
update_msg["radius"] = radius
if passive is not None:
update_msg["passive"] = passive
result = await client.send_websocket_message(update_msg)
if not result.get("success"):
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to update zone config: {result.get('error', 'Unknown error')}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
updated_data = result.get("result", {})
elif helper_type == "schedule":
update_msg = {
"type": "schedule/update",
"schedule_id": unique_id,
}
if name is not None:
update_msg["name"] = name
if icon is not None:
update_msg["icon"] = icon
update_msg.update(_format_schedule_days(
monday, tuesday, wednesday, thursday,
friday, saturday, sunday,
))
result = await client.send_websocket_message(update_msg)
if not result.get("success"):
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to update schedule config: {result.get('error', 'Unknown error')}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
updated_data = result.get("result", {})
# Also update entity registry for icon, area, and labels
if icon or area_id or labels:
registry_update: dict[str, Any] = {
"type": "config/entity_registry/update",
"entity_id": entity_id,
}
if icon:
registry_update["icon"] = icon
if area_id:
registry_update["area_id"] = area_id
if labels:
registry_update["labels"] = labels
await client.send_websocket_message(registry_update)
else:
# Standard helpers: entity registry update only
update_msg = {
"type": "config/entity_registry/update",
"entity_id": entity_id,
}
if name is not None:
update_msg["name"] = name
if icon:
update_msg["icon"] = icon
if area_id:
update_msg["area_id"] = area_id
if labels:
update_msg["labels"] = labels
result = await client.send_websocket_message(update_msg)
if result.get("success"):
updated_data = result.get("result", {}).get("entity_entry", {})
else:
raise_tool_error(create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
f"Failed to update helper: {result.get('error', 'Unknown error')}",
context={"helper_type": helper_type, "entity_id": entity_id},
))
# Wait for entity to reflect the update
wait_bool = coerce_bool_param(wait, "wait", default=True)
response: dict[str, Any] = {
"success": True,
"action": "update",
"helper_type": helper_type,
"entity_id": entity_id,
"updated_data": updated_data,
"message": f"Successfully updated {helper_type}: {entity_id}",
}
if wait_bool:
try:
registered = await wait_for_entity_registered(client, entity_id)
if not registered:
response["warning"] = f"Update applied but {entity_id} not yet queryable."
except Exception as e:
response["warning"] = f"Update applied but verification failed: {e}"
return response
# This should never be reached since action is either "create" or "update"
raise_tool_error(create_error_response(
ErrorCode.INTERNAL_ERROR,
f"Unexpected action: {action}",
))
except ToolError:
raise
except Exception as e:
exception_to_structured_error(
e,
context={"action": action, "helper_type": helper_type},
suggestions=[
"Check Home Assistant connection",
"Verify helper_id exists for update operations",
"Ensure required parameters are provided for the helper type",
],
)
@mcp.tool(
tags={"Helper Entities"},
annotations={
"destructiveHint": True,
"idempotentHint": True,
"title": "Remove Helper"
}
)
@log_tool_usage
async def ha_config_remove_helper(
helper_type: Annotated[
Literal[
"input_button",
"input_boolean",
"input_select",
"input_number",
"input_text",
"input_datetime",
"counter",
"timer",
"schedule",
"zone",
"person",
"tag",
],
Field(description="Type of helper entity to delete"),
],
helper_id: Annotated[
str,
Field(