forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrest_client.py
More file actions
2138 lines (1863 loc) · 91.9 KB
/
Copy pathrest_client.py
File metadata and controls
2138 lines (1863 loc) · 91.9 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
"""
Home Assistant HTTP client with authentication and error handling.
"""
import asyncio
import json
import logging
import os
import ssl
import time
from dataclasses import dataclass
from typing import Any, NoReturn
import httpx
from .._vendor.websockets.exceptions import WebSocketException
from .._version import get_supervisor_base_url, is_running_in_addon
from ..config import get_global_settings
from .supervisor_client import make_supervisor_httpx_client
def _is_ssl_error(exc: BaseException) -> bool:
"""True if ``exc`` (or anything in its cause chain) is an SSL error.
httpx wraps ``ssl.SSLError`` inside ``httpx.ConnectError``; the only
reliable check is to walk ``__cause__`` / ``__context__``.
"""
cur: BaseException | None = exc
while cur is not None:
if isinstance(cur, ssl.SSLError):
return True
cur = cur.__cause__ or cur.__context__
return False
logger = logging.getLogger(__name__)
# Transient gateway statuses from a reverse proxy / Supervisor ingress — HA Core
# restarting or briefly overloaded behind it. Retried for SAFE METHODS ONLY.
#
# None of them proves Home Assistant did not execute the request: RFC 9110 has
# 502 as "received an invalid response from an inbound server", which a proxy
# only sends after reaching it, and 504 as the upstream answering too slowly.
# #1623 extended the retry to writes on the premise that "a gateway 5xx means
# the request never reached the backend"; that premise is false, and replaying
# a write can double-apply it — fire an event twice, run a script twice, or
# turn a completed DELETE into a misleading 404 on the replay.
#
# The flake class #1623 fixed was a 502 storm failing ~190 tests at once, which
# is overwhelmingly reads; those keep the retry. A write that fails loudly is
# recoverable by the caller, which a silent double-apply is not.
_RETRYABLE_GATEWAY_STATUS = frozenset({502, 503, 504})
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
_MAX_REQUEST_ATTEMPTS = 3
# Journald window requested for the Core error log on Supervisor-backed
# installs. Both such branches of get_error_log() build their request from this
# constant, so the window they ask for cannot drift apart.
_ERROR_LOG_LINES = 20000
class HomeAssistantError(Exception):
"""Base exception for Home Assistant API errors."""
class HomeAssistantConnectionError(HomeAssistantError):
"""Connection error to Home Assistant."""
class HomeAssistantCommandNotSent(HomeAssistantConnectionError):
"""A WS command that provably never left the process.
Raised by ``HomeAssistantWebSocketClient.send_command`` ONLY at its single
provably-never-sent site: the entry-guard reject (socket not authenticated), where
nothing is transmitted. Subclass of ``HomeAssistantConnectionError`` so every
existing broad handler is unaffected, yet a write consumer can catch this type
FIRST to fall back to the legacy path safely — the write provably never happened,
so a legacy first fire cannot double-apply. A ``send_json_message`` failure is NOT
this type: ``websocket.send()`` raising does not prove the frame was untransmitted
(bytes may already be on the socket when the close surfaces), so send_command
re-raises the original exception and the consumer treats it as ambiguous. A
post-send socket close (mid-await) likewise raises a plain
``HomeAssistantConnectionError`` (the close handler sets it on the pending future),
so type alone distinguishes never-sent from sent-then-dropped/ambiguous.
"""
class HomeAssistantAuthError(HomeAssistantError):
"""Authentication error with Home Assistant.
Sibling of ``HomeAssistantAPIError`` (not a subclass). The codebase has
18 ``except HomeAssistantAPIError`` sites (util_helpers polling,
tools_integrations registry lookups, etc.) that deliberately rely on
auth errors NOT matching so they can propagate to a paired
``except (HomeAssistantConnectionError, HomeAssistantAuthError): raise``
block. Subclassing AuthError under APIError silently swallowed those
auth errors as part of the local "this entity is not registered yet"
polling logic. Sites that specifically need to catch both must list
them explicitly (see ``_get_supervisor_log`` and
``_get_system_service_log`` in ``tools_utility.py``).
"""
class HomeAssistantAPIError(HomeAssistantError):
"""API error from Home Assistant."""
def __init__(
self,
message: str,
status_code: int | None = None,
response_data: dict[str, Any] | None = None,
):
super().__init__(message)
self.status_code = status_code
self.response_data = response_data
@dataclass(frozen=True)
class SceneResolution:
"""Outcome of resolving a scene identifier via the entity registry.
``registry_hit`` records whether ``config/entity_registry/get`` returned a
usable ``unique_id`` - i.e. the entity actually EXISTS. It is the signal that
separates a genuinely-missing scene from one that exists but is not editable
through HA's scene config API (a Hue/vendor scene, or a raw-YAML scene): both
resolve fine yet 404 on ``config/scene/config/{id}``, because that endpoint is
backed only by the managed ``scenes.yaml`` (issue #1971). ``platform`` carries
the registry entry's integration domain (``"hue"``, ``"homeassistant"``, …)
for error-message enrichment only - it never drives the classification, since
a raw-YAML scene is ``platform="homeassistant"`` yet still 404s.
"""
storage_key: str
registry_hit: bool
platform: str | None
class SceneStorageConfigNotFoundError(HomeAssistantAPIError):
"""A scene entity resolved in the registry, but ``config/scene/config/{id}``
(backed by ``scenes.yaml``) has no matching entry.
The entity EXISTS; it is simply not an editable Home Assistant storage scene
(Hue/vendor scene, or a raw-YAML scene). Raised instead of a bare 404 so the
tools layer can surface ``CONFIG_NOT_FOUND`` rather than the misleading
``ENTITY_NOT_FOUND``/``RESOURCE_NOT_FOUND`` (issue #1971). Subclasses
``HomeAssistantAPIError`` so existing ``except HomeAssistantAPIError`` sites
keep treating it as the 404 it is.
"""
def __init__(
self,
scene_id: str,
*,
platform: str | None = None,
storage_key: str | None = None,
):
self.scene_id = scene_id
self.platform = platform
self.storage_key = storage_key
msg = f"Scene not found in editable storage: {scene_id}"
if storage_key and storage_key != scene_id:
msg += f" (resolved storage key: {storage_key})"
super().__init__(msg, status_code=404)
class HomeAssistantCommandError(HomeAssistantError):
"""WebSocket command returned success=False.
Raised by ``WebSocketClient.send_command`` when Home Assistant responds
with ``{type: "result", success: False}``. Used as a type marker in
``_classify_exception``'s match dispatch; classification then falls
through to ``_classify_by_message`` for pattern matching on the
error message.
``code`` carries HA's structured WebSocket error code (the ``code`` field
of the response ``error`` object — e.g. ``"unknown_command"``,
``"invalid_format"``) when available, so routing decisions can key off the
stable code rather than pattern-matching the human-readable message. It
defaults to ``None`` for exceptions raised without a code (older raise
sites, string error payloads, or direct construction in tests), which
keeps the single-positional-argument constructor backward-compatible.
"""
def __init__(self, message: str, code: str | None = None):
super().__init__(message)
self.code = code
class HomeAssistantCommandTimeout(HomeAssistantError):
"""WebSocket ``send_command`` timed out waiting for HA's response.
Sibling of ``HomeAssistantCommandError`` (not a subclass) so existing
``except HomeAssistantCommandError`` sites — including the match
dispatch in ``helpers._classify_exception`` — keep their original
semantics. Callers that specifically want to handle our 30s WS
round-trip timeout (e.g. short-lived waiter cleanup that should
swallow a timeout instead of masking the real wait result) catch
this type directly. Replaces a bare ``Exception("Command timeout")``
string-match pattern (#1382 Patch76 review).
"""
# Exception classes that are evidence no answer came back from Home Assistant,
# as opposed to Home Assistant answering with a rejection. ``OSError`` covers
# ``ConnectionResetError``; ``WebSocketException`` covers the
# ``ConnectionClosed`` family that ``send_command`` re-raises unwrapped;
# ``HomeAssistantCommandTimeout`` covers a socket that is still open but has
# stopped answering, which leaves a caller just as blind as a closed one.
_NO_ANSWER_ERRORS = (
HomeAssistantConnectionError,
HomeAssistantCommandTimeout,
OSError,
WebSocketException,
)
class HomeAssistantClient:
"""Authenticated HTTP client for Home Assistant API."""
def __init__(
self,
base_url: str | None = None,
token: str | None = None,
timeout: int | None = None,
verify_ssl: bool | None = None,
):
"""
Initialize Home Assistant client.
Args:
base_url: Home Assistant URL (defaults to config)
token: Long-lived access token (defaults to config)
timeout: Request timeout in seconds (defaults to config)
verify_ssl: Whether to verify the HA server's TLS certificate
(defaults to ``settings.verify_ssl``). Pass False to allow
self-signed certs or hostname mismatches.
"""
if base_url is None or token is None or verify_ssl is None:
settings = get_global_settings()
self.base_url = (base_url or settings.homeassistant_url).rstrip("/")
self.token = token or settings.homeassistant_token
self.timeout = timeout if timeout is not None else settings.timeout
self.verify_ssl = (
verify_ssl if verify_ssl is not None else settings.verify_ssl
)
else:
self.base_url = base_url.rstrip("/")
self.token = token
self.timeout = timeout if timeout is not None else 30 # Default timeout
self.verify_ssl = verify_ssl
if not self.verify_ssl:
logger.warning(
"TLS verification disabled for Home Assistant REST client "
"(HA_VERIFY_SSL=false). Connections to %s will accept "
"self-signed and mismatched certificates.",
self.base_url,
)
# Create HTTP client with authentication headers
self.httpx_client = httpx.AsyncClient(
base_url=f"{self.base_url}/api",
headers={
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
},
timeout=httpx.Timeout(self.timeout),
verify=self.verify_ssl,
)
# Lazy-populated by ``_is_supervised_install``. ``None`` means
# "not probed yet"; ``True`` is cached for the session lifetime
# (HAOS-ness can't change at runtime). ``False`` is NOT cached so a
# transient probe failure on the first call doesn't permanently
# disable the supervised branch — subsequent calls re-probe.
self._supervised_detected: bool | None = None
logger.info(f"Initialized Home Assistant client for {self.base_url}")
async def __aenter__(self) -> "HomeAssistantClient":
"""Async context manager entry."""
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
"""Async context manager exit."""
await self.close()
async def close(self) -> None:
"""Close HTTP client."""
await self.httpx_client.aclose()
logger.debug("Closed Home Assistant client")
@staticmethod
def _error_message_from_response(
response: httpx.Response,
) -> tuple[str, dict[str, Any]]:
"""Build a human message and structured error data from a 4xx/5xx body.
Prefers the JSON ``message`` field; falls back to reason phrase or a
placeholder when the body is empty or unparseable.
"""
try:
error_data = response.json()
except Exception:
error_data = {"message": response.text}
message = error_data.get("message")
if not message or not message.strip():
message = response.reason_phrase or "<empty body>"
return message, error_data
async def _raw_request(
self, method: str, endpoint: str, **kwargs: Any
) -> httpx.Response:
"""Authenticated request that returns the raw httpx.Response.
Handles auth, HTTP 4xx/5xx, and transport errors in one place.
Callers parse the body themselves (JSON via `_request`, text via
`get_addon_logs`, etc.). Transient gateway errors (502/503/504) are
retried with bounded exponential backoff for safe methods only; a write
is never replayed.
Raises:
HomeAssistantAuthError: 401 response.
HomeAssistantAPIError: Non-2xx response (with status_code and
response_data set from JSON body when possible).
HomeAssistantConnectionError: Network, timeout, or transport error.
"""
backoff = 0.5
for attempt in range(1, _MAX_REQUEST_ATTEMPTS + 1):
try:
response = await self.httpx_client.request(method, endpoint, **kwargs)
if response.status_code == 401:
raise HomeAssistantAuthError("Invalid authentication token")
if response.status_code >= 400:
message, error_data = self._error_message_from_response(response)
retryable = (
response.status_code in _RETRYABLE_GATEWAY_STATUS
and method.upper() in _SAFE_METHODS
)
if retryable and attempt < _MAX_REQUEST_ATTEMPTS:
logger.warning(
f"Transient {response.status_code} from Home Assistant "
f"(attempt {attempt}/{_MAX_REQUEST_ATTEMPTS}), retrying "
f"in {backoff}s: {message}"
)
await asyncio.sleep(backoff)
backoff *= 2
continue
raise HomeAssistantAPIError(
f"API error: {response.status_code} - {message}",
status_code=response.status_code,
response_data=error_data,
)
return response
except httpx.ConnectError as e:
if _is_ssl_error(e) and self.verify_ssl:
raise HomeAssistantConnectionError(
f"TLS verification failed for {self.base_url}: {e}. "
"If this is a self-signed certificate or hostname "
"mismatch, set HA_VERIFY_SSL=false to skip verification."
) from e
raise HomeAssistantConnectionError(
f"Failed to connect to Home Assistant: {e}"
) from e
except httpx.TimeoutException as e:
raise HomeAssistantConnectionError(f"Request timeout: {e}") from e
except httpx.HTTPError as e:
raise HomeAssistantConnectionError(f"HTTP error: {e}") from e
# Unreachable: the final attempt takes the non-retry branch and raises.
raise AssertionError("_raw_request retry loop exhausted without returning")
async def _request(
self, method: str, endpoint: str, **kwargs: Any
) -> dict[str, Any]:
"""
Make authenticated request to Home Assistant API and parse JSON body.
Args:
method: HTTP method (GET, POST, etc.)
endpoint: API endpoint (without /api prefix)
**kwargs: Additional arguments for httpx request
Returns:
Response data as dictionary
Raises:
HomeAssistantConnectionError: Connection failed
HomeAssistantAuthError: Authentication failed
HomeAssistantAPIError: API error
"""
response = await self._raw_request(method, endpoint, **kwargs)
try:
result: dict[str, Any] = response.json()
return result
except json.JSONDecodeError:
# Some endpoints return empty responses
return {}
async def get_config(self) -> dict[str, Any]:
"""Get Home Assistant configuration."""
logger.debug("Fetching Home Assistant configuration")
return await self._request("GET", "/config")
async def get_states(self) -> list[dict[str, Any]]:
"""Get all entity states.
Raises ``HomeAssistantConnectionError`` when the response isn't the
JSON array ``/states`` always returns on success -- including
``_request``'s own empty-dict fallback for an unparseable body.
Silently returning ``[]`` here would let a genuine fetch failure
masquerade as "this instance has zero entities", which no real,
running Home Assistant instance produces; callers that need to
verify something against the live entity set (e.g. a bulk-control
safety check) would otherwise treat that failure as "verified,
nothing to worry about" instead of "could not verify".
"""
logger.debug("Fetching all entity states")
result = await self._request("GET", "/states")
if isinstance(result, list):
return result
raise HomeAssistantConnectionError(
f"Home Assistant /states returned an unexpected response shape: "
f"{type(result).__name__}"
)
async def get_entity_state(self, entity_id: str) -> dict[str, Any]:
"""
Get specific entity state.
Args:
entity_id: Entity ID (e.g., 'light.living_room')
Returns:
Entity state data
"""
logger.debug(f"Fetching state for entity: {entity_id}")
return await self._request("GET", f"/states/{entity_id}")
async def call_service(
self,
domain: str,
service: str,
data: dict[str, Any] | None = None,
return_response: bool = False,
) -> list[dict[str, Any]] | dict[str, Any]:
"""
Call Home Assistant service.
Args:
domain: Service domain (e.g., 'light', 'climate')
service: Service name (e.g., 'turn_on', 'set_temperature')
data: Optional service data
return_response: If True, returns the service response data (for services
that support SupportsResponse.ONLY or SupportsResponse.OPTIONAL)
Returns:
Service response data - list of affected states normally, or dict with
service response if return_response=True
"""
logger.debug(
f"Calling service {domain}.{service} (return_response={return_response})"
)
payload = data or {}
# Build query params for return_response
params = {}
if return_response:
params["return_response"] = "true"
result = await self._request(
"POST",
f"/services/{domain}/{service}",
json=payload,
params=params if params else None,
)
# When return_response is True, HA returns a dict with service_response key
if return_response:
if isinstance(result, dict):
return result
return {"service_response": result}
# Normal behavior: return list of affected states
if isinstance(result, list):
return result
else:
return []
async def get_services(self) -> dict[str, Any]:
"""Get all available services."""
logger.debug("Fetching available services")
return await self._request("GET", "/services")
async def get_logbook(
self,
entity_id: str | None = None,
start_time: str | None = None,
end_time: str | None = None,
) -> list[dict[str, Any]]:
"""
Get logbook entries.
Args:
entity_id: Optional entity ID to filter
start_time: Optional start time (ISO format) - used as URL path component
end_time: Optional end time (ISO format) - used as query parameter
Returns:
Logbook entries
"""
logger.debug(
f"Fetching logbook entries for entity: {entity_id}, start: {start_time}, end: {end_time}"
)
# Build endpoint - start_time goes in URL path if provided
if start_time:
endpoint = f"/logbook/{start_time}"
else:
endpoint = "/logbook"
# Build query parameters
params = {}
if entity_id:
params["entity"] = entity_id
if end_time:
params["end_time"] = end_time
result = await self._request("GET", endpoint, params=params)
if isinstance(result, list):
return result
else:
return []
async def fire_event(
self, event_type: str, data: dict[str, Any] | None = None
) -> dict[str, Any]:
"""
Fire Home Assistant event.
Args:
event_type: Event type name
data: Optional event data
Returns:
Event response
"""
logger.debug(f"Firing event: {event_type}")
payload = data or {}
return await self._request("POST", f"/events/{event_type}", json=payload)
async def render_template(self, template: str) -> str:
"""
Render Home Assistant template.
Args:
template: Template string
Returns:
Rendered template
"""
logger.debug("Rendering template")
payload = {"template": template}
response = await self._request("POST", "/template", json=payload)
result = response.get("result")
return str(result) if result is not None else ""
async def check_config(self) -> dict[str, Any]:
"""Check Home Assistant configuration."""
logger.debug("Checking configuration")
return await self._request("POST", "/config/core/check_config")
async def get_error_log(self) -> str:
"""Get Home Assistant error log.
Three-way branch depending on how this client reaches HA:
- **Addon context** (``is_running_in_addon()`` True — i.e.
``SUPERVISOR_TOKEN`` is set, meaning this process is the
ha-mcp add-on container talking to the Supervisor sibling):
go direct to Supervisor REST at
``http://supervisor/core/logs``.
- **External client → HAOS/Supervised** (``is_running_in_addon()``
False AND ``hassio`` is listed in HA's loaded components): use
the HA Core hassio proxy at ``/api/hassio/core/logs`` with the
user LLA. ``/api/error_log`` is unregistered by design on
Supervised installs — HA Core's ``bootstrap.py:646-671`` sets
``err_log_path = None`` when ``SUPERVISOR`` is in the env, so
``hass.data[DATA_LOGGING]`` is never populated and the
``APIErrorLog`` view (``api/__init__.py:89-90``) never registers.
The hassio proxy reaches the same underlying log stream.
- **External client → Container/pip HA** (neither of the above):
keep the historical ``/api/error_log`` proxy path.
The middle branch was discovered by the HAOS E2E tier (#1326): the
test harness runs ha-mcp externally against a booted HAOS, hits
the unregistered endpoint, and the old binary branch surfaced as
a confusing 404. Verified end-to-end with the user's real HAOS
and against HA Core source.
Raises:
HomeAssistantAuthError: 401, or empty ``SUPERVISOR_TOKEN`` on
the addon branch.
HomeAssistantAPIError: 403 (role too low — addon needs
``hassio_role: manager``), 404, other non-2xx.
HomeAssistantConnectionError: Network, timeout, or transport
error.
"""
if is_running_in_addon():
logger.debug("Fetching error log via Supervisor direct (core service)")
# An explicit `lines` is required: without it Supervisor applies its
# 100-line default, which is far too short a slice to tell what keeps
# repeating. `_get_supervisor_log` plumbs the same parameter for the
# same reason (#1734).
return await self._supervisor_logs_get("core", lines=_ERROR_LOG_LINES)
if await self._is_supervised_install():
logger.debug(
"Fetching error log via HA Core /hassio/core/logs proxy (supervised)"
)
raw_response = await self._raw_request(
"GET",
f"/hassio/core/logs?lines={_ERROR_LOG_LINES}",
headers={"Accept": "text/plain"},
)
return raw_response.text
logger.debug("Fetching error log via HA Core proxy (Container/pip)")
raw_response = await self._raw_request(
"GET", "/error_log", headers={"Accept": "text/plain"}
)
return raw_response.text
async def _is_supervised_install(self) -> bool:
"""Detect whether the target HA is a Supervised / HAOS install.
Probes ``/api/config`` once per client instance and returns
``"hassio" in components``. Cached for the session lifetime on
BOTH definite outcomes (True or False), since a successful
``/api/config`` response with or without ``hassio`` is a
definitive signal — HA's loaded-components set doesn't change
between Supervised and Container at runtime.
Cache is NOT poisoned on probe failure: a transient network
glitch or HTTP error returns False without setting the cache,
so the next call re-probes. This is the only path that
intentionally fails open — caller proceeds on the historical
Container branch.
A 401 is deliberately excluded from that fail-open: it is a
definitive answer about the credential rather than a transient
glitch, and swallowing it strands exactly the install class this
probe exists for. Failing open sends a Supervised caller down
the Container branch to ``/api/error_log``, which HA Core never
registers under ``SUPERVISOR`` (see ``get_error_log``), so the
auth failure resurfaces as a 404 and the caller answers with
connection advice instead of "re-create the LLAT". Letting
``HomeAssistantAuthError`` propagate reaches the auth handler
directly. Transport / HTTP fail-open is unchanged.
Connection / HTTP errors are caught explicitly; runtime bugs
(TypeError, AttributeError) and BaseException derivatives
(KeyboardInterrupt, CancelledError) deliberately propagate so
they're not silenced as "not supervised".
"""
if self._supervised_detected is not None:
return self._supervised_detected
try:
config = await self._request("GET", "/config")
except (
HomeAssistantAPIError,
HomeAssistantConnectionError,
httpx.HTTPError,
TimeoutError,
) as exc:
# Fail-open on transport / HTTP-layer failures only.
# HomeAssistantAuthError is deliberately absent: a 401 is a
# definitive verdict on the credential, and failing open on
# it routes a Supervised caller to /api/error_log — a route
# that does not exist there — turning the auth error into a
# 404 (see the docstring).
# Logged at WARNING so it's visible at default log levels
# without spamming on every call (probe runs at most once
# per session per outcome).
logger.warning(
"Supervised-install probe failed (fail-open to non-supervised): %r",
exc,
)
return False
components = config.get("components", []) if isinstance(config, dict) else []
is_supervised = isinstance(components, list) and "hassio" in components
self._supervised_detected = is_supervised
return is_supervised
async def get_addon_logs(self, slug: str, lines: int | None = None) -> str:
"""Fetch an add-on's container logs.
Branch on ``is_running_in_addon()``, which requires a truthy
``SUPERVISOR_TOKEN`` and excludes ``HA_MCP_EMBEDDED``: inside the app
(add-on) container goes directly to the Supervisor
REST API at ``http://supervisor/addons/{slug}/logs`` with the
Supervisor token. The HA Core proxy at
``/api/hassio/addons/{slug}/logs`` rejects this token+path combination
on current HA Core releases (see #1116) — the direct path bypasses
HA Core entirely and is the documented Supervisor contract.
On non-addon installs (Docker, pyinstaller, pip pointing at a normal
HA URL), falls back to the HA Core proxy path. That path requires an
admin LLA but works fine when not invoked from the add-on container.
``lines`` sets the journald window Supervisor serves via its
``?lines=`` query param (supervisor/api/host.py). Without it,
Supervisor returns only its default window (``DEFAULT_LINES = 100``
in supervisor/api/const.py) — which silently capped every larger
caller-side limit before this param existed. Both branches carry
it: the direct endpoint parses the query natively, and HA Core's
hassio proxy forwards ``request.query`` upstream
(homeassistant/components/hassio/http.py).
Both branches return ``text/plain`` log content.
Raises:
HomeAssistantAuthError: 401 response, or ``SUPERVISOR_TOKEN`` empty
at call time on the addon branch.
HomeAssistantAPIError: 403 (unrecognized token, missing
``hassio_api``, or insufficient ``hassio_role``), 404
(unknown slug), or other non-2xx. The
``status_code`` attribute lets callers map to specific
suggestions.
HomeAssistantConnectionError: Network, timeout, or transport error.
"""
if is_running_in_addon():
return await self._get_addon_logs_via_supervisor(slug, lines=lines)
logger.debug(f"Fetching addon logs for slug={slug} via HA Core proxy")
response = await self._raw_request(
"GET",
f"/hassio/addons/{slug}/logs",
headers={"Accept": "text/plain"},
params={"lines": lines} if lines is not None else None,
)
return response.text
@staticmethod
def _supervisor_error_message(text_body: str, reason_phrase: str) -> str:
"""Extract a human message from a Supervisor 4xx/5xx body.
Supervisor returns ``{"result":"error","message":"..."}`` on some paths;
prefer that message, then fall back to the raw text, reason phrase, or a
placeholder.
"""
message = ""
try:
envelope = json.loads(text_body) if text_body else None
if isinstance(envelope, dict):
msg = envelope.get("message")
if isinstance(msg, str) and msg:
message = msg
except json.JSONDecodeError:
# Body wasn't a JSON envelope; fall back to raw text below.
pass
if not message:
message = text_body.strip() or reason_phrase or "<empty body>"
return message
async def _supervisor_logs_get(self, path: str, lines: int | None = None) -> str:
"""Fetch ``text/plain`` logs from a Supervisor REST endpoint.
``path`` is everything between ``http://supervisor/`` and ``/logs``:
- ``"addons/<slug>"`` for app (add-on) container logs
- ``"<service>"`` (where service ∈ {supervisor, host, core, dns, audio,
cli, multicast, observer}) for system-service logs
``lines`` maps to the endpoint's ``?lines=`` journald-window query
param; omitted → Supervisor's 100-line default window.
Bypasses ``HomeAssistantClient.httpx_client`` because that client targets
Home Assistant Core through ``http://supervisor/core/api``, while logs
belong to Supervisor at ``http://supervisor``. Both clients use the same
``SUPERVISOR_TOKEN``; the Core proxy requires ``homeassistant_api``, while
system-service and arbitrary app-log paths require ``hassio_api`` and
``hassio_role: manager``. The recognized-app-token exception is
``/addons/self/logs``.
Raises:
HomeAssistantAuthError: ``SUPERVISOR_TOKEN`` absent at call time,
or 401 from Supervisor.
HomeAssistantAPIError: 403 (unrecognized token, missing
``hassio_api``, or insufficient role), 404, other 4xx/5xx.
Parses Supervisor's ``{"result":"error","message":"..."}``
JSON envelope before
falling back to text body / reason phrase / placeholder.
HomeAssistantConnectionError: Timeout or transport error, with
distinct messages so callers can tell them apart.
"""
token = os.environ.get("SUPERVISOR_TOKEN", "")
if not token:
# The is_running_in_addon() gate already keys off SUPERVISOR_TOKEN
# being truthy, so a direct caller landing here without one is a
# detection/config mismatch — fail-fast with a distinct message
# so operators don't read it as "token rejected".
raise HomeAssistantAuthError(
f"Supervisor token absent at call time for /{path}/logs "
"(addon-mode gate fired but SUPERVISOR_TOKEN env var not set)"
)
relative_path = f"/{path}/logs"
logger.debug(
"Fetching %s%s via Supervisor direct (lines=%s)",
get_supervisor_base_url(),
relative_path,
lines,
)
try:
async with asyncio.timeout(self.timeout):
async with make_supervisor_httpx_client(
timeout=httpx.Timeout(self.timeout),
verify=self.verify_ssl,
) as client:
response = await client.get(
relative_path,
headers={"Accept": "text/plain"},
params={"lines": lines} if lines is not None else None,
)
except (TimeoutError, httpx.TimeoutException) as e:
raise HomeAssistantConnectionError(
f"Timeout fetching /{path}/logs from Supervisor after "
f"{self.timeout}s: {str(e) or type(e).__name__}"
) from e
except httpx.HTTPError as e:
raise HomeAssistantConnectionError(
f"Transport error fetching /{path}/logs from Supervisor: {e}"
) from e
if response.status_code == 401:
raise HomeAssistantAuthError(f"Invalid Supervisor token for /{path}/logs")
if response.status_code == 403:
# Supervisor uses 403 for an unrecognized app token, missing
# hassio_api permission, or a hassio_role that cannot access this
# endpoint. The default-to-manager role bump fixed #1116, but it is
# not the only possible cause.
logger.warning(
"Supervisor returned 403 for /%s/logs — check token, hassio_api, "
"and hassio_role (need 'manager')",
path,
)
raise HomeAssistantAPIError(
f"Supervisor forbids /{path}/logs (403) — token may be unrecognized, "
"app may lack hassio_api, or hassio_role may not allow this endpoint "
"(manager required)",
status_code=403,
response_data={"path": path},
)
if response.status_code >= 400:
text_body = response.text
message = self._supervisor_error_message(text_body, response.reason_phrase)
logger.warning(
"Supervisor returned %s for /%s/logs: %s",
response.status_code,
path,
message,
)
raise HomeAssistantAPIError(
f"API error: {response.status_code} - {message}",
status_code=response.status_code,
response_data={"message": text_body, "path": path},
)
return response.text
async def _get_addon_logs_via_supervisor(
self, slug: str, lines: int | None = None
) -> str:
"""Fetch app (add-on) container logs directly from Supervisor REST.
Distinct from ``tools_bug_report._fetch_addon_logs``: that auxiliary
helper uses the app self-service path ``/addons/self/logs`` and may skip
failures. This helper takes arbitrary slugs and surfaces failures because
callers (``ha_get_logs(source="supervisor", slug=...)``) need them.
Arbitrary app-log slugs require a recognized app token with ``hassio_api``
and ``hassio_role: manager``; ``/addons/self/logs`` bypasses the role and
API-permission checks but still requires a recognized app token.
Delegates to ``_supervisor_logs_get`` so error handling stays in
lockstep with ``_get_system_service_logs``.
"""
return await self._supervisor_logs_get(f"addons/{slug}", lines=lines)
async def _get_system_service_logs(
self, service: str, lines: int | None = None
) -> str:
"""Fetch HA system-service logs.
``service`` must be one of the eight Supervisor-managed services:
``supervisor``, ``host``, ``core``, ``dns``, ``audio``, ``cli``,
``multicast``, ``observer``. Caller is responsible for validating
``service``; this helper performs no validation, and unsupported paths
are rejected by the selected direct-Supervisor or Core-proxy route.
Branch on ``is_running_in_addon()`` — mirror of ``get_addon_logs``:
inside the app (add-on) container goes directly to Supervisor at
``http://supervisor/{service}/logs`` with the Supervisor token
(``hassio_api`` and ``hassio_role: manager`` required). On non-app
installs (Docker
without Supervisor, pyinstaller, pip pointing at a normal HA URL),
falls back to the HA Core proxy at ``/api/hassio/{service}/logs``.
All eight service slugs are whitelisted in HA Core's hassio proxy
(``homeassistant/components/hassio/http.py`` — ``PATHS_ADMIN``), so
an admin LLA is sufficient to reach any of them from outside the
app.
"""
if is_running_in_addon():
return await self._supervisor_logs_get(service, lines=lines)
logger.debug(f"Fetching {service} logs via HA Core proxy")
response = await self._raw_request(
"GET",
f"/hassio/{service}/logs",
headers={"Accept": "text/plain"},
params={"lines": lines} if lines is not None else None,
)
return response.text
async def test_connection(self) -> tuple[bool, str | None]:
"""
Test connection to Home Assistant.
Returns:
tuple: (success, error_message)
"""
try:
config = await self.get_config()
if config.get("location_name"):
logger.info(
f"Successfully connected to Home Assistant: {config['location_name']}"
)
return True, None
else:
return False, "Invalid response from Home Assistant"
except Exception as e:
# Intentional broad-catch: is_connected() contract maps any failure
# to (False, error_msg); styleguide § "broad except at top-level
# setup/teardown handlers" applies (connection probe is the analog).
logger.error(f"Failed to connect to Home Assistant: {e}")
return False, str(e)
# Automation Configuration Management
async def _resolve_automation_id(self, identifier: str) -> str:
"""
Convert entity_id to unique_id if needed, or return unique_id as-is.
Args:
identifier: Either entity_id (automation.xxx) or unique_id
Returns:
The unique_id for configuration API
Raises:
HomeAssistantAPIError: If automation not found
"""
# If it looks like an entity_id, convert to unique_id
if identifier.startswith("automation."):
try:
state = await self.get_entity_state(identifier)
unique_id = state.get("attributes", {}).get("id")
if not unique_id:
raise HomeAssistantAPIError(
f"Automation {identifier} has no unique_id attribute",
status_code=404,
)
logger.debug(
f"Converted entity_id {identifier} to unique_id {unique_id}"
)
return str(unique_id)
except HomeAssistantError as e:
raise HomeAssistantAPIError(
f"Failed to resolve automation {identifier}: {str(e)}",
status_code=404,
) from e
else:
# Assume it's already a unique_id
return identifier
async def get_automation_config(self, identifier: str) -> dict[str, Any]:
"""
Get automation configuration by unique_id or entity_id.
Args: