The Orus devbox (a dial-out worker, off the personal tailnet) can't reach ai-agent.lab: its MCP server through the hub failed with a TLS error. GET hub/machines now gives a link worker the guest host's tools URL and public: true; relay tokens carry public (mint / PUT), and the guest host lets only those through (anything else there, a wrong token included, is a 404). The owner's internet address still never serves the relay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
388 lines
20 KiB
Python
388 lines
20 KiB
Python
"""The host features the ``mcp-servers`` plugin builds on (2026-11-26, homelab
|
|
spec ``2026-11-26-ai-agent-mcp-plugin-spec.md`` §4): the manifest's new
|
|
capabilities / slot / provides / page nav, the ``machines.mcp`` bridge to
|
|
each machine's sidecar ``/mcp-servers`` (a fake sidecar here), ``provides:
|
|
machine.attention`` and ``GET /api/machines/attention``, and the carry-over
|
|
of the core's old ``/data/mcp-servers.json``."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import http.server
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
|
|
"META_PATH": TMP / "meta.json", "USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import carryover, hubmachines, machine_attention # noqa: E402
|
|
from plugins.manifest import ManifestError, capability_summary, requires_operator, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
from users.caller import guest_from_record # noqa: E402
|
|
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
|
|
|
|
def _write(root: pathlib.Path, manifest: dict, files: dict) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(manifest))
|
|
for rel, body in files.items():
|
|
p = root / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text(body)
|
|
return root
|
|
|
|
|
|
def _install(td, manifest, files=None) -> PluginStore:
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src", manifest, files or {})),
|
|
is_owner=True, approve=True)
|
|
return store
|
|
|
|
|
|
MF = {"schema": 1, "id": "mcp-servers", "name": "MCP servers",
|
|
"capabilities": ["machines.mcp", "relay.serve"],
|
|
"actions": {"attention": {"script": "handlers/attention.py", "readOnly": True},
|
|
"view": {"script": "handlers/attention.py", "readOnly": True},
|
|
"save": {"script": "handlers/save.py"}},
|
|
"provides": {"machine.attention": "attention"},
|
|
"ui": {"pages": [{"id": "servers", "label": "MCP servers", "nav": "tools", "html": "ui/p.html"},
|
|
{"id": "callback", "label": "Signed in", "nav": "none", "html": "ui/p.html"}],
|
|
"slots": [{"id": "machine", "where": "machine.detail", "html": "ui/p.html"}]}}
|
|
FILES = {"ui/p.html": "<p>x</p>",
|
|
"handlers/attention.py": "import json, sys\nsys.stdin.read()\nprint(json.dumps({'items': ["
|
|
"{'machine': 'local', 'key': 'signin', 'title': '2 MCP servers need a sign-in',"
|
|
" 'detail': 'linear, sentry', 'tone': 'warn'},"
|
|
"{'machine': 'w1', 'key': 'failed', 'title': 'sentry failed', 'tone': 'error'},"
|
|
"{'machine': '../x', 'key': 'k', 'title': 'bad machine'},"
|
|
"{'machine': 'w1', 'title': 'no key'}]}))\n",
|
|
"handlers/save.py": "import sys\nsys.stdin.read()\nprint('{}')\n"}
|
|
|
|
|
|
class Manifest(unittest.TestCase):
|
|
def test_the_new_keys_validate_and_ask_the_operator(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "p", MF, FILES))
|
|
self.assertEqual(mf["capabilities"], ["machines.mcp", "relay.serve"])
|
|
self.assertEqual(mf["provides"], {"machine.attention": "attention"})
|
|
self.assertEqual([p["nav"] for p in mf["ui"]["pages"]], ["tools", "none"])
|
|
self.assertEqual(mf["ui"]["slots"][0]["where"], "machine.detail")
|
|
self.assertTrue(requires_operator(mf))
|
|
caps = [c for c in capability_summary(mf) if c["kind"] == "capability"]
|
|
self.assertTrue(all(c["privileged"] and "Hub capability:" not in c["label"] for c in caps))
|
|
prov = next(c for c in capability_summary(mf) if c["kind"] == "provides")
|
|
self.assertIn("Needs you", prov["label"])
|
|
|
|
def test_an_unknown_nav_is_still_refused(self):
|
|
bad = {**MF, "ui": {"pages": [{"id": "p", "label": "P", "nav": "hidden", "html": "ui/p.html"}]}}
|
|
with tempfile.TemporaryDirectory() as td, self.assertRaises(ManifestError):
|
|
validate_manifest(_write(pathlib.Path(td) / "p", bad, FILES))
|
|
|
|
|
|
# ── machines.mcp ─────────────────────────────────────────────────────────────
|
|
class FakeSidecar(http.server.ThreadingHTTPServer):
|
|
daemon_threads = True
|
|
|
|
def __init__(self, token):
|
|
super().__init__(("127.0.0.1", 0), SidecarHandler)
|
|
self.token, self.seen = token, []
|
|
|
|
@property
|
|
def url(self):
|
|
return f"http://127.0.0.1:{self.server_address[1]}"
|
|
|
|
|
|
class SidecarHandler(http.server.BaseHTTPRequestHandler):
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def _go(self):
|
|
n = int(self.headers.get("Content-Length") or 0)
|
|
body = self.rfile.read(n).decode() if n else ""
|
|
self.server.seen.append((self.command, self.path, body))
|
|
if self.path == "/mcp-servers/slow":
|
|
import time
|
|
time.sleep(2)
|
|
if self.headers.get("Authorization") != f"Bearer {self.server.token}":
|
|
status, out = 401, {"detail": "bad token"}
|
|
elif self.path == "/mcp-servers" and self.command == "GET":
|
|
status, out = 200, {"mcpServers": {"version": 2, "logins": []}}
|
|
elif self.path == "/mcp-servers" and self.command == "POST":
|
|
status, out = 200, {"results": {"linear": {"ok": True}}, "echo": json.loads(body)}
|
|
elif self.path.startswith("/mcp-servers/login") and self.command == "POST":
|
|
status, out = 409, {"detail": {"message": "agy can't sign in", "kind": "unsupported"}}
|
|
else:
|
|
status, out = 200, {"ok": True, "path": self.path}
|
|
raw = json.dumps(out).encode()
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(raw)))
|
|
self.end_headers()
|
|
self.wfile.write(raw)
|
|
|
|
do_GET = do_POST = do_DELETE = _go
|
|
|
|
|
|
class FakeWorkers:
|
|
def __init__(self, workers, online):
|
|
self.w, self.on = {w["id"]: w for w in workers}, set(online)
|
|
|
|
def list(self):
|
|
return list(self.w.values())
|
|
|
|
def get(self, wid):
|
|
return self.w.get(wid)
|
|
|
|
def online(self, wid):
|
|
return wid in self.on
|
|
|
|
def status(self, wid):
|
|
return {"status": "online" if wid in self.on else "offline"}
|
|
|
|
|
|
class MachinesBridge(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.lab = FakeSidecar("lab-tok")
|
|
cls.mac = FakeSidecar("mac-tok")
|
|
for s in (cls.lab, cls.mac):
|
|
threading.Thread(target=s.serve_forever, daemon=True).start()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.lab.shutdown()
|
|
cls.mac.shutdown()
|
|
|
|
def setUp(self):
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.store = _install(self.td.name, MF, FILES)
|
|
workers = FakeWorkers([
|
|
{"id": "w1", "name": "Orus Mac", "url": self.mac.url, "token": "mac-tok", "platform": "darwin",
|
|
"account": "work"},
|
|
{"id": "w2", "name": "Off box", "url": "http://127.0.0.1:9", "token": "x"},
|
|
{"id": "w3", "name": "Wrong token", "url": self.mac.url, "token": "stale"},
|
|
{"id": "g1", "name": "Cel's", "url": self.mac.url, "token": "mac-tok", "owner": "cel"},
|
|
{"id": "p1", "name": "Pending", "url": self.mac.url, "token": "mac-tok", "pending": True},
|
|
], online=["w1", "w3", "g1", "p1"])
|
|
deps = main.app.state.ai
|
|
self.patches = [patch.object(deps, "plugin_store", self.store),
|
|
patch.object(deps, "worker_store", workers),
|
|
patch("core.config.SIDECAR_URL", self.lab.url),
|
|
patch("core.config.SIDECAR_TOKEN", "lab-tok"),
|
|
patch.object(hubmachines, "lab_online", return_value=True)]
|
|
for p in self.patches:
|
|
p.start()
|
|
self.tc = TestClient(main.app)
|
|
self.h = {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'mcp-servers', ttl=600)}"}
|
|
self.base = "/proxy/tools/plugins/mcp-servers/hub/machines"
|
|
|
|
def tearDown(self):
|
|
for p in reversed(self.patches):
|
|
p.stop()
|
|
self.td.cleanup()
|
|
|
|
def test_the_owners_machines_lab_first(self):
|
|
r = self.tc.get(self.base, headers=self.h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
rows = r.json()
|
|
self.assertEqual([m["id"] for m in rows], ["local", "w1", "w2", "w3"])
|
|
self.assertEqual(rows[0]["kind"], "lab")
|
|
self.assertEqual(rows[0]["toolsUrl"], hubmachines.LAB_TOOLS_URL)
|
|
w1 = rows[1]
|
|
self.assertEqual((w1["kind"], w1["status"], w1["platform"], w1["account"]),
|
|
("worker", "online", "darwin", "work"))
|
|
self.assertTrue(w1["toolsUrl"].endswith("/proxy/tools"))
|
|
self.assertIs(w1["public"], False)
|
|
self.assertEqual(rows[2]["status"], "offline")
|
|
|
|
def test_a_dial_out_worker_reaches_the_hub_on_the_guest_host(self):
|
|
main.app.state.ai.worker_store.w["wd"] = {"id": "wd", "name": "Devbox", "url": self.mac.url,
|
|
"token": "mac-tok", "link": True}
|
|
with patch("users.deliver.GUEST_PUBLIC_URL", "https://ai-agent.example"):
|
|
rows = self.tc.get(self.base, headers=self.h).json()
|
|
d = [m for m in rows if m["id"] == "wd"][0]
|
|
self.assertEqual((d["toolsUrl"], d["public"]), ("https://ai-agent.example/proxy/tools", True))
|
|
|
|
def test_calls_pass_through_to_the_sidecar(self):
|
|
r = self.tc.get(f"{self.base}/local/mcp", headers=self.h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["mcpServers"]["version"], 2)
|
|
body = {"harness": "claude", "account": "work", "add": [], "remove": ["old"]}
|
|
r = self.tc.post(f"{self.base}/w1/mcp", headers=self.h, json=body)
|
|
self.assertEqual(r.json()["echo"], body)
|
|
r = self.tc.post(f"{self.base}/w1/mcp/login", headers=self.h,
|
|
json={"harness": "agy", "account": "g", "name": "x"})
|
|
self.assertEqual(r.status_code, 409)
|
|
self.assertEqual(r.json()["detail"]["kind"], "unsupported")
|
|
r = self.tc.delete(f"{self.base}/w1/mcp/login/abc123", headers=self.h)
|
|
self.assertEqual(r.json()["path"], "/mcp-servers/login/abc123")
|
|
self.assertEqual(self.mac.seen[-1][0], "DELETE")
|
|
|
|
def test_refusals(self):
|
|
def kind(path, method="GET"):
|
|
r = self.tc.request(method, f"{self.base}/{path}", headers=self.h, json={})
|
|
return r.status_code, r.json()["detail"]["kind"]
|
|
self.assertEqual(kind("g1/mcp"), (403, "forbidden"))
|
|
self.assertEqual(kind("p1/mcp"), (409, "worker_offline"))
|
|
self.assertEqual(kind("w2/mcp"), (409, "worker_offline"))
|
|
self.assertEqual(kind("nope/mcp"), (404, "unknown_machine"))
|
|
self.assertEqual(kind("w3/mcp"), (502, "worker_auth"))
|
|
self.assertEqual(kind("w1/mcp/..%2F..%2Fsessions")[0], 400)
|
|
with patch.object(hubmachines, "timeout_for", return_value=0.5):
|
|
self.assertEqual(kind("w1/mcp/slow"), (504, "timeout"))
|
|
|
|
def test_only_the_plugins_handler_with_the_capability(self):
|
|
guest = {"Authorization": f"Bearer {access.mint_handler('cel', 'mcp-servers', ttl=600)}"}
|
|
self.assertIn(self.tc.get(self.base, headers=guest).status_code, (403, 404))
|
|
self.assertEqual(self.tc.get(self.base).status_code, 401)
|
|
with tempfile.TemporaryDirectory() as td:
|
|
bare = _install(td, {**MF, "capabilities": ["relay.serve"]}, FILES)
|
|
with patch.object(main.app.state.ai, "plugin_store", bare):
|
|
self.assertEqual(self.tc.get(self.base, headers=self.h).status_code, 403)
|
|
|
|
def test_timeouts(self):
|
|
self.assertEqual(hubmachines.timeout_for("POST", ""), 300)
|
|
self.assertEqual(hubmachines.timeout_for("POST", "login"), 60)
|
|
self.assertEqual(hubmachines.timeout_for("POST", "login/callback"), 90)
|
|
self.assertEqual(hubmachines.timeout_for("GET", ""), 30)
|
|
self.assertEqual(hubmachines.timeout_for("POST", "refresh"), 30)
|
|
|
|
|
|
# ── machine.attention ────────────────────────────────────────────────────────
|
|
class Attention(unittest.TestCase):
|
|
def setUp(self):
|
|
machine_attention.invalidate()
|
|
|
|
def tearDown(self):
|
|
machine_attention.invalidate()
|
|
|
|
def test_items_cached_and_dropped_by_a_change(self):
|
|
deps = main.app.state.ai
|
|
tc = TestClient(main.app, headers=OWNER_H)
|
|
published = []
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = _install(td, MF, FILES)
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch.object(deps.hub, "publish", side_effect=published.append):
|
|
r = tc.get("/api/machines/attention")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
items = r.json()["items"]
|
|
self.assertEqual([(i["machine"], i["key"], i["tone"]) for i in items],
|
|
[("local", "signin", "warn"), ("w1", "failed", "error")])
|
|
self.assertEqual(items[0]["pluginId"], "mcp-servers")
|
|
self.assertEqual(items[0]["detail"], "linear, sentry")
|
|
with patch("plugins.runner.run_script") as run:
|
|
tc.get("/api/machines/attention")
|
|
run.assert_not_called() # cached
|
|
# a read-only action changes nothing…
|
|
tc.post("/api/plugins/mcp-servers/actions/view", json={})
|
|
self.assertNotIn({"type": "machine-attention"}, published)
|
|
# …any other does
|
|
tc.post("/api/plugins/mcp-servers/actions/save", json={})
|
|
self.assertIn({"type": "machine-attention"}, published)
|
|
with patch("plugins.runner.run_script", return_value={"items": []}) as run:
|
|
self.assertEqual(tc.get("/api/machines/attention").json()["items"], [])
|
|
run.assert_called_once()
|
|
|
|
def test_owner_only(self):
|
|
from plugins.routes import machines_attention
|
|
guest = guest_from_record({"id": "cel", "name": "Cel"})
|
|
with self.assertRaises(HTTPException) as e:
|
|
machines_attention(main.app.state.ai, guest)
|
|
self.assertEqual(e.exception.status_code, 403)
|
|
from authz.routes import TABLE
|
|
self.assertEqual(TABLE[("GET", "/api/machines/attention")], "lab.read")
|
|
|
|
def test_no_provider_no_items(self):
|
|
with tempfile.TemporaryDirectory() as td, \
|
|
patch.object(main.app.state.ai, "plugin_store", PluginStore(pathlib.Path(td))):
|
|
r = TestClient(main.app, headers=OWNER_H).get("/api/machines/attention")
|
|
self.assertEqual(r.json(), {"items": []})
|
|
|
|
def test_normalize(self):
|
|
out = machine_attention.normalize("p", {"items": [
|
|
{"machine": "local", "key": "k", "title": " t\n x ", "tone": "loud"}, "junk",
|
|
{"machine": "local", "key": "k2"}]})
|
|
self.assertEqual(out, [{"pluginId": "p", "machine": "local", "key": "k", "title": "t x", "tone": "warn"}])
|
|
self.assertEqual(machine_attention.normalize("p", None), [])
|
|
|
|
|
|
# ── carry-over ───────────────────────────────────────────────────────────────
|
|
class CarryOver(unittest.TestCase):
|
|
def _legacy(self, td):
|
|
p = pathlib.Path(td) / "mcp-servers.json"
|
|
p.write_text(json.dumps({
|
|
"servers": {
|
|
"linear": {"transport": "http", "url": "https://mcp.linear.app/mcp", "headers": {},
|
|
"accounts": ["personal", "work", "guest-cel"], "preset": "linear", "createdAt": 1},
|
|
"fs": {"transport": "stdio", "command": "npx", "args": ["-y", "fs"], "env": {"K": "v"},
|
|
"accounts": ["work"], "createdAt": 2},
|
|
"../bad": {"transport": "http", "url": "https://x"}},
|
|
"lab": {"overrides": {"linear": False}}}))
|
|
return p
|
|
|
|
def test_once_the_plugin_is_installed(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
legacy = self._legacy(td)
|
|
store = PluginStore(pathlib.Path(td) / "plugins")
|
|
workers = FakeWorkers([{"id": "w1", "mcpServerOverrides": {"fs": False, "x": "no"}},
|
|
{"id": "g1", "owner": "cel", "mcpServerOverrides": {"fs": True}}], [])
|
|
# not installed: waits
|
|
self.assertFalse(carryover.mcp_servers(store, workers, str(legacy)))
|
|
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src", MF, FILES)),
|
|
is_owner=True, approve=True)
|
|
shared = store.shared_data_dir("mcp-servers")
|
|
priv = shared / "_private"
|
|
priv.mkdir(parents=True)
|
|
(priv / "servers.json").write_text(json.dumps({"servers": {"fs": {"transport": "stdio",
|
|
"command": "mine"}}}))
|
|
self.assertTrue(carryover.mcp_servers(store, workers, str(legacy)))
|
|
servers = json.loads((priv / "servers.json").read_text())["servers"]
|
|
self.assertEqual(sorted(servers), ["fs", "linear"])
|
|
self.assertEqual(servers["fs"]["command"], "mine") # the plugin's own wins
|
|
lin = servers["linear"]
|
|
self.assertEqual(lin["accounts"], ["claude:personal", "claude:work"])
|
|
self.assertEqual((lin["mode"], lin["url"], lin["preset"]), ("direct", "https://mcp.linear.app/mcp", "linear"))
|
|
ov = json.loads((priv / "overrides.json").read_text())
|
|
self.assertEqual(ov, {"local": {"linear": False}, "w1": {"fs": False}})
|
|
for f in ("servers.json", "overrides.json"):
|
|
self.assertEqual((priv / f).stat().st_mode & 0o777, 0o600)
|
|
self.assertTrue((shared / ".carried-over").exists())
|
|
self.assertTrue(legacy.exists()) # never deleted
|
|
self.assertFalse(carryover.mcp_servers(store, workers, str(legacy))) # once
|
|
|
|
def test_nothing_to_carry(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = _install(td, MF, FILES)
|
|
self.assertFalse(carryover.mcp_servers(store, None, str(pathlib.Path(td) / "absent.json")))
|
|
self.assertFalse((store.shared_data_dir("mcp-servers") / ".carried-over").exists())
|
|
|
|
def test_installing_the_plugin_carries_over(self):
|
|
deps = main.app.state.ai
|
|
with tempfile.TemporaryDirectory() as td:
|
|
legacy = self._legacy(td)
|
|
store = PluginStore(pathlib.Path(td) / "plugins")
|
|
src = _write(pathlib.Path(td) / "src", MF, FILES)
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch.object(carryover, "MCP_SERVERS_LEGACY_PATH", str(legacy)), \
|
|
patch.object(carryover.mcp_servers, "__defaults__", (None, str(legacy))):
|
|
r = TestClient(main.app, headers=OWNER_H).post("/api/plugins/install", json={"source": str(src)})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertTrue((store.shared_data_dir("mcp-servers") / ".carried-over").exists())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|