Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,18 @@ 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.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에 인터넷으로 접속할 수 있어야 합니다.

Expand Down
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,18 @@ 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`.** 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.
- **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 <token>`. A client hosted in the cloud needs your Home Assistant to be reachable from the internet.

Expand Down
137 changes: 108 additions & 29 deletions custom_components/ble_esl/llm_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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).

Expand All @@ -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] = []
Expand Down Expand Up @@ -1244,27 +1248,67 @@ 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] = []

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:
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 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}]", 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()):
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), in_payload
)
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)
if drop_payload:
copy["actions"][-1]["data"]["payload"] = []
return copy
return neutralize(automation, ""), errors, warnings


def _template_policy(value: Any, path: str = "payload") -> list[str]:
Expand Down Expand Up @@ -1492,7 +1536,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)
Expand All @@ -1505,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]],
Expand Down Expand Up @@ -1616,13 +1685,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,
Expand Down Expand Up @@ -1716,9 +1785,15 @@ 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}")
errors += _scalar_entity_ids(triggers, "triggers")
errors += _scalar_entity_ids(conditions, "conditions")

result: dict[str, Any] = {
"status": "invalid" if errors else "ok",
Expand All @@ -1740,8 +1815,12 @@ 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")
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 & "
Expand Down
Loading
Loading