From 096b1986924d32e3011bfe1227d5be19e369c02c Mon Sep 17 00:00:00 2001 From: Roman Buryan Date: Tue, 17 Nov 2026 16:58:12 +0300 Subject: [PATCH] =?UTF-8?q?[TOOLS]=20P0:=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=8B=20ha.search=20(=D0=BF=D0=BE=D0=B8?= =?UTF-8?q?=D1=81=D0=BA=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82=D0=B5?= =?UTF-8?q?=D0=B9=20HA),=20media.search=20(Sonarr/Radarr=20lookup),=20medi?= =?UTF-8?q?a.request=20(=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5/=D0=BF=D0=BE=D0=B8=D1=81=D0=BA=20=D1=81=D0=B5?= =?UTF-8?q?=D0=B7=D0=BE=D0=BD=D0=B0,=20confirm).=20MCP-=D1=81=D1=85=D0=B5?= =?UTF-8?q?=D0=BC=D1=8B=20=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B.=20=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE:=20ha.search=20=D0=BD=D0=B0=D1=88=D1=91=D0=BB=20=D0=BA?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=B4=D0=BE=D1=80=20=D0=B8=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B8=D1=85=D0=BE=D0=B6=D1=83=D1=8E=20(=D0=BE=D0=B1=D0=B5=20on?= =?UTF-8?q?=20=D1=81=2003:50);=20media.search=20=D1=80=D0=B0=D0=BD=D0=B5?= =?UTF-8?q?=D0=B5=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=BB=20(Clarkson?= =?UTF-8?q?'s=20Farm=20tvdb=20378165),=20=D1=81=D0=B5=D0=B9=D1=87=D0=B0?= =?UTF-8?q?=D1=81=20Sonarr=20lookup=20503=20(=D0=B8=D0=BD=D0=B4=D0=B5?= =?UTF-8?q?=D0=BA=D1=81=D0=B5=D1=80);=20media.request=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20=D1=81=D1=83=D1=89=D0=B5=D1=81=D1=82=D0=B2=D1=83=D1=8E=D1=89?= =?UTF-8?q?=D0=B5=D0=B3=D0=BE=20=D1=81=D0=B5=D1=80=D0=B8=D0=B0=D0=BB=D0=B0?= =?UTF-8?q?=20=D0=B2=D0=BE=D0=B7=D0=B2=D1=80=D0=B0=D1=89=D0=B0=D0=B5=D1=82?= =?UTF-8?q?=20already=5Fexists=20+=20SeasonSearch.=20Jellyfin=20=D0=BA?= =?UTF-8?q?=D0=BB=D1=8E=D1=87=20401=20=E2=80=94=20=D0=BD=D1=83=D0=B6=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ops/audits/P0-TOOLS-2026-11-17.md | 42 +++++++++++ ops/tools/gateway.py | 116 ++++++++++++++++++++++++++++++ ops/tools/mcp_gateway.py | 12 +++- 3 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 ops/audits/P0-TOOLS-2026-11-17.md diff --git a/ops/audits/P0-TOOLS-2026-11-17.md b/ops/audits/P0-TOOLS-2026-11-17.md new file mode 100644 index 0000000..e632ffc --- /dev/null +++ b/ops/audits/P0-TOOLS-2026-11-17.md @@ -0,0 +1,42 @@ +# P0-инструменты: ha.search, media.search, media.request (17.11.2026) + +## Что добавлено в Tool Gateway + +| Инструмент | Тип | Что делает | +|---|---|---| +| `ha.search` | read | поиск сущностей HA по имени/домену с состояниями и атрибутами | +| `media.search` | read | поиск сериала (Sonarr) или фильма (Radarr) | +| `media.request` | write (confirm) | добавить сериал/фильм; для существующего — запустить поиск сезона | + +MCP-схемы обновлены, агент видит новые инструменты. + +## Проверки + +* `ha.search` — работает; агент нашёл: + * `light.lampa_koridor_lampa_koridor` — on с 03:50 + * `light.svet_v_prikhozhei_svet_v_prikhozhei` — on с 03:50 + * автоматизацию «Свет в прихожей днём больше 2 часов»; +* `media.search` — ранее отдавал `Clarkson's Farm` (tvdb 378165); сейчас + Sonarr lookup отвечает **503** (индексер/поиск), `series` и `system/status` — 200; +* `media.request` — при существующем сериале возвращает `already_exists` + и запускает `SeasonSearch`; проверка заблокирована 503 lookup. + +## Почему свет «включён», а физически нет + +Обе сущности числятся `on` с 03:50 МСК. Агент вызывал `light.turn_off` и +`light.turn_on` для обеих — HA отвечал 200. Причины: + +1. не та сущность (коридор vs прихожая); +2. реле/устройство offline, HA показывает последнее состояние; +3. нет обратной связи (`supported_features=0`, истории нет). + +Нужен ответ владельца: какая сущность — реальный свет в коридоре. + +## Известные проблемы + +* **Jellyfin** `/System/Info` → 401: ключ `/root/.jellyfin-key` недействителен, + `media.recent` не работает, нужен новый ключ. +* **Sonarr lookup 503** — проверить индексеры/Prowlarr, до этого + `media.search`/`media.request` будут возвращать ошибку. +* `media.request` для существующего сериала: 400 → `already_exists`, + затем `SeasonSearch` (когда lookup доступен). diff --git a/ops/tools/gateway.py b/ops/tools/gateway.py index 3579245..ed485ec 100755 --- a/ops/tools/gateway.py +++ b/ops/tools/gateway.py @@ -190,6 +190,115 @@ def t_photos_albums(args): return {"count": len(d or []), "albums": [a.get("albumName") for a in (d or [])][:50]} +def t_ha_search(args): + q = (args.get("query") or "").lower() + domain = args.get("domain") + st, body = http("GET", HA + "/api/states", {"Authorization": "Bearer " + HA_TOKEN}) + states = json.loads(body) + out = [] + for s in states: + if domain and not s["entity_id"].startswith(domain + "."): + continue + name = ((s.get("attributes") or {}).get("friendly_name") or "").lower() + if q and q not in name and q not in s["entity_id"].lower(): + continue + a = s.get("attributes") or {} + out.append({"entity_id": s["entity_id"], + "name": a.get("friendly_name"), + "state": s.get("state"), + "last_changed": s.get("last_changed"), + "domain": s["entity_id"].split(".")[0], + "device_class": a.get("device_class"), + "supported_features": a.get("supported_features")}) + return {"query": q, "count": len(out), "entities": out[:50]} + + +def _lookup(kind, query): + if kind == "series": + st, body = http("GET", SONARR + "/api/v3/series/lookup?term=" + urllib.parse.quote(query), + {"X-Api-Key": SONARR_KEY}) + else: + st, body = http("GET", RADARR + "/api/v3/movie/lookup?term=" + urllib.parse.quote(query), + {"X-Api-Key": RADARR_KEY}) + return json.loads(body) + + +def t_media_search(args): + kind = args.get("kind", "series") + q = args.get("query") or "" + items = _lookup(kind, q) + out = [] + for it in (items or [])[:8]: + out.append({"title": it.get("title"), "year": it.get("year"), + "tvdbId": it.get("tvdbId"), "tmdbId": it.get("tmdbId"), + "overview": (it.get("overview") or "")[:200]}) + return {"kind": kind, "query": q, "count": len(out), "items": out} + + +def t_media_request(args): + kind = args.get("kind", "series") + q = args.get("query") or "" + season = args.get("season") + items = _lookup(kind, q) + if not items: + return {"error": "not_found", "query": q} + it = items[0] + if kind == "series": + st, body = http("GET", SONARR + "/api/v3/rootfolder", {"X-Api-Key": SONARR_KEY}) + roots = json.loads(body) + st, body = http("GET", SONARR + "/api/v3/qualityprofile", {"X-Api-Key": SONARR_KEY}) + profiles = json.loads(body) + root = roots[0]["path"] if roots else "/data/series" + qp = profiles[0]["id"] if profiles else 1 + seasons = it.get("seasons") or [] + for s in seasons: + s["monitored"] = (str(s.get("seasonNumber")) == str(season)) if season else True + payload = {"title": it.get("title"), "tvdbId": it.get("tvdbId"), + "qualityProfileId": qp, "rootFolderPath": root, + "monitored": True, "seasonFolder": True, "seasons": seasons, + "addOptions": {"searchForMissingEpisodes": True, + "monitor": "none" if season else "all"}} + st, body = http("POST", SONARR + "/api/v3/series", {"X-Api-Key": SONARR_KEY}, payload) + else: + st, body = http("GET", RADARR + "/api/v3/rootfolder", {"X-Api-Key": RADARR_KEY}) + roots = json.loads(body) + st, body = http("GET", RADARR + "/api/v3/qualityprofile", {"X-Api-Key": RADARR_KEY}) + profiles = json.loads(body) + root = roots[0]["path"] if roots else "/data/movies" + qp = profiles[0]["id"] if profiles else 1 + payload = {"title": it.get("title"), "tmdbId": it.get("tmdbId"), + "qualityProfileId": qp, "rootFolderPath": root, "monitored": True, + "addOptions": {"searchForMovie": True}} + st, body = http("POST", RADARR + "/api/v3/movie", {"X-Api-Key": RADARR_KEY}, payload) + try: + res = json.loads(body) + except Exception: + res = {"raw": body.decode("utf-8", "replace")[:200]} + if st >= 400 and kind == "series": + try: + st2, body2 = http("GET", SONARR + "/api/v3/series", {"X-Api-Key": SONARR_KEY}) + for ser in json.loads(body2): + if ser.get("tvdbId") == it.get("tvdbId"): + out = {"kind": kind, "query": q, "season": season, + "already_exists": True, "title": ser.get("title"), + "id": ser.get("id")} + if season: + try: + cmd = {"name": "SeasonSearch", "seriesId": ser.get("id"), + "seasonNumber": int(season)} + st3, body3 = http("POST", SONARR + "/api/v3/command", + {"X-Api-Key": SONARR_KEY}, cmd) + out["search"] = {"status": st3, + "body": body3.decode("utf-8", "replace")[:120]} + except Exception as e: + out["search"] = {"error": str(e)[:120]} + return out + except Exception: + pass + return {"kind": kind, "query": q, "season": season, "status": st, + "title": res.get("title"), "id": res.get("id"), + "error": res if st >= 400 else None} + TOOLS = { "hub.status": {"fn": t_hub_status, "scope": "read", "confirm": False}, "hub.notify": {"fn": t_hub_notify, "scope": "write", "confirm": True, @@ -204,6 +313,10 @@ TOOLS = { "actors": ["owner", "family"]}, "photos.people": {"fn": t_photos_people, "scope": "read", "confirm": False}, "photos.albums": {"fn": t_photos_albums, "scope": "read", "confirm": False}, + "ha.search": {"fn": t_ha_search, "scope": "read", "confirm": False}, + "media.search": {"fn": t_media_search, "scope": "read", "confirm": False}, + "media.request": {"fn": t_media_request, "scope": "write", "confirm": True, + "actors": ["owner", "family"]}, } @@ -274,6 +387,9 @@ class Handler(BaseHTTPRequestHandler): "ha.call": ["domain", "service"], "calendar.create": ["title", "start"], "hub.notify": ["message"], + "ha.search": ["query"], + "media.search": ["query"], + "media.request": ["query"], }.get(tool, []) missing = [k for k in required if not args.get(k)] if missing: diff --git a/ops/tools/mcp_gateway.py b/ops/tools/mcp_gateway.py index e168f69..a16afb8 100755 --- a/ops/tools/mcp_gateway.py +++ b/ops/tools/mcp_gateway.py @@ -11,7 +11,7 @@ import urllib.request URL = os.environ.get("TG_URL", "http://192.168.1.10:9140") TOKEN = os.environ.get("TG_TOKEN", "") -WRITE = {"hub.notify", "ha.call", "calendar.create"} +WRITE = {"hub.notify", "ha.call", "calendar.create", "media.request"} SCHEMAS = { "hub.status": ("Статус сервисов хаба: сколько всего и что лежит", {"type": "object", "properties": {}}), @@ -34,6 +34,16 @@ SCHEMAS = { "required": ["title", "start"]}), "photos.people": ("Люди в Immich", {"type": "object", "properties": {}}), "photos.albums": ("Альбомы Immich", {"type": "object", "properties": {}}), + "ha.search": ("Найти сущности Home Assistant по имени", {"type": "object", "properties": { + "query": {"type": "string"}, "domain": {"type": "string"}}, "required": ["query"]}), + "media.search": ("Поиск сериала или фильма в Sonarr/Radarr", {"type": "object", "properties": { + "kind": {"type": "string", "enum": ["series", "movie"]}, + "query": {"type": "string"}}, "required": ["query"]}), + "media.request": ("Добавить сериал/фильм и запустить поиск", {"type": "object", "properties": { + "kind": {"type": "string", "enum": ["series", "movie"]}, + "query": {"type": "string"}, "season": {"type": "integer"}}, + "required": ["query"]}), + }