diff --git a/ops/audits/TOOL-GATEWAY-MCP-2026-11-17.md b/ops/audits/TOOL-GATEWAY-MCP-2026-11-17.md new file mode 100644 index 0000000..2748a32 --- /dev/null +++ b/ops/audits/TOOL-GATEWAY-MCP-2026-11-17.md @@ -0,0 +1,54 @@ +# Tool Gateway + MCP: интеграция с секретарём (17.11.2026) + +## Что подключено + +Секретарь (OpenClaw) видит **10 инструментов Tool Gateway** нативно через MCP. + +* Gateway: `http://192.168.1.10:9140` (systemd `tool-gateway`). +* MCP-адаптер: `ops/tools/mcp_gateway.py` (stdio), лежит в CT115 + `/opt/openclaw/mcp_gateway.py`. +* В OpenClaw: `mcp.servers.toolgateway` (command python3, env TG_URL/TG_TOKEN). +* Агент вызывает инструменты сам, без shell. + +## Проверено на живом агенте + +| Запрос | Что сделал | Результат | +|---|---|---| +| «Сколько сервисов в хабе?» | `hub.status` | «74 сервиса, все работают» | +| «Создай событие 21.11 в 16:00» | `calendar.create` | событие создано (201), затем удалено | +| «Включи свет в коридоре» | `ha.states` + `ha.call` | `light.turn_on`, состояние `on` | + +Аудит: каждый вызов в `/var/lib/tool-gateway/audit.db` (actor/tool/ok/ms). +Первый вызов `hub.status` иногда таймаутит 20 с — добавлен ретрай (3 попытки, +таймаут 30 с). Валидация аргументов: `ha.call` без `domain` → 400 с подсказкой. + +## Архитектура + +``` +Matrix → OpenClaw (мозг) → MCP → Tool Gateway → hub / HA / *arr / CalDAV / Immich + ↓ + audit.db +``` + +Права: owner / family / agent; write требует `confirm=true` +(MCP передаёт подтверждение для owner-сессии). + +## Что ещё нужно + +1. **Подтверждения через Matrix**: 409 → заявка → «одобри N» (сейчас confirm + проходит автоматически для owner). +2. **Rate limit и идемпотентность** на уровне gateway. +3. **Больше инструментов**: media.request, photos.search (человек/дата), + approvals, backup.status. +4. **Family-доступ**: отдельный MCP-сервер/токен для Polina и остальных. +5. **Аудит в Postgres** и просмотр через hub. +6. **Selfcheck**: добавлена проверка Tool Gateway (служба + /health). + +## Ловушки + +| Ловушка | Что было | +|---|---| +| MCP add при работающем gateway | lock: «exclusive offline state»; правили `mcp.servers` в конфиге и перезапускали | +| первый `hub.status` | таймаут 20 с → добавлен ретрай | +| `ha.call` без domain | 500 → теперь 400 с missing_args | +| тестовое событие | создано и удалено (204), календарь чист | diff --git a/ops/automations/registry.yaml b/ops/automations/registry.yaml index d9b1591..352307c 100644 --- a/ops/automations/registry.yaml +++ b/ops/automations/registry.yaml @@ -1,5 +1,5 @@ # Реестр автоматизаций Buryans Hub -# Сгенерировано: 2026-11-17 12:26 (ops/scripts/build_automations_registry.py) +# Сгенерировано: 2026-11-17 16:19 (ops/scripts/build_automations_registry.py) total: 168 by_source: cron.d: 49 diff --git a/ops/scripts/selfcheck_platform.py b/ops/scripts/selfcheck_platform.py index a76fbd3..40ed82f 100755 --- a/ops/scripts/selfcheck_platform.py +++ b/ops/scripts/selfcheck_platform.py @@ -250,12 +250,20 @@ def check_pg_conn(): pct = 100.0 * total / limit if limit else 100 add("Postgres соединения", pct < 80, "%d/%d (%.0f%%)" % (total, limit, pct)) + +def check_tool_gateway(): + """Tool Gateway: служба и /health.""" + active = sh("systemctl is-active tool-gateway 2>/dev/null").strip() + health = sh("curl -s -m 5 http://127.0.0.1:9140/health 2>/dev/null").strip() + ok = active == "active" and '"ok": true' in health + add("Tool Gateway", ok, "active=%s health=%s" % (active, health[:60])) + def main(): print("Самопроверка платформы", date.today().isoformat()) checks = [check_units, check_services, check_bots, check_matrix_sso, check_ollama, check_n8n, check_digests, check_reports, check_registry, check_cron_dots, check_tasks, check_approvals, check_hermes, check_errors, check_disk, - check_lvm, check_pg_conn] + check_lvm, check_pg_conn, check_tool_gateway] for fn in checks: try: fn() diff --git a/ops/tools/gateway.py b/ops/tools/gateway.py index 55004cf..3579245 100755 --- a/ops/tools/gateway.py +++ b/ops/tools/gateway.py @@ -63,7 +63,16 @@ def basic(user, pw): # ---------- инструменты ---------- def t_hub_status(args): - st, body = http("GET", HUB + "/status.json") + last = None + for _ in range(3): + try: + st, body = http("GET", HUB + "/status.json", timeout=30) + break + except Exception as e: + last = e + time.sleep(2) + else: + raise last or RuntimeError("hub status unavailable") d = json.loads(body) svc = d.get("services", []) down = [s["name"] for s in svc if not s.get("up")] @@ -261,6 +270,15 @@ class Handler(BaseHTTPRequestHandler): if actor not in allowed: return self._send(403, {"error": "forbidden for actor", "actor": actor, "allowed": allowed}) + required = { + "ha.call": ["domain", "service"], + "calendar.create": ["title", "start"], + "hub.notify": ["message"], + }.get(tool, []) + missing = [k for k in required if not args.get(k)] + if missing: + return self._send(400, {"error": "missing_args", "missing": missing, + "tool": tool, "required": required}) if spec["confirm"] and not req.get("confirm"): return self._send(409, {"error": "confirmation_required", "tool": tool, "hint": "повторите с confirm=true"}) diff --git a/ops/tools/mcp_gateway.py b/ops/tools/mcp_gateway.py new file mode 100755 index 0000000..e168f69 --- /dev/null +++ b/ops/tools/mcp_gateway.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""MCP stdio-адаптер к Tool Gateway Buryans Hub. + +Отдаёт инструменты gateway как MCP tools. Read-only по умолчанию; +write-инструменты вызываются с confirm=true только для owner-токена. +""" +import json +import os +import sys +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"} + +SCHEMAS = { + "hub.status": ("Статус сервисов хаба: сколько всего и что лежит", {"type": "object", "properties": {}}), + "hub.notify": ("Отправить уведомление в хаб", {"type": "object", "properties": { + "title": {"type": "string"}, "message": {"type": "string"}, + "priority": {"type": "string", "enum": ["low", "normal", "high"]}}, + "required": ["message"]}), + "ha.states": ("Состояния Home Assistant, можно фильтровать по домену", {"type": "object", "properties": { + "domain": {"type": "string"}}}), + "ha.call": ("Вызвать сервис Home Assistant (свет, сцены и т.п.)", {"type": "object", "properties": { + "domain": {"type": "string"}, "service": {"type": "string"}, + "data": {"type": "object"}}, "required": ["domain", "service"]}), + "media.queue": ("Очередь Radarr/Sonarr", {"type": "object", "properties": {}}), + "media.recent": ("Недавно добавленные фильмы Jellyfin", {"type": "object", "properties": {}}), + "calendar.list": ("События календаря на N дней", {"type": "object", "properties": { + "calendar": {"type": "string"}, "days": {"type": "integer"}}}), + "calendar.create": ("Создать событие (start: 20261120T150000)", {"type": "object", "properties": { + "title": {"type": "string"}, "start": {"type": "string"}, + "end": {"type": "string"}, "calendar": {"type": "string"}}, + "required": ["title", "start"]}), + "photos.people": ("Люди в Immich", {"type": "object", "properties": {}}), + "photos.albums": ("Альбомы Immich", {"type": "object", "properties": {}}), +} + + +def call_gateway(tool, args): + body = {"tool": tool, "args": args or {}, "confirm": tool in WRITE} + req = urllib.request.Request(URL + "/call", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", + "X-Gateway-Token": TOKEN}, method="POST") + with urllib.request.urlopen(req, timeout=40) as r: + return json.loads(r.read().decode()) + + +def reply(obj): + sys.stdout.write(json.dumps(obj, ensure_ascii=False) + "\n") + sys.stdout.flush() + + +def main(): + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except Exception: + continue + method = msg.get("method") + mid = msg.get("id") + if method == "initialize": + reply({"jsonrpc": "2.0", "id": mid, "result": { + "protocolVersion": "2024-11-05", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "buryans-tool-gateway", "version": "1.0"}}}) + elif method in ("notifications/initialized", "initialized"): + continue + elif method == "ping": + reply({"jsonrpc": "2.0", "id": mid, "result": {}}) + elif method == "tools/list": + tools = [] + for name, (desc, schema) in SCHEMAS.items(): + tools.append({"name": name, "description": desc, "inputSchema": schema}) + reply({"jsonrpc": "2.0", "id": mid, "result": {"tools": tools}}) + elif method == "tools/call": + params = msg.get("params") or {} + name = params.get("name") + args = params.get("arguments") or {} + if name not in SCHEMAS: + reply({"jsonrpc": "2.0", "id": mid, + "error": {"code": -32602, "message": "unknown tool"}}) + continue + try: + res = call_gateway(name, args) + text = json.dumps(res, ensure_ascii=False) + reply({"jsonrpc": "2.0", "id": mid, "result": { + "content": [{"type": "text", "text": text}], + "isError": not res.get("ok", False)}}) + except Exception as e: + reply({"jsonrpc": "2.0", "id": mid, "result": { + "content": [{"type": "text", "text": "gateway error: " + str(e)[:200]}], + "isError": True}}) + else: + if mid is not None: + reply({"jsonrpc": "2.0", "id": mid, + "error": {"code": -32601, "message": "method not found"}}) + + +if __name__ == "__main__": + main()