Files
ai-agent/backend/plugins/hubmachines.py
gabrielvidalandClaude Opus 5.5 77a545444f feat(relay): a dial-out worker's public token passes on the guest host
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>
2026-11-26 22:06:52 +01:00

244 lines
10 KiB
Python

"""``machines.mcp`` — the owner's machines and their sidecar's MCP routes, for a
plugin's handlers (the ``mcp-servers`` plugin, 2026-11-26; homelab spec
``data/log/2026-11-26-ai-agent-mcp-plugin-spec.md`` §4.2).
Owner only, operator approval, the plugin's own handlers only:
* ``GET …/hub/machines`` — ``local`` (the Homelab, the host sidecar) first,
then each of the owner's paired workers (never a guest's computer, never one
still pending): ``{id, name, kind: lab|worker, status: online|offline,
platform?, account?, toolsUrl}``. ``toolsUrl`` is the ``AIA_TOOLS_URL`` that
machine's runs get — what a machine reaches the hub's relay on
(``plugins/relay.py``).
* ``GET|POST|DELETE …/hub/machines/{machine}/mcp[/{rest}]`` → that machine's
sidecar ``/mcp-servers[/{rest}]``, the JSON body and query passed through,
the sidecar's status and JSON body passed back as they are (its errors are
``{"detail": {"message", "kind"}}``). The bridge's own refusals carry the
same ``detail`` beside the usual ``error``: an offline or pending machine
409 ``worker_offline``, a guest's computer 403 ``forbidden``, an unknown one
404 ``unknown_machine``; a machine refusing the hub's token 502
``worker_auth``, one that doesn't answer in time 504 ``timeout``.
"""
from __future__ import annotations
import json
import logging
import os
import re
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from starlette.concurrency import run_in_threadpool
from plugins.proxyroutes import _active_plugin, _who
log = logging.getLogger(__name__)
router = APIRouter(include_in_schema=False)
CAP = "machines.mcp"
LAB = "local"
LAB_NAME = "Homelab"
# What a lab run's tool calls reach the hub on (runs/service.py).
LAB_TOOLS_URL = os.environ.get("TOOLS_PROXY_LAB_URL", "http://127.0.0.1:8096/proxy/tools")
_REST_RE = re.compile(r"^[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)*$")
_MACHINE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
MAX_BODY = 1024 * 1024
# The host sidecar's /health, checked at most this often (the lab's status).
_LAB_TTL_S = 15.0
_lab_seen: tuple[float, bool] | None = None
_lab_lock = threading.Lock()
def _refuse(status: int, message: str, kind: str) -> JSONResponse:
"""A refusal both a ``detail`` reader (the sidecar's shape) and an
``error`` reader (the other bridges') understand."""
d = {"message": message, "kind": kind}
return JSONResponse({"error": d, "detail": d}, status_code=status)
def _bridge(request: Request, pid: str):
"""(rec, error): the plugin's own handler, run for the owner, holding the
capability."""
who, err = _who(request, pid)
if err:
return None, err
if who.handler != pid:
return None, _refuse(403, f"{CAP} is only available to the plugin's own handlers",
"handler_only")
if not who.is_owner:
return None, _refuse(403, f"{CAP} is owner-only", "capability")
_, rec, _, _, err = _active_plugin(request.app.state.ai, who, pid)
if err:
return None, err
if CAP not in (rec["manifest"].get("capabilities") or []):
return None, _refuse(403, f"plugin lacks {CAP} capability", "capability")
return rec, None
# ── the machines ─────────────────────────────────────────────────────────────
def lab_online() -> bool:
"""The host sidecar answers ``/health`` (cached :data:`_LAB_TTL_S`)."""
global _lab_seen
now = time.monotonic()
with _lab_lock:
if _lab_seen and now - _lab_seen[0] < _LAB_TTL_S:
return _lab_seen[1]
from runs.sidecar_client import _sidecar_get
ok = _sidecar_get("/health", timeout=3) is not None
with _lab_lock:
_lab_seen = (time.monotonic(), ok)
return ok
def eligible(w: dict) -> bool:
"""An owner's machine, paired: never a guest's computer, never pending."""
return not w.get("owner") and not w.get("pending")
def machines_payload(deps) -> list[dict[str, Any]]:
from core.state import tool_hub_url
from users.deliver import GUEST_PUBLIC_URL
store = deps.worker_store
rows: list[dict[str, Any]] = [{
"id": LAB, "name": LAB_NAME, "kind": "lab",
"status": "online" if lab_online() else "offline",
"toolsUrl": LAB_TOOLS_URL,
}]
for w in store.list():
if not eligible(w):
continue
# A dial-out worker (``link``) is off the tailnet: it reaches the hub
# only on the guest host, like its link — so does its tools URL, and
# its relay token must be a ``public`` one (relay.py).
public = bool(w.get("link"))
tools = f"{GUEST_PUBLIC_URL}/proxy/tools" if public and GUEST_PUBLIC_URL \
else tool_hub_url(w)
rows.append({
"id": w["id"], "name": w.get("name") or w["id"], "kind": "worker",
"status": "online" if store.online(w["id"]) else "offline",
"platform": w.get("platform"), "account": w.get("account"),
"toolsUrl": tools or None, "public": public,
})
return rows
@router.get("/proxy/tools/plugins/{pid}/hub/machines")
async def hub_machines(pid: str, request: Request):
_rec, err = _bridge(request, pid)
if err:
return err
return await run_in_threadpool(machines_payload, request.app.state.ai)
# ── a machine's /mcp-servers ─────────────────────────────────────────────────
def timeout_for(method: str, rest: str) -> float:
"""POST ``/mcp-servers`` (an apply: ``claude mcp add-json`` per server)
300 s, a sign-in's start 60 s, its callback 90 s, anything else 30 s."""
if method == "POST" and rest == "":
return 300.0
if rest == "login" and method == "POST":
return 60.0
if rest == "login/callback":
return 90.0
return 30.0
def target(deps, machine: str) -> tuple[dict[str, str] | None, JSONResponse | None]:
"""``({url, token, label}, None)`` of a machine's sidecar, or a refusal."""
if machine in (LAB, "lab"):
from core.config import SIDECAR_TOKEN, SIDECAR_URL
if not SIDECAR_TOKEN:
return None, _refuse(409, "the host sidecar isn't configured", "worker_offline")
return {"url": SIDECAR_URL, "token": SIDECAR_TOKEN, "label": LAB_NAME}, None
if not _MACHINE_RE.match(machine or ""):
return None, _refuse(404, f"unknown machine: {machine!r}", "unknown_machine")
store = deps.worker_store
w = store.get(machine)
if not w:
return None, _refuse(404, f"unknown machine: {machine!r}", "unknown_machine")
name = w.get("name") or w["id"]
if w.get("owner"):
return None, _refuse(403, "a guest's computer sets up its own MCP servers", "forbidden")
if w.get("pending"):
return None, _refuse(409, f"{name} isn't paired yet", "worker_offline")
if not store.online(w["id"]):
return None, _refuse(409, f"{name} is offline", "worker_offline")
return {"url": w["url"], "token": w["token"], "label": name}, None
def call(m: dict[str, str], method: str, path: str, body: bytes | None,
timeout: float) -> tuple[int, Any]:
"""One sidecar call: ``(status, its JSON)``. A refused hub token is a 502
``worker_auth`` (nothing a plugin can fix); an unreachable machine a 409
``worker_offline``."""
req = urllib.request.Request(
f"{m['url']}{path}", data=body, method=method,
headers={"Content-Type": "application/json", "Accept": "application/json",
"Authorization": f"Bearer {m['token']}"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
raw, status = r.read(), r.status
except urllib.error.HTTPError as e:
raw, status = e.read(), e.code
if status in (401, 403):
again = "check SIDECAR_TOKEN" if m["label"] == LAB_NAME else "pair it again"
d = {"message": f"{m['label']} refused the hub's token — {again}", "kind": "worker_auth"}
return 502, {"error": d, "detail": d}
except (urllib.error.URLError, OSError, ValueError) as e:
why = getattr(e, "reason", e)
if isinstance(why, TimeoutError):
d = {"message": f"{m['label']} didn't answer within {int(timeout)} s", "kind": "timeout"}
return 504, {"error": d, "detail": d}
d = {"message": f"{m['label']} unreachable: {why}"[:300], "kind": "worker_offline"}
return 409, {"error": d, "detail": d}
try:
return status, json.loads(raw.decode() or "null")
except ValueError:
d = {"message": f"{m['label']} answered HTTP {status} without JSON", "kind": "bad_answer"}
return 502, {"error": d, "detail": d}
@router.api_route("/proxy/tools/plugins/{pid}/hub/machines/{machine}/mcp",
methods=["GET", "POST", "DELETE"])
async def hub_machine_mcp(pid: str, machine: str, request: Request):
return await _machine_mcp(pid, machine, request, "")
@router.api_route("/proxy/tools/plugins/{pid}/hub/machines/{machine}/mcp/{rest:path}",
methods=["GET", "POST", "DELETE"])
async def hub_machine_mcp_rest(pid: str, machine: str, rest: str, request: Request):
return await _machine_mcp(pid, machine, request, rest)
async def _machine_mcp(pid: str, machine: str, request: Request, rest: str):
_rec, err = _bridge(request, pid)
if err:
return err
rest = rest.strip("/")
if rest and (not _REST_RE.match(rest) or ".." in rest.split("/")):
return _refuse(400, "bad path", "bad_request")
body = None
if request.method == "POST":
body = await request.body()
if len(body) > MAX_BODY:
return _refuse(413, "body too large", "bad_request")
body = body or b"{}"
deps = request.app.state.ai
m, err = target(deps, machine)
if err:
return err
path = "/mcp-servers" + (f"/{rest}" if rest else "")
q = request.url.query
if q:
path += "?" + urllib.parse.urlencode(urllib.parse.parse_qsl(q, keep_blank_values=True))
status, out = await run_in_threadpool(
call, m, request.method, path, body, timeout_for(request.method, rest))
return JSONResponse(out, status_code=status)