From fbb6bea5dc6671422c4cea4fcbbee76c48550e4b Mon Sep 17 00:00:00 2001 From: eigger Date: Mon, 30 Nov 2026 19:38:44 +0900 Subject: [PATCH 1/3] Fix LLM draft validation and MCP schema compatibility --- README.ko.md | 6 +- README.md | 6 +- custom_components/ble_esl/llm_api.py | 128 ++++++++++++++++++----- tests/components/ble_esl/test_llm_api.py | 87 ++++++++++++++- 4 files changed, 189 insertions(+), 38 deletions(-) diff --git a/README.ko.md b/README.ko.md index 7c22936..fdf3695 100644 --- a/README.ko.md +++ b/README.ko.md @@ -98,11 +98,11 @@ data: ## AI 에이전트 (MCP) -이 통합은 **BLE ESL**이라는 LLM API를 등록합니다. 그래서 Home Assistant의 [Model Context Protocol Server](https://www.home-assistant.io/integrations/mcp_server/)로 연결한 AI 에이전트가 태그를 찾고 그림을 그릴 수 있습니다. 연결 방법은 두 가지이며, **A**는 이 통합이 지원하는 모든 Home Assistant 버전에서, **B**는 더 새로운 버전에서만 동작합니다. +이 통합은 **BLE ESL** LLM API를 등록합니다. [Model Context Protocol](https://www.home-assistant.io/integrations/mcp_server/) 통합(2026.10까지는 **Model Context Protocol Server**)을 추가한 뒤 다음 엔드포인트 중 하나로 연결하세요. -**A. 공용 엔드포인트 `/api/mcp`.** **설정 → 기기 및 서비스**에서 **Model Context Protocol Server**를 추가하고 **Assist**와 **BLE ESL**을 모두 선택합니다(다중 선택). 이 통합에는 옵션 화면이 없고 항목을 하나만 만들 수 있으므로, 이미 추가했다면 삭제한 뒤 다시 추가해야 선택을 바꿀 수 있습니다. 도구 이름에는 접두어가 붙습니다(예: `ble-esl__write_tag`). 이 엔드포인트 자체는 관리자를 요구하지 않지만, BLE ESL 도구가 관리자인지 확인하고 다른 사용자는 거부합니다. +**전용 엔드포인트 `/api/mcp/ble_esl` (권장).** 지원 최소 버전인 Home Assistant 2026.8.0부터 사용할 수 있습니다. 별도의 MCP 서버로 등록하며, 도구 이름에 접두어가 붙지 않고 관리자만 사용할 수 있습니다. -**B. 전용 엔드포인트 `/api/mcp/ble_esl`.** 이 통합이 지원하는 최소 버전인 Home Assistant 2026.8부터 사용할 수 있습니다. Model Context Protocol Server 통합이 추가되어 있어야 하지만 선택은 필요 없으며, Home Assistant가 관리자만 허용합니다. 클라이언트에 별도의 MCP 서버로 등록하세요. 도구 이름에 접두어가 붙지 않습니다. +**공용 엔드포인트 `/api/mcp`.** Home Assistant 2026.10부터 통합 옵션에서 노출할 API와 관리자 요구 여부를 바꿀 수 있습니다. 새 항목은 기본적으로 모든 API를 노출하고 관리자만 허용합니다. 기존 항목은 API 선택을 유지합니다. 2026.8–2026.9에서는 통합을 추가할 때 BLE ESL을 선택하고, 선택을 바꾸려면 항목을 삭제한 뒤 다시 추가하세요. 2026.11 이전에는 여러 API를 노출할 때 접두어가 붙습니다(예: `ble-esl__write_tag`). 2026.11부터 도구 이름이 충돌할 때만 네임스페이스가 붙으며 공용 엔드포인트에 읽기 전용 설정도 사용할 수 있습니다. 설정에 따라 관리자 접근이 필요하거나 쓰기 도구가 제외될 수 있습니다. BLE ESL 도구 자체도 관리자를 요구합니다. 두 방법 모두 Home Assistant의 전체 URL(예: `https://ha.example.com/api/mcp/ble_esl`)을 쓰고 **관리자**로 로그인해야 합니다. MCP 인증 규격을 지원하는 클라이언트는 Home Assistant 로그인 페이지를 열고(Home Assistant가 `/.well-known/oauth-authorization-server`와 `/.well-known/oauth-protected-resource`를 제공합니다), 그렇지 않으면 장기 액세스 토큰을 `Authorization: Bearer <토큰>`으로 보냅니다. 클라우드에서 동작하는 클라이언트는 Home Assistant에 인터넷으로 접속할 수 있어야 합니다. diff --git a/README.md b/README.md index bb4c0a5..2bfa9af 100644 --- a/README.md +++ b/README.md @@ -98,11 +98,11 @@ The tag refreshes in a few seconds. To preview the layout without sending it, ad ## AI agents (MCP) -The integration registers an LLM API named **BLE ESL**, so an AI agent connected through Home Assistant's [Model Context Protocol Server](https://www.home-assistant.io/integrations/mcp_server/) can find your tags and draw on them. Connect it in one of two ways; **A** works on every Home Assistant release this integration supports, **B** needs a newer one. +The integration registers an LLM API named **BLE ESL**. Add Home Assistant's [Model Context Protocol](https://www.home-assistant.io/integrations/mcp_server/) integration (called **Model Context Protocol Server** through 2026.10), then connect using one of these endpoints. -**A. Shared endpoint `/api/mcp`.** In **Settings → Devices & services**, add **Model Context Protocol Server** and select both **Assist** and **BLE ESL** (the selection is multiple choice). The integration has no options flow and allows a single entry, so if it is already added, delete it and add it again to change the selection. The tools then carry a prefix (for example `ble-esl__write_tag`). This endpoint does not itself require an administrator; the BLE ESL tools check it and refuse everyone else. +**Dedicated endpoint `/api/mcp/ble_esl` (recommended).** Available from Home Assistant 2026.8.0, the minimum supported version. Register it as a separate MCP server. Home Assistant restricts it to administrators and exposes tool names without a prefix. -**B. Dedicated endpoint `/api/mcp/ble_esl`.** Available from Home Assistant 2026.8, the minimum this integration supports. It needs the Model Context Protocol Server integration to be added, but no selection, and Home Assistant restricts it to administrators. Register it in your client as a separate MCP server, with the tool names unprefixed. +**Shared endpoint `/api/mcp`.** From Home Assistant 2026.10, the integration's options let you select exposed APIs and require administrators. New entries expose all APIs and require administrators by default. Existing entries retain their API selections. On 2026.8–2026.9, select BLE ESL when adding the integration. To change the selection on those versions, delete and re-add the entry. Before 2026.11, names are prefixed when multiple APIs are exposed (for example `ble-esl__write_tag`). From 2026.11, names are namespaced only when they collide, and a read-only option is available for the shared endpoint. Depending on the settings, administrator access may be required or write tools may be omitted. BLE ESL tools themselves also require an administrator. For both, use the full URL of your Home Assistant (for example `https://ha.example.com/api/mcp/ble_esl`) and sign in as an **administrator**: either an MCP client that supports the MCP authorization spec opens the Home Assistant login page (Home Assistant serves `/.well-known/oauth-authorization-server` and `/.well-known/oauth-protected-resource`), or you send a long-lived access token as `Authorization: Bearer `. A client hosted in the cloud needs your Home Assistant to be reachable from the internet. diff --git a/custom_components/ble_esl/llm_api.py b/custom_components/ble_esl/llm_api.py index 05f7f41..7ebabb4 100644 --- a/custom_components/ble_esl/llm_api.py +++ b/custom_components/ble_esl/llm_api.py @@ -726,11 +726,11 @@ class WriteTagTool(llm.Tool): "rotate", default=0, description="Degrees 0/90/180/270; 90 and 270 swap the canvas width and height", - ): vol.All(vol.Coerce(int), vol.In((0, 90, 180, 270))), - vol.Optional("background", default="white"): vol.In(BACKGROUNDS), + ): vol.All(vol.Coerce(int), vol.In([0, 90, 180, 270])), + vol.Optional("background", default="white"): vol.In(list(BACKGROUNDS)), vol.Optional( "mode", default="write", description="write or guarded (see description)" - ): vol.In(("write", "guarded")), + ): vol.In(["write", "guarded"]), vol.Optional("dry_run", default=False): cv.boolean, vol.Optional( "wait", default=True, description="Wait for the transfer to finish" @@ -1157,7 +1157,10 @@ def _short_text(node: Any) -> bool: def _unsupported( - env: Any, text: str, known: frozenset[str] | set[str] = frozenset() + env: Any, + text: str, + known: frozenset[str] | set[str] = frozenset(), + tree: Any = None, ) -> tuple[list[str], list[str]]: """(unknown names, what draft_automation does not evaluate) of a template (parse only). @@ -1175,7 +1178,8 @@ def _unsupported( if len(text) > MAX_PARSED_CHARS: return [], [f"a template of over {MAX_PARSED_CHARS} characters (too long to check)"] try: - tree = env.parse(text) + if tree is None: + tree = env.parse(text) except TemplateSyntaxError: return [], [] found: list[str] = [] @@ -1244,27 +1248,61 @@ def named(args: list[Any], allowed: frozenset[str], what: str) -> None: return unknown, found -def _neutralize(env: Any, value: Any) -> Any: - """A copy of `value` where templates that are not evaluated are replaced by a plain word. - - Home Assistant compiles every template while it validates an automation; this keeps - the ones that were not allowlisted away from it. Blocking (parses): executor. - """ - if isinstance(value, str): - return "unchecked" if template_syntax(value) and _unsupported(env, value)[1] else value - if isinstance(value, list): - return [_neutralize(env, item) for item in value] - if isinstance(value, dict): - return {key: _neutralize(env, item) for key, item in value.items()} - return value +def _validation_copy( + env: Any, automation: dict[str, Any], drop_payload: bool +) -> tuple[dict[str, Any], list[str], list[str]]: + """Replace unsafe expressions before HA validation and report every replacement.""" + warnings: list[str] = [] + errors: list[str] = [] + def neutralize(value: Any, path: str) -> Any: + if isinstance(value, str) and template_syntax(value): + tree = None + if len(value) <= MAX_PARSED_CHARS: + try: + tree = env.parse(value) + except TemplateSyntaxError: + return value # Home Assistant reports syntax errors. + _, reasons = _unsupported(env, value, tree=tree) + if reasons: + # Parsing is safe; compiling could evaluate constant expressions. Check + # filter and test names without compiling or evaluating the expression. + if len(value) <= MAX_PARSED_CHARS: + try: + for node in tree.find_all((jinja_nodes.Filter, jinja_nodes.Test)): + registry = ( + env.filters if isinstance(node, jinja_nodes.Filter) else env.tests + ) + if node.name not in registry: + kind = "filter" if isinstance(node, jinja_nodes.Filter) else "test" + errors.append(f"{path}: unknown {kind} `{node.name}`") + except TemplateSyntaxError as err: + errors.append(f"{path}: template syntax error: {err}") + warnings.append( + f"{path}: original template was not checked by Home Assistant " + f"validation ({', '.join(reasons)}); review it" + ) + return "{{ 0 }}" + return value + if isinstance(value, list): + return [neutralize(item, f"{path}[{index}]") for index, item in enumerate(value)] + if isinstance(value, dict): + result: dict[Any, Any] = {} + reserved = set(value) + for index, (key, item) in enumerate(value.items()): + checked = neutralize(key, f"{path}.[key {key!r}]") if isinstance(key, str) else key + if checked != key: + checked = f"__unchecked_key_{index}__" + while checked in reserved or checked in result: + checked += "_" + result[checked] = neutralize(item, f"{path}.{key}" if path else str(key)) + return result + return value -def _validation_copy(env: Any, automation: dict[str, Any], drop_payload: bool) -> dict[str, Any]: - """The automation as Home Assistant may safely validate it (never compiles risky text).""" - copy = _neutralize(env, automation) + copy = neutralize(automation, "") if drop_payload: copy["actions"][-1]["data"]["payload"] = [] - return copy + return copy, errors, warnings def _template_policy(value: Any, path: str = "payload") -> list[str]: @@ -1492,7 +1530,9 @@ def _missing_entities(hass: HomeAssistant, value: Any, path: str) -> list[str]: for key, item in value.items(): here = f"{path}.{key}" if key == "entity_id": - for entity_id in [item] if isinstance(item, str) else (item or []): + for entity_id in ( + [item] if isinstance(item, str) else (item if isinstance(item, list) else []) + ): if ( isinstance(entity_id, str) and _ENTITY_ID.match(entity_id) @@ -1616,13 +1656,13 @@ class DraftAutomationTool(llm.Tool): vol.Optional("description", description="Description of the automation"): cv.string, vol.Optional( "mode", default="write", description="write or guarded: which action it calls" - ): vol.In(("write", "guarded")), + ): vol.In(["write", "guarded"]), vol.Optional( "rotate", default=0, description="Degrees 0/90/180/270; 90 and 270 swap the canvas width and height", - ): vol.All(vol.Coerce(int), vol.In((0, 90, 180, 270))), - vol.Optional("background", default="white"): vol.In(BACKGROUNDS), + ): vol.All(vol.Coerce(int), vol.In([0, 90, 180, 270])), + vol.Optional("background", default="white"): vol.In(list(BACKGROUNDS)), vol.Optional( "preview", default=False, @@ -1716,10 +1756,38 @@ async def async_call( "No triggers: the automation never runs by itself. Pass `triggers`, or a person " "has to add them in Home Assistant." ) - safe = await hass.async_add_executor_job(_validation_copy, env, automation, refused) + safe, validation_errors, validation_warnings = await hass.async_add_executor_job( + _validation_copy, env, automation, refused + ) + errors += validation_errors + warnings += validation_warnings if problem := await _validate_automation(hass, safe): errors.append(f"Home Assistant rejects the automation: {problem}") + def scalar_entity_paths(value: Any, path: str) -> list[str]: + if isinstance(value, list): + return [ + p + for index, item in enumerate(value) + for p in scalar_entity_paths(item, f"{path}[{index}]") + ] + if isinstance(value, dict): + paths: list[str] = [] + kind = value.get("trigger", value.get("platform", value.get("condition"))) + if kind in ("state", "numeric_state") and isinstance( + value.get("entity_id"), (int, float, bool) + ): + paths.append(f"{path}.entity_id: invalid entity ID value") + if "conditions" in value: + paths.extend(scalar_entity_paths(value["conditions"], f"{path}.conditions")) + if "triggers" in value: + paths.extend(scalar_entity_paths(value["triggers"], f"{path}.triggers")) + return paths + return [] + + errors += scalar_entity_paths(triggers, "triggers") + errors += scalar_entity_paths(conditions, "conditions") + result: dict[str, Any] = { "status": "invalid" if errors else "ok", "tag": data.address, @@ -1740,8 +1808,14 @@ async def async_call( warnings += await self._preview(hass, entry, rendered, args, result) result["errors"] = errors[:20] + if len(errors) > 20: + result["errors"].append(f"{len(errors) - 20} more errors omitted") if warnings: result["warnings"] = warnings[:20] + if len(warnings) > 20: + result["warnings"].append( + f"{len(warnings) - 20} more warnings omitted; validation was incomplete" + ) result["note"] = ( "Nothing was saved. The saved automation runs in trusted mode, so a person should " "read automation_yaml, then create it in Home Assistant (Settings > Automations & " diff --git a/tests/components/ble_esl/test_llm_api.py b/tests/components/ble_esl/test_llm_api.py index d5de100..db352a4 100644 --- a/tests/components/ble_esl/test_llm_api.py +++ b/tests/components/ble_esl/test_llm_api.py @@ -19,6 +19,7 @@ label_registry as lr, llm, ) +from jinja2 import Environment from PIL import Image import pytest import voluptuous as vol @@ -177,6 +178,9 @@ async def test_api_registered_with_serializable_tools(hass: HomeAssistant, wolin assert draft["required"] == ["tag", "payload"] assert draft["properties"]["triggers"]["type"] == "array" assert list(draft["properties"]["mode"]["enum"]) == ["write", "guarded"] + for schema in (write, draft): + for field in ("mode", "rotate", "background"): + assert isinstance(schema["properties"][field]["enum"], list) async def test_tools_name_their_integration( @@ -1107,11 +1111,14 @@ async def ticker() -> None: task = hass.async_create_background_task(ticker(), "ticker") try: - # Compiling folds constants (it can run for minutes): nothing may reach it. - with patch( - "jinja2.environment.Environment.compile", - side_effect=AssertionError("the template was compiled"), - ): + # Compiling the original folds constants; only the inert placeholder may reach it. + compile_original = Environment.compile + + def guarded_compile(env, source, *args, **kwargs): + assert source != template + return compile_original(env, source, *args, **kwargs) + + with patch.object(Environment, "compile", guarded_compile): result = await draft( hass, hass_admin_user, payload=temp_payload(template), triggers=[TRIGGER] ) @@ -1256,3 +1263,73 @@ async def test_draft_automation_default_does_not_hide_undefined_names( result = await draft(hass, hass_admin_user, payload=temp_payload(template), triggers=[TRIGGER]) assert result["status"] == "invalid" assert any("foo" in e for e in result["errors"]) + + +async def test_draft_reports_unsafe_condition_template(hass, wolink_entry, hass_admin_user): + result = await draft( + hass, + hass_admin_user, + conditions=[ + { + "condition": "template", + "value_template": "{{ states('sensor.temp') | nonexistent_filter }}", + } + ], + ) + assert result["status"] == "invalid" + assert any( + "conditions[0].value_template" in error and "nonexistent_filter" in error + for error in result["errors"] + ) + assert any("conditions[0].value_template" in warning for warning in result["warnings"]) + + +async def test_draft_invalid_scalar_entity_id(hass, wolink_entry, hass_admin_user): + result = await draft(hass, hass_admin_user, triggers=[{"trigger": "state", "entity_id": 123}]) + assert result["status"] == "invalid" + assert any("entity_id" in error for error in result["errors"]) + + +async def test_validation_copy_preserves_colliding_keys(hass: HomeAssistant) -> None: + from homeassistant.helpers.template import Template + + env = Template("", hass)._env + automation = { + "variables": { + "{{ 1 * 2 }}": "first", + "__unchecked_key_0__": "static", + "{{ 3 * 4 }}": "last", + } + } + safe, errors, warnings = await hass.async_add_executor_job( + llm_api._validation_copy, env, automation, False + ) + assert not errors + assert set(safe["variables"].values()) == {"first", "static", "last"} + assert len(warnings) == 2 + + +async def test_draft_nested_invalid_entity_id(hass, wolink_entry, hass_admin_user): + result = await draft( + hass, + hass_admin_user, + triggers=[TRIGGER], + conditions=[ + { + "condition": "and", + "conditions": [{"condition": "state", "entity_id": 123, "state": "on"}], + } + ], + ) + assert result["status"] == "invalid" + assert any("conditions[0].conditions[0].entity_id" in error for error in result["errors"]) + + +async def test_draft_unsafe_trigger_duration_is_neutralized(hass, wolink_entry, hass_admin_user): + result = await draft( + hass, + hass_admin_user, + triggers=[{"trigger": "state", "entity_id": "sensor.temp", "for": "{{ 60 * 2 }}"}], + ) + assert result["status"] == "ok", result["errors"] + assert any("triggers[0].for" in warning for warning in result["warnings"]) From a3c5b1a2c036708a332c7c3efabf82989d66f490 Mon Sep 17 00:00:00 2001 From: eigger Date: Mon, 30 Nov 2026 19:50:36 +0900 Subject: [PATCH 2/3] Address review: dedupe payload validation warnings and tidy draft validation Co-Authored-By: Claude Opus 5.5 --- README.ko.md | 9 +- README.md | 9 +- custom_components/ble_esl/llm_api.py | 105 ++++++++++++----------- tests/components/ble_esl/test_llm_api.py | 38 +++++++- 4 files changed, 108 insertions(+), 53 deletions(-) diff --git a/README.ko.md b/README.ko.md index fdf3695..84e0bbb 100644 --- a/README.ko.md +++ b/README.ko.md @@ -102,7 +102,14 @@ data: **전용 엔드포인트 `/api/mcp/ble_esl` (권장).** 지원 최소 버전인 Home Assistant 2026.8.0부터 사용할 수 있습니다. 별도의 MCP 서버로 등록하며, 도구 이름에 접두어가 붙지 않고 관리자만 사용할 수 있습니다. -**공용 엔드포인트 `/api/mcp`.** Home Assistant 2026.10부터 통합 옵션에서 노출할 API와 관리자 요구 여부를 바꿀 수 있습니다. 새 항목은 기본적으로 모든 API를 노출하고 관리자만 허용합니다. 기존 항목은 API 선택을 유지합니다. 2026.8–2026.9에서는 통합을 추가할 때 BLE ESL을 선택하고, 선택을 바꾸려면 항목을 삭제한 뒤 다시 추가하세요. 2026.11 이전에는 여러 API를 노출할 때 접두어가 붙습니다(예: `ble-esl__write_tag`). 2026.11부터 도구 이름이 충돌할 때만 네임스페이스가 붙으며 공용 엔드포인트에 읽기 전용 설정도 사용할 수 있습니다. 설정에 따라 관리자 접근이 필요하거나 쓰기 도구가 제외될 수 있습니다. BLE ESL 도구 자체도 관리자를 요구합니다. +**공용 엔드포인트 `/api/mcp`.** Home Assistant 버전에 따라 동작이 다릅니다. + +- **2026.8–2026.9:** 통합을 추가할 때 BLE ESL을 선택합니다. 선택을 바꾸려면 항목을 삭제한 뒤 다시 추가하세요. +- **2026.10부터:** 통합 옵션에서 노출할 API와 관리자 요구 여부를 바꿀 수 있습니다. 새 항목은 기본적으로 모든 API를 노출하고 관리자만 허용합니다. 기존 항목은 API 선택을 유지합니다. +- **2026.11 이전:** 여러 API를 노출할 때 접두어가 붙습니다(예: `ble-esl__write_tag`). +- **2026.11부터:** 도구 이름이 충돌할 때만 네임스페이스가 붙으며 공용 엔드포인트에 읽기 전용 설정도 사용할 수 있습니다. + +설정에 따라 관리자 접근이 필요하거나 쓰기 도구가 제외될 수 있습니다. BLE ESL 도구 자체도 관리자를 요구합니다. 두 방법 모두 Home Assistant의 전체 URL(예: `https://ha.example.com/api/mcp/ble_esl`)을 쓰고 **관리자**로 로그인해야 합니다. MCP 인증 규격을 지원하는 클라이언트는 Home Assistant 로그인 페이지를 열고(Home Assistant가 `/.well-known/oauth-authorization-server`와 `/.well-known/oauth-protected-resource`를 제공합니다), 그렇지 않으면 장기 액세스 토큰을 `Authorization: Bearer <토큰>`으로 보냅니다. 클라우드에서 동작하는 클라이언트는 Home Assistant에 인터넷으로 접속할 수 있어야 합니다. diff --git a/README.md b/README.md index 2bfa9af..954b140 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,14 @@ The integration registers an LLM API named **BLE ESL**. Add Home Assistant's [Mo **Dedicated endpoint `/api/mcp/ble_esl` (recommended).** Available from Home Assistant 2026.8.0, the minimum supported version. Register it as a separate MCP server. Home Assistant restricts it to administrators and exposes tool names without a prefix. -**Shared endpoint `/api/mcp`.** From Home Assistant 2026.10, the integration's options let you select exposed APIs and require administrators. New entries expose all APIs and require administrators by default. Existing entries retain their API selections. On 2026.8–2026.9, select BLE ESL when adding the integration. To change the selection on those versions, delete and re-add the entry. Before 2026.11, names are prefixed when multiple APIs are exposed (for example `ble-esl__write_tag`). From 2026.11, names are namespaced only when they collide, and a read-only option is available for the shared endpoint. Depending on the settings, administrator access may be required or write tools may be omitted. BLE ESL tools themselves also require an administrator. +**Shared endpoint `/api/mcp`.** Behaviour depends on your Home Assistant version: + +- **2026.8–2026.9:** select BLE ESL when adding the integration. To change the selection, delete and re-add the entry. +- **From 2026.10:** the integration's options let you select exposed APIs and require administrators. New entries expose all APIs and require administrators by default. Existing entries retain their API selections. +- **Before 2026.11:** names are prefixed when multiple APIs are exposed (for example `ble-esl__write_tag`). +- **From 2026.11:** names are namespaced only when they collide, and a read-only option is available for the shared endpoint. + +Depending on the settings, administrator access may be required or write tools may be omitted. BLE ESL tools themselves also require an administrator. For both, use the full URL of your Home Assistant (for example `https://ha.example.com/api/mcp/ble_esl`) and sign in as an **administrator**: either an MCP client that supports the MCP authorization spec opens the Home Assistant login page (Home Assistant serves `/.well-known/oauth-authorization-server` and `/.well-known/oauth-protected-resource`), or you send a long-lived access token as `Authorization: Bearer `. A client hosted in the cloud needs your Home Assistant to be reachable from the internet. diff --git a/custom_components/ble_esl/llm_api.py b/custom_components/ble_esl/llm_api.py index 7ebabb4..e2b4cb3 100644 --- a/custom_components/ble_esl/llm_api.py +++ b/custom_components/ble_esl/llm_api.py @@ -1255,7 +1255,13 @@ def _validation_copy( warnings: list[str] = [] errors: list[str] = [] - def neutralize(value: Any, path: str) -> Any: + payload = automation["actions"][-1]["data"]["payload"] + + def neutralize(value: Any, path: str, in_payload: bool = False) -> Any: + if value is payload: + if drop_payload: + return [] # Replaced anyway; nothing in it is worth reporting. + in_payload = True if isinstance(value, str) and template_syntax(value): tree = None if len(value) <= MAX_PARSED_CHARS: @@ -1267,42 +1273,42 @@ def neutralize(value: Any, path: str) -> Any: if reasons: # Parsing is safe; compiling could evaluate constant expressions. Check # filter and test names without compiling or evaluating the expression. - if len(value) <= MAX_PARSED_CHARS: - try: - for node in tree.find_all((jinja_nodes.Filter, jinja_nodes.Test)): - registry = ( - env.filters if isinstance(node, jinja_nodes.Filter) else env.tests - ) - if node.name not in registry: - kind = "filter" if isinstance(node, jinja_nodes.Filter) else "test" - errors.append(f"{path}: unknown {kind} `{node.name}`") - except TemplateSyntaxError as err: - errors.append(f"{path}: template syntax error: {err}") - warnings.append( - f"{path}: original template was not checked by Home Assistant " - f"validation ({', '.join(reasons)}); review it" - ) + if tree is not None: + for node in tree.find_all((jinja_nodes.Filter, jinja_nodes.Test)): + registry = ( + env.filters if isinstance(node, jinja_nodes.Filter) else env.tests + ) + if node.name not in registry: + kind = "filter" if isinstance(node, jinja_nodes.Filter) else "test" + errors.append(f"{path}: unknown {kind} `{node.name}`") + if not in_payload: # The renderer already warns about payload templates. + warnings.append( + f"{path}: original template was not checked by Home Assistant " + f"validation ({', '.join(reasons)}); review it" + ) return "{{ 0 }}" return value if isinstance(value, list): - return [neutralize(item, f"{path}[{index}]") for index, item in enumerate(value)] + return [ + neutralize(item, f"{path}[{index}]", in_payload) for index, item in enumerate(value) + ] if isinstance(value, dict): result: dict[Any, Any] = {} reserved = set(value) for index, (key, item) in enumerate(value.items()): - checked = neutralize(key, f"{path}.[key {key!r}]") if isinstance(key, str) else key + key_path = f"{path}.[key {key!r}]" if path else f"[key {key!r}]" + checked = neutralize(key, key_path, in_payload) if isinstance(key, str) else key if checked != key: checked = f"__unchecked_key_{index}__" while checked in reserved or checked in result: checked += "_" - result[checked] = neutralize(item, f"{path}.{key}" if path else str(key)) + result[checked] = neutralize( + item, f"{path}.{key}" if path else str(key), in_payload + ) return result return value - copy = neutralize(automation, "") - if drop_payload: - copy["actions"][-1]["data"]["payload"] = [] - return copy, errors, warnings + return neutralize(automation, ""), errors, warnings def _template_policy(value: Any, path: str = "payload") -> list[str]: @@ -1545,6 +1551,29 @@ def _missing_entities(hass: HomeAssistant, value: Any, path: str) -> list[str]: return found +def _scalar_entity_ids(value: Any, path: str) -> list[str]: + """Errors for state triggers or conditions whose entity_id is a number or boolean.""" + if isinstance(value, list): + return [ + p + for index, item in enumerate(value) + for p in _scalar_entity_ids(item, f"{path}[{index}]") + ] + if isinstance(value, dict): + paths: list[str] = [] + kind = value.get("trigger", value.get("platform", value.get("condition"))) + if kind in ("state", "numeric_state") and isinstance( + value.get("entity_id"), (int, float, bool) + ): + paths.append(f"{path}.entity_id: invalid entity ID value") + if "conditions" in value: + paths.extend(_scalar_entity_ids(value["conditions"], f"{path}.conditions")) + if "triggers" in value: + paths.extend(_scalar_entity_ids(value["triggers"], f"{path}.triggers")) + return paths + return [] + + def _build_draft( raw_payload: list[dict[str, Any]], rendered: list[dict[str, Any]], @@ -1763,30 +1792,8 @@ async def async_call( warnings += validation_warnings if problem := await _validate_automation(hass, safe): errors.append(f"Home Assistant rejects the automation: {problem}") - - def scalar_entity_paths(value: Any, path: str) -> list[str]: - if isinstance(value, list): - return [ - p - for index, item in enumerate(value) - for p in scalar_entity_paths(item, f"{path}[{index}]") - ] - if isinstance(value, dict): - paths: list[str] = [] - kind = value.get("trigger", value.get("platform", value.get("condition"))) - if kind in ("state", "numeric_state") and isinstance( - value.get("entity_id"), (int, float, bool) - ): - paths.append(f"{path}.entity_id: invalid entity ID value") - if "conditions" in value: - paths.extend(scalar_entity_paths(value["conditions"], f"{path}.conditions")) - if "triggers" in value: - paths.extend(scalar_entity_paths(value["triggers"], f"{path}.triggers")) - return paths - return [] - - errors += scalar_entity_paths(triggers, "triggers") - errors += scalar_entity_paths(conditions, "conditions") + errors += _scalar_entity_ids(triggers, "triggers") + errors += _scalar_entity_ids(conditions, "conditions") result: dict[str, Any] = { "status": "invalid" if errors else "ok", @@ -1813,9 +1820,7 @@ def scalar_entity_paths(value: Any, path: str) -> list[str]: if warnings: result["warnings"] = warnings[:20] if len(warnings) > 20: - result["warnings"].append( - f"{len(warnings) - 20} more warnings omitted; validation was incomplete" - ) + result["warnings"].append("... more warnings omitted") result["note"] = ( "Nothing was saved. The saved automation runs in trusted mode, so a person should " "read automation_yaml, then create it in Home Assistant (Settings > Automations & " diff --git a/tests/components/ble_esl/test_llm_api.py b/tests/components/ble_esl/test_llm_api.py index db352a4..9bb601c 100644 --- a/tests/components/ble_esl/test_llm_api.py +++ b/tests/components/ble_esl/test_llm_api.py @@ -1299,7 +1299,8 @@ async def test_validation_copy_preserves_colliding_keys(hass: HomeAssistant) -> "{{ 1 * 2 }}": "first", "__unchecked_key_0__": "static", "{{ 3 * 4 }}": "last", - } + }, + "actions": [{"data": {"payload": []}}], } safe, errors, warnings = await hass.async_add_executor_job( llm_api._validation_copy, env, automation, False @@ -1309,6 +1310,41 @@ async def test_validation_copy_preserves_colliding_keys(hass: HomeAssistant) -> assert len(warnings) == 2 +async def test_validation_copy_payload_warnings(hass: HomeAssistant) -> None: + from homeassistant.helpers.template import Template + + env = Template("", hass)._env + unsafe = "{{ 1 * 2 }}" + automation = {"actions": [{"data": {"payload": [{"type": "text", "value": unsafe}]}}]} + safe, errors, warnings = await hass.async_add_executor_job( + llm_api._validation_copy, env, automation, False + ) + # The renderer already warns about payload templates; no second warning here. + assert not errors + assert not warnings + assert safe["actions"][0]["data"]["payload"][0]["value"] == "{{ 0 }}" + + unknown = {"actions": [{"data": {"payload": [{"value": "{{ 1 | nope }}"}]}}]} + _, errors, warnings = await hass.async_add_executor_job( + llm_api._validation_copy, env, unknown, False + ) + assert any("unknown filter `nope`" in error for error in errors) + assert not warnings + + +async def test_validation_copy_skips_refused_payload(hass: HomeAssistant) -> None: + from homeassistant.helpers.template import Template + + env = Template("", hass)._env + automation = {"actions": [{"data": {"payload": [{"value": "{{ 1 | nope }}{{ 1 * 2 }}"}]}}]} + safe, errors, warnings = await hass.async_add_executor_job( + llm_api._validation_copy, env, automation, True + ) + assert not errors + assert not warnings + assert safe["actions"][0]["data"]["payload"] == [] + + async def test_draft_nested_invalid_entity_id(hass, wolink_entry, hass_admin_user): result = await draft( hass, From 15ba93bfd86786f5e3b2b05a0188cebfa7b43af3 Mon Sep 17 00:00:00 2001 From: eigger Date: Mon, 30 Nov 2026 19:52:10 +0900 Subject: [PATCH 3/3] Restore omitted-warnings count Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- custom_components/ble_esl/llm_api.py | 2 +- tests/components/ble_esl/test_llm_api.py | 12 ++++++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 954b140..9403501 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ The integration registers an LLM API named **BLE ESL**. Add Home Assistant's [Mo **Dedicated endpoint `/api/mcp/ble_esl` (recommended).** Available from Home Assistant 2026.8.0, the minimum supported version. Register it as a separate MCP server. Home Assistant restricts it to administrators and exposes tool names without a prefix. -**Shared endpoint `/api/mcp`.** Behaviour depends on your Home Assistant version: +**Shared endpoint `/api/mcp`.** Behavior depends on your Home Assistant version: - **2026.8–2026.9:** select BLE ESL when adding the integration. To change the selection, delete and re-add the entry. - **From 2026.10:** the integration's options let you select exposed APIs and require administrators. New entries expose all APIs and require administrators by default. Existing entries retain their API selections. diff --git a/custom_components/ble_esl/llm_api.py b/custom_components/ble_esl/llm_api.py index e2b4cb3..3a2b8c7 100644 --- a/custom_components/ble_esl/llm_api.py +++ b/custom_components/ble_esl/llm_api.py @@ -1820,7 +1820,7 @@ async def async_call( if warnings: result["warnings"] = warnings[:20] if len(warnings) > 20: - result["warnings"].append("... more warnings omitted") + result["warnings"].append(f"{len(warnings) - 20} more warnings omitted") result["note"] = ( "Nothing was saved. The saved automation runs in trusted mode, so a person should " "read automation_yaml, then create it in Home Assistant (Settings > Automations & " diff --git a/tests/components/ble_esl/test_llm_api.py b/tests/components/ble_esl/test_llm_api.py index 9bb601c..0178aed 100644 --- a/tests/components/ble_esl/test_llm_api.py +++ b/tests/components/ble_esl/test_llm_api.py @@ -1284,6 +1284,18 @@ async def test_draft_reports_unsafe_condition_template(hass, wolink_entry, hass_ assert any("conditions[0].value_template" in warning for warning in result["warnings"]) +async def test_draft_overflow_counts(hass, wolink_entry, hass_admin_user): + triggers = [{"trigger": "state", "entity_id": f"sensor.missing_{index}"} for index in range(25)] + result = await draft(hass, hass_admin_user, triggers=triggers) + assert len(result["warnings"]) == 21 + assert result["warnings"][-1] == "6 more warnings omitted" + + bad = [{"trigger": "state", "entity_id": index} for index in range(25)] + result = await draft(hass, hass_admin_user, triggers=bad) + assert len(result["errors"]) == 21 + assert result["errors"][-1] == "6 more errors omitted" + + async def test_draft_invalid_scalar_entity_id(hass, wolink_entry, hass_admin_user): result = await draft(hass, hass_admin_user, triggers=[{"trigger": "state", "entity_id": 123}]) assert result["status"] == "invalid"