[TOOLS] Tool Gateway подключён к секретарю через MCP: mcp.servers.toolgateway (stdio, env TG_URL/TG_TOKEN), агент вызывает 10 инструментов нативно. Проверено: hub.status (74/0), calendar.create (201, удалено), ha.states+ha.call (свет), аудит в SQLite. Добавлены ретрай hub.status, валидация аргументов (400), selfcheck-проверка Tool Gateway. Дальше: подтверждения через Matrix, rate limit, family-токен
This commit is contained in:
1 parent
623acdc690
commit
a026315f08
5 files changed
+187
-3
No files matched your search
+19
-1
@@ -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"})
|
||||
|
||||
Executable
+104
@@ -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()
|
||||
Reference in new issue
Block a user