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"]}), + }