forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools_addons.py
More file actions
3806 lines (3488 loc) · 144 KB
/
Copy pathtools_addons.py
File metadata and controls
3806 lines (3488 loc) · 144 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
"""
App (add-on) management tools for Home Assistant MCP Server.
Provides tools to manage apps through Supervisor and to call app web APIs using
the applicable route: an explicit container port, direct sibling ingress in app
mode, or Home Assistant Core's Ingress proxy in non-app modes.
Note: These tools only work with Home Assistant OS or Supervised installations.
"""
import asyncio
import json
import logging
import re
import ssl
import time
from typing import Annotated, Any, ClassVar, Literal, NoReturn
from urllib.parse import unquote, urlsplit
import httpx
from fastmcp.exceptions import ToolError
from pydantic import Field
from ha_mcp._vendor import websockets
from ha_mcp._vendor.websockets.asyncio.client import ClientConnection
from .._version import is_running_in_addon
from ..client.rest_client import (
HomeAssistantAPIError,
HomeAssistantClient,
HomeAssistantCommandError,
HomeAssistantCommandNotSent,
HomeAssistantCommandTimeout,
HomeAssistantConnectionError,
_is_ssl_error,
)
from ..client.supervisor_client import make_supervisor_httpx_client
from ..errors import (
ErrorCode,
create_error_response,
create_validation_error,
)
from ..redaction import (
collect_addon_secret_values,
redact_addon_options,
redaction_enabled,
register_known_secret_values,
sentinel_option_keys,
sentinel_replacement,
)
from ..utils.python_sandbox import (
PythonSandboxError,
format_sandbox_error,
safe_execute_expression,
)
from .helpers import (
exception_to_structured_error,
log_tool_usage,
raise_tool_error,
validate_identifier_not_empty,
)
from .util_helpers import ANSI_ESCAPE_RE, JSON_STRING_COERCION
logger = logging.getLogger(__name__)
# Maximum response size to return from app (add-on) API calls (50 KB)
_MAX_RESPONSE_SIZE = 50 * 1024
# Supervisor is local to the app network, so connection acquisition should
# remain short even when an app operation needs a multi-minute response budget.
_SUPERVISOR_ACQUIRE_TIMEOUT = 10.0
_SUPERVISOR_AVAILABILITY_SUGGESTION = (
"Check Home Assistant connection and Supervisor availability"
)
_SUPERVISOR_RESPONSE_TRUNCATION_SUFFIX = (
f"\n[Supervisor response truncated to {_MAX_RESPONSE_SIZE // 1024} KiB]"
)
# Hard safety cap on WebSocket messages collected per call. `message_limit`
# can lower this but never raise it.
_MAX_WS_MESSAGES = 1000
# Substrings that flag a WebSocket message as "signal" for the summarize pass.
# Keep conservative: false negatives get elided, false positives just mean
# no elision. Case-insensitive match on the JSON-stringified message.
_SIGNAL_PATTERNS = re.compile(
r"(?:^|[^A-Za-z])(INFO|WARN(?:ING)?|ERROR|FATAL|FAIL(?:ED|URE)?|EXCEPTION|"
r"TRACEBACK|Configuration is valid|Successfully|unsuccessful|exit|"
r"returncode|Compiling|Linking)",
re.IGNORECASE,
)
# Consecutive non-signal messages needed to trigger elision. Below this,
# the run passes through untouched.
_SUMMARIZE_RUN_THRESHOLD = 10
# Messages preserved verbatim at each end of an elided run for context.
_SUMMARIZE_CONTEXT_KEEP = 2
def _slice_ws_messages(
messages: list[Any],
offset: int,
limit: int | None,
) -> tuple[list[Any], dict[str, Any]]:
"""Apply offset/limit to a collected WebSocket message list.
Returns ``(sliced_messages, pagination_metadata)``. Pagination metadata
is always returned so the response shape is stable regardless of whether
offset/limit were applied.
"""
total_collected = len(messages)
offset = max(offset, 0)
if offset > total_collected:
sliced: list[Any] = []
elif limit is None:
sliced = messages[offset:]
else:
limit = max(limit, 0)
sliced = messages[offset : offset + limit]
pagination: dict[str, Any] = {
"total_collected": total_collected,
"offset": offset,
"returned": len(sliced),
}
if limit is not None:
pagination["limit"] = limit
return sliced, pagination
def _is_signal_message(msg: Any) -> bool:
"""Return True if ``msg`` looks like a log line or terminal event worth keeping.
The heuristic errs toward keeping messages — false positives just mean
a run doesn't get elided.
"""
if isinstance(msg, (dict, list)):
serialized = json.dumps(msg, default=str)
else:
serialized = str(msg)
return bool(_SIGNAL_PATTERNS.search(serialized[:2000]))
def _summarize_ws_messages(
messages: list[Any],
*,
run_threshold: int = _SUMMARIZE_RUN_THRESHOLD,
context_keep: int = _SUMMARIZE_CONTEXT_KEEP,
) -> tuple[list[Any], dict[str, Any]]:
"""Collapse runs of non-signal WebSocket messages into elision markers.
Each run of ≥ ``run_threshold`` consecutive non-signal entries becomes:
``context_keep`` originals, one elision dict
``{"elided": N, "note": "..."}``, then ``context_keep`` originals.
Signal messages always pass through unchanged.
"""
result: list[Any] = []
run_start: int | None = None
elided_total = 0
def flush(run_end: int) -> None:
nonlocal elided_total
assert run_start is not None
run_len = run_end - run_start
if run_len >= run_threshold:
result.extend(messages[run_start : run_start + context_keep])
elided_count = run_len - 2 * context_keep
result.append(
{
"elided": elided_count,
"note": (
f"{elided_count} non-signal messages elided; "
"pass summarize=False for full output"
),
}
)
result.extend(messages[run_end - context_keep : run_end])
elided_total += elided_count
else:
result.extend(messages[run_start:run_end])
for i, msg in enumerate(messages):
if _is_signal_message(msg):
if run_start is not None:
flush(i)
run_start = None
result.append(msg)
elif run_start is None:
run_start = i
if run_start is not None:
flush(len(messages))
return result, {
"original_count": len(messages),
"summarized_count": len(result),
"elided_count": elided_total,
}
def _apply_response_transform(response: Any, expr: str) -> Any:
"""Run a sandboxed ``python_transform`` expression against ``response``.
Exposes the value to the expression as ``response``. Supports both
in-place mutation and reassignment (``response = [...]``). Raises
ToolError with VALIDATION_FAILED on sandbox errors so the agent gets
a structured code it can react to.
"""
try:
return safe_execute_expression(expr, {"response": response}, "response")
except PythonSandboxError as e:
message, suggestions = format_sandbox_error(e, expr, variable_name="response")
raise_tool_error(
create_error_response(
ErrorCode.VALIDATION_FAILED,
message,
context={"expression_preview": expr[:200]},
suggestions=suggestions,
)
)
def _merge_options(base: dict, override: dict) -> dict:
"""Merge caller options into current options with one-level deep merge.
Top-level scalar values are replaced. Top-level dict values are merged
one level deep so callers can update a single nested field (e.g.
``{"ssh": {"sftp": True}}``) without losing sibling fields.
"""
merged = dict(base)
for key, value in override.items():
if isinstance(value, dict) and isinstance(merged.get(key), dict):
merged[key] = {**merged[key], **value}
else:
merged[key] = value
return merged
# Supervisor's per-job-group rejection, matched case-insensitively, plus the
# bounded window and backoff used to ride it out. See _supervisor_api_call.
# The "for job group" tail is load-bearing: JobGroup.acquire raises
# "Another job is running for job group <name>" for the transient per-app
# collision, while the job-level JobConcurrency.REJECT path raises a bare
# "Another job is running" for long operations (OS update, data-disk wipe)
# that must NOT be retried on this schedule.
_JOB_COLLISION_MARKER = "another job is running for job group"
_JOB_COLLISION_RETRY_WINDOW = 60.0
_JOB_COLLISION_RETRY_INITIAL_DELAY = 1.0
_JOB_COLLISION_RETRY_MAX_DELAY = 5.0
# Matches Supervisor's canonical app slug grammar. A whole-segment "." or
# ".." also matches that grammar, but is not a valid identifier here because
# an HTTP client can normalize it as path traversal.
_SUPERVISOR_SLUG_PATTERN = re.compile(r"[-_.A-Za-z0-9]+\Z")
def _is_valid_supervisor_slug(value: str) -> bool:
"""Return whether a value is safe as one Supervisor path segment."""
return (
value not in {".", ".."}
and _SUPERVISOR_SLUG_PATTERN.fullmatch(value) is not None
)
def _validate_supervisor_slug(value: str, parameter: str = "slug") -> None:
"""Reject values that could escape a Supervisor path segment."""
if _is_valid_supervisor_slug(value):
return
raise_tool_error(
create_validation_error(
f"{parameter!r} must be a valid Supervisor slug.",
parameter=parameter,
details=(
"Use only ASCII letters, numbers, hyphens, underscores, and periods; "
"the complete value cannot be '.' or '..'."
),
)
)
def _supervisor_rest_failure(
response: httpx.Response,
error: object,
response_data: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Normalize direct REST failure and retain 4xx/5xx status metadata."""
error_text = str(error)
result: dict[str, Any] = {"success": False, "error": error_text}
if response.is_error:
result["_status_code"] = response.status_code
if response_data is not None:
result["_response_data"] = response_data
return result
if not error_text.lower().startswith("command failed:"):
result["error"] = f"Command failed: {error_text}"
return result
def _supervisor_invalid_response(
response: httpx.Response,
error: object,
endpoint: str,
method: str,
) -> dict[str, Any]:
"""Classify a malformed direct response without replaying an accepted write."""
verb = method.upper()
if response.is_success and verb not in {"GET", "HEAD"}:
_raise_supervisor_write_outcome_unknown(
ErrorCode.SERVICE_CALL_FAILED,
f"Supervisor API {verb} {endpoint} returned an invalid success response; "
"the request outcome is unknown.",
endpoint,
verb,
)
return _supervisor_rest_failure(response, error)
def _bounded_supervisor_text(value: str) -> str:
"""Return model-safe Supervisor text, marking any truncation visibly."""
if len(value) <= _MAX_RESPONSE_SIZE:
return value
prefix_size = _MAX_RESPONSE_SIZE - len(_SUPERVISOR_RESPONSE_TRUNCATION_SUFFIX)
return value[:prefix_size] + _SUPERVISOR_RESPONSE_TRUNCATION_SUFFIX
def _bounded_supervisor_response_text(response: httpx.Response) -> str:
"""Return a model-safe Supervisor response body with visible truncation."""
return _bounded_supervisor_text(response.text.strip())
def _normalize_supervisor_rest_response(
response: httpx.Response,
endpoint: str,
method: str,
) -> dict[str, Any]:
"""Normalize a direct Supervisor response and retain write ambiguity."""
verb = method.upper()
write_outcome_unknown = verb not in {"GET", "HEAD"} and (
300 <= response.status_code < 400 or response.status_code >= 500
)
if write_outcome_unknown:
response_body = _bounded_supervisor_response_text(response)
_raise_supervisor_write_outcome_unknown(
ErrorCode.SERVICE_CALL_FAILED,
f"Supervisor API {verb} {endpoint} returned HTTP "
f"{response.status_code}; the request outcome is unknown.",
endpoint,
verb,
status_code=response.status_code,
response_body=response_body or None,
)
try:
payload = response.json()
except ValueError:
body = _bounded_supervisor_response_text(response)
error_message = (
body or f"Supervisor returned invalid JSON (HTTP {response.status_code})"
)
return _supervisor_invalid_response(response, error_message, endpoint, method)
if not isinstance(payload, dict):
return _supervisor_invalid_response(
response,
f"Supervisor returned an invalid response: {payload!r}",
endpoint,
method,
)
result_marker = payload.get("result")
valid_result_marker = isinstance(result_marker, str) and result_marker in {
"ok",
"error",
}
if response.is_success and not valid_result_marker:
return _supervisor_invalid_response(
response,
f"Supervisor returned an invalid success response: {payload!r}",
endpoint,
method,
)
if response.is_error or result_marker != "ok":
error = payload.get("message") or payload.get("error")
fallback = f"Supervisor API call failed (HTTP {response.status_code})"
return _supervisor_rest_failure(
response, error or fallback, response_data=payload
)
return {"success": True, "result": payload.get("data", {})}
def _supervisor_unknown_outcome_suggestions(endpoint: str, method: str) -> list[str]:
"""Return verification guidance suited to the Supervisor operation."""
action = endpoint.rstrip("/").rsplit("/", 1)[-1]
if action in {"restart", "rebuild"}:
return [
f"The {action} request may have been accepted; do not replay it "
"automatically",
f"Inspect Supervisor jobs and logs for {method} {endpoint} before "
"deciding whether manual action is needed",
]
return [
"The request may have been accepted; check the relevant durable state "
"with ha_get_app before retrying",
f"Check Supervisor jobs and logs for {method} {endpoint}",
]
def _raise_supervisor_write_outcome_unknown(
code: ErrorCode,
message: str,
endpoint: str,
method: str,
*,
status_code: int | None = None,
response_body: str | None = None,
) -> NoReturn:
"""Report an inconclusive Supervisor write without implying replay is safe."""
context: dict[str, Any] = {
"endpoint": endpoint,
"method": method,
"outcome": "unknown",
}
if status_code is not None:
context["status_code"] = status_code
if response_body:
context["response_body"] = response_body
raise_tool_error(
create_error_response(
code,
message,
context=context,
suggestions=_supervisor_unknown_outcome_suggestions(endpoint, method),
)
)
async def _supervisor_api_call_via_core(
client: HomeAssistantClient,
endpoint: str,
method: str,
wait_timeout: float,
websocket_kwargs: dict[str, Any],
) -> dict[str, Any]:
"""Call Supervisor through Core and preserve ambiguous write outcomes."""
verb = method.upper()
try:
result = await client.send_websocket_message(
{
"type": "supervisor/api",
"_wait_timeout": wait_timeout,
**websocket_kwargs,
}
)
except HomeAssistantCommandNotSent:
raise
except (HomeAssistantCommandTimeout, HomeAssistantConnectionError) as exc:
if verb not in {"GET", "HEAD"}:
code = (
ErrorCode.TIMEOUT_OPERATION
if isinstance(exc, HomeAssistantCommandTimeout)
else ErrorCode.CONNECTION_FAILED
)
_raise_supervisor_write_outcome_unknown(
code,
f"Home Assistant WebSocket returned no answer for Supervisor "
f"{verb} {endpoint}; the request outcome is unknown: {exc}",
endpoint,
verb,
)
raise
if (
verb not in {"GET", "HEAD"}
and result.get("success") is False
and result.get("error_code") == "unknown_error"
and str(result.get("error", "")).strip().casefold() == "command failed:"
):
_raise_supervisor_write_outcome_unknown(
ErrorCode.SERVICE_CALL_FAILED,
f"Home Assistant Core returned a blank Supervisor bridge error for "
f"{verb} {endpoint}; the request outcome is unknown.",
endpoint,
verb,
)
return result
async def _supervisor_api_call_once(
client: HomeAssistantClient,
endpoint: str,
method: str,
data: dict[str, Any] | None,
wait_timeout: float,
websocket_kwargs: dict[str, Any],
) -> dict[str, Any]:
"""Call Supervisor through the transport allowed for this install mode."""
if not is_running_in_addon():
return await _supervisor_api_call_via_core(
client, endpoint, method, wait_timeout, websocket_kwargs
)
request_kwargs: dict[str, Any] = {}
if data is not None or method.upper() == "POST":
# Supervisor's install/update/rebuild/uninstall handlers validate an
# optional schema by parsing request.json(), so bodyless POST actions
# must still carry an empty JSON object.
request_kwargs["json"] = data or {}
acquire_timeout = min(wait_timeout, _SUPERVISOR_ACQUIRE_TIMEOUT)
transport_timeout = httpx.Timeout(
wait_timeout,
connect=acquire_timeout,
pool=acquire_timeout,
)
try:
async with make_supervisor_httpx_client(
timeout=transport_timeout,
verify=client.verify_ssl,
) as supervisor_client:
response = await supervisor_client.request(
method,
endpoint,
**request_kwargs,
)
except (httpx.ConnectTimeout, httpx.PoolTimeout) as exc:
raise HomeAssistantConnectionError(
f"Supervisor API {method.upper()} {endpoint} could not start before "
f"the {acquire_timeout}s connection-acquisition timeout: {exc}"
) from exc
except httpx.TimeoutException as exc:
verb = method.upper()
if verb in {"GET", "HEAD"}:
raise HomeAssistantConnectionError(
f"Supervisor API {verb} {endpoint} request timeout after "
f"{wait_timeout}s"
) from exc
_raise_supervisor_write_outcome_unknown(
ErrorCode.TIMEOUT_OPERATION,
f"Supervisor API {verb} {endpoint} timed out after {wait_timeout}s; "
"the request outcome is unknown.",
endpoint,
verb,
)
except (httpx.RequestError, OSError) as exc:
verb = method.upper()
if verb not in {"GET", "HEAD"} and not isinstance(exc, httpx.ConnectError):
_raise_supervisor_write_outcome_unknown(
ErrorCode.CONNECTION_FAILED,
f"Supervisor API {verb} {endpoint} transport failed; "
f"the request outcome is unknown: {exc}",
endpoint,
verb,
)
raise HomeAssistantConnectionError(
f"Failed to connect to Supervisor API {endpoint}: {exc}"
) from exc
return _normalize_supervisor_rest_response(response, endpoint, method)
def _raise_supervisor_api_failure(
result: dict[str, Any],
endpoint: str,
) -> NoReturn:
"""Raise the structured exception represented by a non-retryable result."""
# Both transports land here, and both carry Supervisor's own text: the
# direct REST payload and the message Core relays over the WebSocket
# bridge. Bind the size once, where every failure passes.
error_text = _bounded_supervisor_text(
str(result.get("error", f"Supervisor API call failed: {endpoint}"))
)
status_code = result.get("_status_code")
response_data = result.get("_response_data")
if status_code == 401:
raise_tool_error(
create_error_response(
ErrorCode.AUTH_INVALID_TOKEN,
f"{error_text}. Supervisor rejected the app's managed token.",
context={"endpoint": endpoint, "status_code": 401},
suggestions=[
"Restart the ha-mcp app to obtain a fresh Supervisor-managed token",
"Check Supervisor logs for token validation failures",
],
)
)
if status_code == 404:
raise HomeAssistantAPIError(
error_text,
status_code=404,
response_data=response_data if isinstance(response_data, dict) else None,
)
if status_code == 403:
raise_tool_error(
create_error_response(
ErrorCode.AUTH_INSUFFICIENT_PERMISSIONS,
(
f"{error_text}. Supervisor denied the app request; HTTP 403 "
"can mean either token rejection or insufficient API role."
),
context={"endpoint": endpoint, "status_code": 403},
suggestions=[
"Restart the app to refresh its Supervisor-managed token",
"Check the ha-mcp app's hassio_api and hassio_role configuration",
"Check Supervisor logs for an invalid token or missing API permission",
],
)
)
if isinstance(status_code, int) and not error_text.lower().startswith(
"command failed:"
):
error_text = f"Command failed: {error_text}"
raise HomeAssistantCommandError(error_text)
def _supervisor_result_mapping(
result: dict[str, Any],
endpoint: str,
method: str,
) -> dict[str, Any]:
"""Require the mapping payload used by every supported Supervisor endpoint."""
payload = result.get("result", {})
if isinstance(payload, dict):
return payload
verb = method.upper()
message = _bounded_supervisor_text(
f"Supervisor API {verb} {endpoint} returned an invalid result payload: "
f"{payload!r}"
)
if verb not in {"GET", "HEAD"}:
_raise_supervisor_write_outcome_unknown(
ErrorCode.SERVICE_CALL_FAILED,
f"{message}; the request outcome is unknown.",
endpoint,
verb,
)
raise_tool_error(
create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
message,
context={"endpoint": endpoint, "method": verb},
)
)
raise AssertionError("unreachable: raise_tool_error always raises")
async def _supervisor_api_call(
client: HomeAssistantClient,
endpoint: str,
method: str = "GET",
data: dict[str, Any] | None = None,
timeout: int | None = None,
) -> dict[str, Any]:
"""Make a Supervisor API call through the supported install-mode transport.
App (add-on) installs use their manager-role token against Supervisor REST.
Other installs retain Home Assistant Core's ``supervisor/api`` WebSocket proxy.
Args:
client: Home Assistant client used for off-host WebSocket calls and
as the TLS-verification source for direct REST.
endpoint: Supervisor API endpoint (e.g., "/addons", "/addons/{slug}/info")
method: HTTP method (default "GET")
data: Optional request body data
timeout: Optional timeout override
A transient Supervisor job-group collision is retried while the
``_JOB_COLLISION_RETRY_WINDOW`` deadline remains. Individual transport
attempts retain their normal timeout, so total elapsed time can exceed it.
Returns:
``{"success": True, "result": ...}``. Every failure raises — this
never returns an error dict.
"""
try:
kwargs: dict[str, Any] = {"endpoint": endpoint, "method": method}
if data is not None:
kwargs["data"] = data
# On the WebSocket route, ``timeout`` tells the Supervisor proxy how
# long to wait on the underlying REST operation. On the direct route,
# only the local httpx timeout is needed. In both cases it must outlast
# a multi-minute app operation; the default local wait is only 30s.
wait_timeout = 30.0
if timeout is not None:
kwargs["timeout"] = timeout
wait_timeout = float(timeout) + 15.0
# Non-app deployments, including embedded mode, use the shared pooled
# Home Assistant Core WebSocket (issue #1813).
# App installs call Supervisor REST directly because its app-to-Core
# proxy rejects app-originated ``supervisor/api`` commands.
# Both transports feed the common retry and error-normalization path:
# direct 4xx/5xx responses retain status metadata, while WebSocket
# failures are classified from the returned message.
#
# Supervisor serialises jobs per app job group and rejects a
# state-changing call while a still-settling job (a watchdog restart,
# a prior start/stop, or a store reload) holds that group. The rejection
# happens before the job body runs, so retrying cannot double-execute.
# Each collision response checks the shared retry deadline before
# backing off. Individual attempts retain their transport timeout, so
# the final retry and total elapsed time may extend past that window.
# Any other failure raises immediately.
deadline = time.monotonic() + _JOB_COLLISION_RETRY_WINDOW
delay = _JOB_COLLISION_RETRY_INITIAL_DELAY
attempts = 0
while True:
attempts += 1
result = await _supervisor_api_call_once(
client,
endpoint,
method,
data,
wait_timeout,
kwargs,
)
if result.get("success"):
return {
"success": True,
"result": _supervisor_result_mapping(result, endpoint, method),
}
error_text = str(
result.get("error", f"Supervisor API call failed: {endpoint}")
)
if _JOB_COLLISION_MARKER not in error_text.lower():
_raise_supervisor_api_failure(result, endpoint)
# The marker test runs on the raw text; everything below reports
# it, so bind the size once the classification is settled.
error_text = _bounded_supervisor_text(error_text)
remaining = deadline - time.monotonic()
if remaining <= 0:
# The retry budget is exhausted; the group may be stuck or
# legitimately occupied by a long-running operation. Raise a
# ToolError here so the caller gets guidance about the busy
# job instead of the generic connectivity suggestion attached
# to other failures.
waited = _JOB_COLLISION_RETRY_WINDOW - remaining
logger.warning(
"Supervisor job group still busy on %s after %.0fs "
"(%d attempts); giving up: %s",
endpoint,
waited,
attempts,
error_text,
)
raise_tool_error(
create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
error_text,
context={
"endpoint": endpoint,
"attempts": attempts,
"waited_seconds": round(waited, 1),
},
suggestions=[
"Another job has held this app (add-on)'s job group for "
f"over {_JOB_COLLISION_RETRY_WINDOW:.0f}s — check "
"Supervisor logs for a stuck or long-running job",
"Retry once the in-flight app operation "
"(install, update, restart or backup) finishes",
],
)
)
logger.info(
"Supervisor job-group collision on %s; retrying in %.1fs (%s)",
endpoint,
delay,
error_text,
)
await asyncio.sleep(min(delay, remaining))
delay = min(delay * 2, _JOB_COLLISION_RETRY_MAX_DELAY)
except ToolError:
raise
except Exception as e:
logger.error(f"Error calling Supervisor API {endpoint}: {e}")
error_response = exception_to_structured_error(
e,
context={
"endpoint": endpoint,
"operation": f"Supervisor API {endpoint}",
"timeout_seconds": wait_timeout,
},
raise_error=False,
)
error_details = error_response.get("error")
if (
isinstance(error_details, dict)
and error_details.get("code") == ErrorCode.RESOURCE_NOT_FOUND.value
):
error_details["suggestion"] = _SUPERVISOR_AVAILABILITY_SUGGESTION
error_details["suggestions"] = [_SUPERVISOR_AVAILABILITY_SUGGESTION]
raise_tool_error(error_response)
return None # unreachable: raise_tool_error always raises
def _addon_connection_failure_suggestions(
client: HomeAssistantClient, port: int | None
) -> list[str]:
"""Suggestions for connect/timeout failures against an app (add-on).
Three modes — direct-port hits a container IP, the app-mode ingress
route hits a sibling container's ingress port, the off-host ingress route
hits HA Core. Each mode fails for different reasons, so suggest different
next steps.
"""
if port:
return [
"Check that the app (add-on) is running",
"Direct-port access requires the MCP host to share Home "
+ "Assistant's container network. On PyPI/uvx installs, drop "
+ "the 'port' parameter to route through Ingress instead.",
]
if is_running_in_addon():
return [
"The target app (add-on) container may not be reachable from this "
+ "MCP app. Check that the target app is running.",
"If the failure persists, the app (add-on) Docker network may be "
+ "unhealthy — try restarting the target app, then this "
+ "MCP app.",
]
return [
f"Verify Home Assistant is reachable at {client.base_url}",
"Check network connectivity from the MCP host to HA Core",
]
async def _create_ingress_session(client: HomeAssistantClient) -> str:
"""Create a Supervisor ingress session and return its token.
App mode uses a direct sibling-ingress route and never calls this helper.
Non-app deployments, including embedded mode, mint sessions through Home
Assistant Core's ``supervisor/api`` WebSocket command. The token is set as the
``ingress_session`` cookie on requests to Core's
``/api/hassio_ingress/<addon_token>/...`` endpoint, which Supervisor
validates before proxying to the app container. Sessions are valid for
approximately 15 minutes; a fresh one is minted per call.
"""
response = await _supervisor_api_call(
client, "/ingress/session", method="POST", data={}
)
session = response.get("result", {}).get("session")
if not isinstance(session, str) or not session:
raise_tool_error(
create_error_response(
ErrorCode.SERVICE_CALL_FAILED,
"Supervisor returned no ingress session token",
details=str(response),
)
)
return session
async def _resolve_http_route(
client: HomeAssistantClient,
addon: dict[str, Any],
normalized_path: str,
port: int | None,
) -> tuple[str, dict[str, str]]:
"""Pick the HTTP route shape based on `port` and install variant.
Three branches:
- `port` set → direct container port (`http://<ip>:<port>/...`), no
auth headers. Only reachable when the MCP host shares HA's container
network.
- Running as the HA app (add-on) (`is_running_in_addon()` true) → direct
`<addon_ip>:<addon_ingress_port>` with `X-Ingress-Path` and
`X-Hass-Source: core.ingress` headers. Routing through HA Core's
`/api/hassio_ingress/...` proxy regresses here because
`client.base_url` is `http://supervisor/core` (a Supervisor proxy
mount that demands `Authorization: Bearer $SUPERVISOR_TOKEN`).
- Off-host → HA Core ingress proxy at
`<base_url>/api/hassio_ingress/<token>/<path>` with `Cookie:
ingress_session=<token>`. Mints a fresh session per call.
"""
addon_name = addon.get("name", "")
headers: dict[str, str] = {}
if port:
addon_ip = addon.get("ip_address", "")
if not addon_ip:
raise_tool_error(
create_error_response(
ErrorCode.INTERNAL_ERROR,
f"App (add-on) '{addon_name}' is missing ip_address",
context={"slug": addon.get("slug"), "ip_address": addon_ip},
)
)
return f"http://{addon_ip}:{port}/{normalized_path}", headers
ingress_entry = addon.get("ingress_entry")
if not ingress_entry:
raise_tool_error(
create_error_response(
ErrorCode.INTERNAL_ERROR,
f"App (add-on) '{addon_name}' is missing ingress_entry",
context={"slug": addon.get("slug")},
)
)
if is_running_in_addon():
addon_ip = addon.get("ip_address", "")
ingress_port = addon.get("ingress_port")
if not addon_ip or not ingress_port:
raise_tool_error(
create_error_response(
ErrorCode.INTERNAL_ERROR,
f"App (add-on) '{addon_name}' is missing network info "
"(ip_address or ingress_port)",
context={
"slug": addon.get("slug"),
"ip_address": addon_ip,
"ingress_port": ingress_port,
},
)
)
# Sibling app (add-on) containers share the hassio bridge, so we hit the
# ingress port directly. The X-Ingress-Path / X-Hass-Source headers
# are what the app's nginx trusts as authenticated ingress source.
headers["X-Ingress-Path"] = ingress_entry
headers["X-Hass-Source"] = "core.ingress"
return (
f"http://{addon_ip}:{ingress_port}/{normalized_path}",
headers,
)
session = await _create_ingress_session(client)
base = client.base_url.rstrip("/")
headers["Cookie"] = f"ingress_session={session}"
return f"{base}{ingress_entry}/{normalized_path}", headers
async def _resolve_ws_route(
client: HomeAssistantClient,
addon: dict[str, Any],
normalized_path: str,
port: int | None,
) -> tuple[str, dict[str, str]]:
"""Pick the WebSocket route shape. Mirrors `_resolve_http_route`.
The app-mode and direct-port branches always speak `ws://` because
they hit the container directly. The off-host branch echoes
`client.base_url`'s scheme (so HTTPS-fronted HA gets `wss://`).
"""
addon_name = addon.get("name", "")
headers: dict[str, str] = {}
if port:
addon_ip = addon.get("ip_address", "")
if not addon_ip:
raise_tool_error(
create_error_response(
ErrorCode.INTERNAL_ERROR,
f"App (add-on) '{addon_name}' is missing ip_address",
context={"slug": addon.get("slug")},
)
)
return f"ws://{addon_ip}:{port}/{normalized_path}", headers
ingress_entry = addon.get("ingress_entry")
if not ingress_entry:
raise_tool_error(
create_error_response(
ErrorCode.INTERNAL_ERROR,
f"App (add-on) '{addon_name}' is missing ingress_entry",
context={"slug": addon.get("slug")},
)
)
if is_running_in_addon():
addon_ip = addon.get("ip_address", "")
ingress_port = addon.get("ingress_port")
if not addon_ip or not ingress_port:
raise_tool_error(
create_error_response(
ErrorCode.INTERNAL_ERROR,
f"App (add-on) '{addon_name}' is missing network info "
"(ip_address or ingress_port)",
context={
"slug": addon.get("slug"),
"ip_address": addon_ip,
"ingress_port": ingress_port,
},
)
)
headers["X-Ingress-Path"] = ingress_entry
headers["X-Hass-Source"] = "core.ingress"
return (
f"ws://{addon_ip}:{ingress_port}/{normalized_path}",
headers,
)
session = await _create_ingress_session(client)
parsed = urlsplit(client.base_url)
ws_scheme = "wss" if parsed.scheme == "https" else "ws"