#!/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", "media.request"} 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": {}}), "books.search": ("Поиск книг в OpenLibrary", {"type": "object", "properties": { "query": {"type": "string"}}, "required": ["query"]}), "books.link": ("Ссылки на поиск книги (без скачивания)", {"type": "object", "properties": { "query": {"type": "string"}}, "required": ["query"]}), "books.status": ("Доступность Calibre-Web", {"type": "object", "properties": {}}), "audit.recent": ("Последние записи аудита Tool Gateway", {"type": "object", "properties": { "limit": {"type": "integer"}, "actor": {"type": "string"}}}), "docs.search": ("Поиск по документации репозитория", {"type": "object", "properties": { "query": {"type": "string"}}, "required": ["query"]}), "hub.service_detail": ("Детали одной службы хаба по имени", {"type": "object", "properties": { "name": {"type": "string"}}, "required": ["name"]}), "alerts.active": ("Активные алерты Alertmanager", {"type": "object", "properties": {}}), "backup.status": ("Статус заданий бэкапа/проверки", {"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"]}), } 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()