[STAGE5] Tool Gateway runtime + hub-tools service
lint / hygiene (pull_request) Failing after 27s
lint / hygiene (push) Failing after 19s
standard / check (push) Successful in 8s
standard / check (pull_request) Successful in 7s

This commit is contained in:
architect committed 2026-11-27 21:13:08 +03:00
1 parent 649386f0b8
commit 7735ddff28
4 files changed
+135 -1

No files matched your search

+8 -1
View File
@@ -51,7 +51,7 @@ services:
tier: 0
ct: 108
owner: roman
endpoint: "http://127.0.0.1:9120/status"
endpoint: "http://127.0.0.1:9120/health"
health: "http"
backup: "config"
restore: "config"
@@ -89,3 +89,10 @@ services:
endpoint: "http://192.168.1.108:5680/healthz"
health: "http"
note: "port 5680 -> container 5678"
- id: hub-tools
tier: 1
ct: 10
owner: roman
endpoint: "http://127.0.0.1:9137/health"
health: "http"
note: "Tool Gateway; agents must use this for tools"
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=Buryans Tool Gateway
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /root/buryan-infra/ops/ai/tool_gateway_server.py
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
+14
View File
@@ -0,0 +1,14 @@
import sys, unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from tool_gateway_server import tools
class GatewayServerTests(unittest.TestCase):
def test_policy_loads(self):
t = tools()
self.assertIn("catalog.read", t)
self.assertEqual(t["catalog.read"]["mode"], "read")
self.assertTrue(t["notify.send"]["approval"])
if __name__ == "__main__":
unittest.main()
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Stage 5 Tool Gateway: allowlisted proxy for agents.
Listens on 127.0.0.1:9137. It never exposes production directly:
agents call a named tool, the gateway validates policy and forwards.
Write tools require X-Approval: approved.
"""
import json
import os
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
import yaml
POLICY = "/root/buryan-infra/docs/architecture/REGISTRY/tool_gateway.yaml"
LOG = "/var/log/hub-tools/gateway.jsonl"
HOST, PORT = "127.0.0.1", 9137
def tools():
return {t["name"]: t for t in (yaml.safe_load(open(POLICY).read()).get("tools") or [])}
def log(entry):
os.makedirs(os.path.dirname(LOG), exist_ok=True)
with open(LOG, "a") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
class H(BaseHTTPRequestHandler):
def _json(self, code, obj):
b = json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
u = urlparse(self.path)
if u.path == "/health":
return self._json(200, {"ok": True, "service": "hub-tools", "tools": len(tools())})
if u.path == "/v1/tools":
return self._json(200, {"tools": list(tools().values())})
if u.path != "/v1/call":
return self._json(404, {"error": "not found"})
name = (parse_qs(u.query).get("tool") or [""])[0]
t = tools().get(name)
if not t:
return self._json(404, {"error": "unknown tool"})
if t["mode"] != "read":
return self._json(403, {"error": "write tool requires POST approval"})
try:
req = urllib.request.Request(t["gateway"], method="GET")
with urllib.request.urlopen(req, timeout=10) as r:
body = r.read(200000).decode("utf-8", "replace")
log({"tool": name, "mode": "read", "code": 200})
return self._json(200, {"tool": name, "upstream": t["gateway"], "body": body})
except Exception as e:
log({"tool": name, "mode": "read", "error": str(e)[:200]})
return self._json(502, {"error": str(e)[:200]})
def do_POST(self):
u = urlparse(self.path)
if u.path != "/v1/call":
return self._json(404, {"error": "not found"})
n = int(self.headers.get("Content-Length") or 0)
try:
data = json.loads(self.rfile.read(n) or b"{}")
except Exception:
return self._json(400, {"error": "bad json"})
name = data.get("tool")
t = tools().get(name)
if not t:
return self._json(404, {"error": "unknown tool"})
if t["mode"] != "write":
return self._json(200, {"error": "read tool; use GET"})
if t.get("approval") and self.headers.get("X-Approval") != "approved":
log({"tool": name, "mode": "write", "code": 403})
return self._json(403, {"error": "approval required"})
try:
payload = json.dumps(data.get("body") or {}, ensure_ascii=False).encode()
req = urllib.request.Request(t["gateway"], data=payload, method="POST",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
body = r.read(200000).decode("utf-8", "replace")
log({"tool": name, "mode": "write", "code": 200})
return self._json(200, {"tool": name, "body": body})
except Exception as e:
log({"tool": name, "mode": "write", "error": str(e)[:200]})
return self._json(502, {"error": str(e)[:200]})
def log_message(self, *a):
pass
if __name__ == "__main__":
ThreadingHTTPServer((HOST, PORT), H).serve_forever()