An MCP client that gets a 401 (even without WWW-Authenticate) looks for /.well-known/oauth-protected-resource at the hub's origin, which the hub's own MCP server answers. Every relay refusal (bad token, unlisted route, upstream signed out) is now a 403 relay_auth / relay_unauthorized; the sidecar probe reads the relay's message from either status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1069 lines
43 KiB
Python
1069 lines
43 KiB
Python
"""
|
||
MCP servers, the core's generic half — what every harness's MCP adapter
|
||
shares (MCP plugin spec §2, ``~/homelab/data/log/2026-11-26-ai-agent-mcp-plugin-spec.md``).
|
||
|
||
The hub's ``mcp-servers`` plugin sets up, signs in and approves the MCP
|
||
servers the owner wants on each machine, for each **login** — one harness ×
|
||
one account, keyed ``"<harness>:<account>"`` (``claude:personal``,
|
||
``opencode:chatgpt-work``, ``agy:google-personal``). How a harness stores and
|
||
lists its servers is its own business: each harness plugin's driver answers
|
||
``mcp_adapter()`` with an :class:`McpAdapter` (``sidecar/mcp.py`` in
|
||
harness-claude / harness-opencode / harness-agy). This module never names a
|
||
harness; ``routes_mcp.py`` is the thin HTTP layer on top.
|
||
|
||
What is here:
|
||
|
||
- the **canonical config** the hub sends (Claude-shaped:
|
||
``{"type": "http"|"sse", "url", "headers"}`` /
|
||
``{"type": "stdio", "command", "args", "env"}``), :func:`valid_config`,
|
||
:func:`config_hash` (the same function as the plugin's), :func:`redact`;
|
||
- the **managed store** — ``pairing.state_dir()/mcp-managed.json``,
|
||
``{"<harness>:<account>": {name: hash}}``: the servers the hub added, the
|
||
only ones it may replace or remove (a key without ``:`` — the file before
|
||
2026-11-26 — reads as ``claude:<key>`` and is rewritten on the next save);
|
||
- :func:`apply` — add / replace / remove the hub's servers on one login;
|
||
- the **listing cache**: every login's servers, health-checked by its adapter
|
||
in a background thread every ``TTL_S`` (30 min), after each change and when
|
||
the machine's page asks (``refresh_soon``) — :func:`report` never waits;
|
||
- :class:`PtyLogin` — a harness CLI's ``mcp login`` on a pty: the
|
||
provider's authorize URL it prints (``redirect_uri`` on localhost) is opened
|
||
on any device, and the address the browser ended on is pasted back and
|
||
replayed to the CLI's callback port here (:func:`finish_login`); a
|
||
connector link (a host the adapter names in ``connector_hosts``) needs no
|
||
paste;
|
||
- :func:`probe_http` / :func:`probe_stdio` — an MCP ``initialize`` against a
|
||
server, for the harnesses whose CLI has no health check of its own.
|
||
|
||
**Never on a guest's computer**: :func:`enabled` is False on a dial-out link
|
||
that isn't the owner's, and then nothing here reads or touches anything.
|
||
|
||
Secrets: header values and env values travel on stdin or in 0600 files, never
|
||
in argv; a listed ``target`` is always redacted (a URL loses its query string
|
||
and userinfo, a command keeps its program and first https URL); nothing here
|
||
logs a config.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import concurrent.futures
|
||
import functools
|
||
import hashlib
|
||
import json
|
||
import logging
|
||
import os
|
||
import pathlib
|
||
import pty
|
||
import re
|
||
import secrets
|
||
import selectors
|
||
import signal
|
||
import subprocess
|
||
import threading
|
||
import time
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
from typing import Callable
|
||
|
||
from fastapi import HTTPException
|
||
|
||
import config as _cfg
|
||
|
||
log = logging.getLogger("mcp")
|
||
|
||
# A listing health-checks every server (``claude mcp list`` starts every stdio
|
||
# one — an `npx mcp-remote` whose token expired can open a browser tab on a
|
||
# Mac), so the background one is rare; the machine's page asks for a fresh one.
|
||
TTL_S = 30 * 60
|
||
LOGIN_TTL_S = 10 * 60
|
||
URL_WAIT_S = 30
|
||
EXCHANGE_WAIT_S = 60
|
||
PROBE_WORKERS = 4
|
||
PROTOCOL_VERSION = "2025-06-18"
|
||
CLIENT_VERSION = "2"
|
||
|
||
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
||
# A listed server can carry spaces ("claude.ai Linear") or colons
|
||
# ("plugin:x:y") — only a name passed to a CLI or a file must be NAME_RE.
|
||
LISTED_NAME_RE = re.compile(r"^[^\x00-\x1f]{1,120}$")
|
||
ANSI = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[ -/]*[@-~]|\r")
|
||
URL_RE = re.compile(r"https://\S+")
|
||
_ANY_URL = re.compile(r"\b[a-z][a-z0-9+.-]*://[^\s'\"<>]+", re.I)
|
||
|
||
SOURCES = ("hub", "user", "local", "project", "plugin", "connector", "other")
|
||
STATUSES = ("connected", "needs_auth", "failed", "pending", "disabled", "unknown")
|
||
TRANSPORTS = ("http", "sse", "stdio")
|
||
DEFAULT_CAPS = {"login": False, "approve": False, "connectors": False,
|
||
"transports": TRANSPORTS}
|
||
|
||
|
||
# ── the adapter contract ──────────────────────────────────────────────────────
|
||
class McpError(Exception):
|
||
"""An adapter could not do what it was asked (``write`` / ``delete`` /
|
||
``approve`` / ``login_argv``). ``message`` is shown as is — never a secret."""
|
||
|
||
def __init__(self, message: str, kind: str = "apply_failed", status: int = 502):
|
||
super().__init__(message)
|
||
self.message = str(message)[:300]
|
||
self.kind = kind
|
||
self.status = status
|
||
|
||
|
||
class McpAdapter:
|
||
"""One harness's MCP know-how. Subclass it or duck-type it.
|
||
|
||
Required: ``harness_id``, ``accounts``, ``list_account``, ``own_names``,
|
||
``write``, ``delete``. ``login_argv`` when ``caps["login"]``, ``approve``
|
||
when ``caps["approve"]``. ``config_dir`` / ``cwd`` are what the report
|
||
shows (``cwd``: the directory a listing / sign-in runs in)."""
|
||
|
||
harness_id: str = ""
|
||
caps: dict = DEFAULT_CAPS
|
||
# Hosts whose link printed by a sign-in is a connector to approve there
|
||
# (nothing pasted back): ("claude.ai",) for Claude.
|
||
connector_hosts: tuple[str, ...] = ()
|
||
|
||
def accounts(self) -> list[str]:
|
||
return []
|
||
|
||
def config_dir(self, account: str) -> str:
|
||
return ""
|
||
|
||
def cwd(self, account: str) -> str:
|
||
return _cfg.DEFAULT_CWD
|
||
|
||
def list_account(self, account: str, managed: dict[str, str]) -> dict:
|
||
"""``{"servers": [{name, source, transport, target, status, detail,
|
||
managed}], "listError": str | None}`` — health-checked; may be slow."""
|
||
raise NotImplementedError
|
||
|
||
def own_names(self, account: str) -> set[str]:
|
||
"""The names already in the scope this adapter writes — ours and the
|
||
user's (a user's one of the same name is a conflict, left alone)."""
|
||
raise NotImplementedError
|
||
|
||
def write(self, account: str, name: str, config: dict) -> None:
|
||
raise McpError("this harness can't add MCP servers", "unsupported", 409)
|
||
|
||
def delete(self, account: str, name: str) -> None:
|
||
raise McpError("this harness can't remove MCP servers", "unsupported", 409)
|
||
|
||
|
||
def caps_of(adapter) -> dict:
|
||
"""The adapter's caps, every key there and ``transports`` a list."""
|
||
raw = getattr(adapter, "caps", None)
|
||
raw = raw if isinstance(raw, dict) else {}
|
||
out = {k: bool(raw.get(k, v)) for k, v in DEFAULT_CAPS.items() if k != "transports"}
|
||
t = raw.get("transports", DEFAULT_CAPS["transports"])
|
||
out["transports"] = [x for x in TRANSPORTS if x in (t or ())]
|
||
if out["login"] and not callable(getattr(adapter, "login_argv", None)):
|
||
out["login"] = False
|
||
if out["approve"] and not callable(getattr(adapter, "approve", None)):
|
||
out["approve"] = False
|
||
return out
|
||
|
||
|
||
def login_key(harness: str, account: str) -> str:
|
||
return f"{harness}:{account}"
|
||
|
||
|
||
# ── where ─────────────────────────────────────────────────────────────────────
|
||
def enabled() -> bool:
|
||
"""False on a guest's own computer (a link that isn't the owner's)."""
|
||
if not _cfg.IS_WORKER:
|
||
return True
|
||
try:
|
||
import link
|
||
cfg = link.config()
|
||
except Exception:
|
||
cfg = None
|
||
return not cfg or bool(cfg.get("owner"))
|
||
|
||
|
||
def adapters() -> list:
|
||
"""Every loaded harness driver's adapter (``mcp_adapter()`` not None):
|
||
claude first, then by harness id. A driver whose adapter breaks is
|
||
skipped — never the others."""
|
||
import harness_loader
|
||
out = []
|
||
for d in harness_loader.drivers():
|
||
fn = getattr(d, "mcp_adapter", None)
|
||
if not callable(fn):
|
||
continue
|
||
try:
|
||
a = fn()
|
||
except Exception: # noqa: BLE001 — one broken adapter never hides the others
|
||
log.exception("mcp_adapter of %r", getattr(d, "harness_id", d))
|
||
continue
|
||
hid = getattr(a, "harness_id", None) if a is not None else None
|
||
if isinstance(hid, str) and hid:
|
||
out.append(a)
|
||
return sorted(out, key=lambda a: (a.harness_id != "claude", a.harness_id))
|
||
|
||
|
||
def adapter(harness: str | None):
|
||
for a in adapters():
|
||
if a.harness_id == (harness or "claude"):
|
||
return a
|
||
return None
|
||
|
||
|
||
def accounts_of(adapter) -> list[str]:
|
||
try:
|
||
return [a for a in (adapter.accounts() or []) if isinstance(a, str) and a]
|
||
except Exception: # noqa: BLE001
|
||
log.exception("accounts of %s", adapter.harness_id)
|
||
return []
|
||
|
||
|
||
def logins() -> list[tuple]:
|
||
"""``[(adapter, account)]`` — every login, in report order."""
|
||
return [(a, acct) for a in adapters() for acct in accounts_of(a)]
|
||
|
||
|
||
def forbidden() -> HTTPException:
|
||
return HTTPException(403, {"message": "a guest's computer sets up its own MCP servers",
|
||
"kind": "forbidden"})
|
||
|
||
|
||
def resolve(harness: str | None, account: str):
|
||
"""The adapter for a request on ``harness:account`` — or the HTTP error
|
||
the hub gets (forbidden / unknown_harness / unknown_account)."""
|
||
if not enabled():
|
||
raise forbidden()
|
||
harness = harness or "claude"
|
||
a = adapter(harness)
|
||
if a is None:
|
||
raise HTTPException(400, {"message": f"no {harness!r} harness with MCP servers here",
|
||
"kind": "unknown_harness"})
|
||
if account not in accounts_of(a):
|
||
raise HTTPException(400, {"message": f"no {harness} login {account!r} here",
|
||
"kind": "unknown_account"})
|
||
return a
|
||
|
||
|
||
# ── files ─────────────────────────────────────────────────────────────────────
|
||
def read_json(p: pathlib.Path) -> dict:
|
||
"""A JSON object file, ``{}`` when missing or unreadable."""
|
||
try:
|
||
v = json.loads(pathlib.Path(p).read_text(encoding="utf-8"))
|
||
return v if isinstance(v, dict) else {}
|
||
except (OSError, ValueError):
|
||
return {}
|
||
|
||
|
||
def write_json(p: pathlib.Path, data: dict, mode: int | None = None) -> None:
|
||
"""Write atomically (tmp + rename). ``mode`` None keeps the file's own."""
|
||
p = pathlib.Path(p)
|
||
p.parent.mkdir(parents=True, exist_ok=True)
|
||
tmp = p.with_name(f".{p.name}.{secrets.token_hex(4)}.tmp")
|
||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||
try:
|
||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||
f.write(json.dumps(data, indent=2) + "\n")
|
||
if mode is not None:
|
||
os.chmod(tmp, mode)
|
||
elif p.exists():
|
||
os.chmod(tmp, p.stat().st_mode & 0o777)
|
||
os.replace(tmp, p)
|
||
except BaseException:
|
||
try:
|
||
tmp.unlink()
|
||
except OSError:
|
||
pass
|
||
raise
|
||
|
||
|
||
# ── the canonical config ──────────────────────────────────────────────────────
|
||
def config_hash(config: dict) -> str:
|
||
"""Same function as the hub plugin's (spec §1)."""
|
||
return hashlib.sha256(json.dumps(config, sort_keys=True,
|
||
separators=(",", ":")).encode()).hexdigest()[:16]
|
||
|
||
|
||
def valid_config(cfg) -> bool:
|
||
if not isinstance(cfg, dict):
|
||
return False
|
||
t = cfg.get("type")
|
||
if t in ("http", "sse"):
|
||
u = cfg.get("url")
|
||
h = cfg.get("headers") or {}
|
||
return (isinstance(u, str) and bool(re.match(r"^https?://[^\s]+$", u))
|
||
and isinstance(h, dict)
|
||
and all(isinstance(k, str) and isinstance(v, str) and "\n" not in k + v
|
||
for k, v in h.items()))
|
||
if t == "stdio":
|
||
c, a, e = cfg.get("command"), cfg.get("args") or [], cfg.get("env") or {}
|
||
return (isinstance(c, str) and bool(c.strip()) and "\n" not in c
|
||
and isinstance(a, list) and all(isinstance(x, str) for x in a)
|
||
and isinstance(e, dict)
|
||
and all(isinstance(k, str) and isinstance(v, str) for k, v in e.items()))
|
||
return False
|
||
|
||
|
||
def redact(target: str) -> str:
|
||
"""A server's target without secrets: a URL keeps scheme, host and path; a
|
||
command its program's name plus the first https URL among its args. A
|
||
trailing ``(HTTP)``-style tag is kept. Idempotent."""
|
||
t = (target or "").strip()
|
||
suffix = ""
|
||
m = re.search(r"\s\((HTTP|SSE|WS|WebSocket|stdio)\)$", t, re.I)
|
||
if m:
|
||
suffix, t = f" ({m.group(1)})", t[:m.start()].strip()
|
||
if re.match(r"^[a-z][a-z0-9+.-]*://", t, re.I):
|
||
return bare_url(t) + suffix
|
||
parts = t.split()
|
||
if not parts:
|
||
return ""
|
||
prog = os.path.basename(parts[0])
|
||
url = next((bare_url(u) for u in URL_RE.findall(t)), None)
|
||
return (f"{prog} … {url}" if url else prog)[:200] + suffix
|
||
|
||
|
||
def bare_url(u: str) -> str:
|
||
"""A URL without its query, fragment and userinfo."""
|
||
try:
|
||
p = urllib.parse.urlsplit(u)
|
||
host = p.hostname or ""
|
||
if p.port:
|
||
host += f":{p.port}"
|
||
except ValueError:
|
||
return ""
|
||
return urllib.parse.urlunsplit((p.scheme, host, p.path, "", ""))[:200]
|
||
|
||
|
||
def scrub(text: str | None, limit: int = 200) -> str | None:
|
||
"""Free text (a CLI's error line) with every URL in it bare."""
|
||
if not text:
|
||
return None
|
||
out = _ANY_URL.sub(lambda m: bare_url(m.group(0)), str(text)).strip()
|
||
return out[:limit] or None
|
||
|
||
|
||
def last_line(out: str) -> str:
|
||
lines = [ln.strip() for ln in (out or "").splitlines() if ln.strip()]
|
||
return scrub(lines[-1], 300) or "" if lines else ""
|
||
|
||
|
||
def row(name: str, *, source: str, transport: str, target: str, status: str,
|
||
detail: str | None = None, managed: bool = False) -> dict:
|
||
"""One listed server, in the report's shape."""
|
||
return {"name": name, "source": source, "transport": transport, "target": target,
|
||
"status": status, "detail": detail, "managed": managed}
|
||
|
||
|
||
def _normalize(s: dict, mine: dict[str, str]) -> dict:
|
||
"""An adapter's row, held to the report's shape: known source / status,
|
||
target redacted, detail scrubbed and short."""
|
||
name = str(s.get("name") or "")[:120]
|
||
transport = str(s.get("transport") or "").lower()[:16] or "stdio"
|
||
return row(name,
|
||
source=s.get("source") if s.get("source") in SOURCES else "other",
|
||
transport=transport,
|
||
target=redact(str(s.get("target") or "")),
|
||
status=s.get("status") if s.get("status") in STATUSES else "unknown",
|
||
detail=scrub(s.get("detail")),
|
||
managed=bool(s["managed"]) if "managed" in s else name in mine)
|
||
|
||
|
||
# ── the managed store ─────────────────────────────────────────────────────────
|
||
_managed_lock = threading.RLock()
|
||
|
||
|
||
def managed_path() -> pathlib.Path:
|
||
import pairing
|
||
return pairing.state_dir() / "mcp-managed.json"
|
||
|
||
|
||
def _load_managed() -> dict[str, dict[str, str]]:
|
||
"""The whole store, keys as ``harness:account`` (a bare ``account`` — the
|
||
Claude-only file before — read as ``claude:account``)."""
|
||
raw = read_json(managed_path())
|
||
out: dict[str, dict[str, str]] = {}
|
||
# A new-style key wins over a legacy one naming the same login.
|
||
for k in sorted(raw, key=lambda k: ":" in k):
|
||
v = raw[k]
|
||
if not isinstance(k, str) or not isinstance(v, dict):
|
||
continue
|
||
key = k if ":" in k else login_key("claude", k)
|
||
out.setdefault(key, {}).update(
|
||
{n: h for n, h in v.items() if isinstance(n, str) and isinstance(h, str)})
|
||
return out
|
||
|
||
|
||
def managed(key: str) -> dict[str, str]:
|
||
"""``{name: hash}`` the hub added on that login."""
|
||
with _managed_lock:
|
||
return dict(_load_managed().get(key) or {})
|
||
|
||
|
||
def set_managed(key: str, name: str, h: str | None) -> None:
|
||
with _managed_lock:
|
||
data = _load_managed()
|
||
mine = data.setdefault(key, {})
|
||
if h is None:
|
||
mine.pop(name, None)
|
||
else:
|
||
mine[name] = h
|
||
if not mine:
|
||
data.pop(key, None)
|
||
write_json(managed_path(), data, 0o600)
|
||
|
||
|
||
# ── listing ───────────────────────────────────────────────────────────────────
|
||
_lock = threading.Lock()
|
||
_state: dict = {"at": 0.0, "running": False, "logins": {}}
|
||
_apply_lock = threading.Lock()
|
||
|
||
|
||
def list_login(adapter, account: str) -> dict:
|
||
"""One login's servers, health-checked by its adapter."""
|
||
key = login_key(adapter.harness_id, account)
|
||
mine = managed(key)
|
||
try:
|
||
got = adapter.list_account(account, dict(mine)) or {}
|
||
except Exception as e: # noqa: BLE001 — one broken login never hides the others
|
||
log.exception("mcp list %s", key)
|
||
return {"listedAt": int(time.time()),
|
||
"listError": scrub(str(e) or type(e).__name__, 300), "servers": None}
|
||
servers = got.get("servers")
|
||
if isinstance(servers, list):
|
||
servers = [_normalize(s, mine) for s in servers if isinstance(s, dict)]
|
||
else:
|
||
servers = None
|
||
at = got.get("listedAt")
|
||
return {"listedAt": int(at) if isinstance(at, (int, float)) and at else int(time.time()),
|
||
"listError": scrub(got.get("listError"), 300), "servers": servers}
|
||
|
||
|
||
def _refresh() -> None:
|
||
"""List every login: each harness in a thread of its own, its logins one
|
||
after the other (a CLI's listing starts every stdio server)."""
|
||
try:
|
||
by_harness: dict[str, list] = {}
|
||
for a, acct in logins():
|
||
by_harness.setdefault(a.harness_id, []).append((a, acct))
|
||
|
||
def one_harness(pairs):
|
||
return {login_key(a.harness_id, acct): list_login(a, acct) for a, acct in pairs}
|
||
|
||
got: dict[str, dict] = {}
|
||
if by_harness:
|
||
with concurrent.futures.ThreadPoolExecutor(
|
||
max_workers=len(by_harness), thread_name_prefix="mcp-list") as ex:
|
||
for part in ex.map(one_harness, by_harness.values()):
|
||
got.update(part)
|
||
with _lock:
|
||
_state["logins"] = got
|
||
_state["at"] = time.time()
|
||
except Exception: # noqa: BLE001
|
||
log.exception("mcp listing")
|
||
finally:
|
||
with _lock:
|
||
_state["running"] = False
|
||
|
||
|
||
def _pass() -> None:
|
||
"""One background listing (``running`` already set), then another when a
|
||
change came in while it ran — that pass may predate the change."""
|
||
_refresh()
|
||
with _lock:
|
||
again = _state.pop("again", False)
|
||
if again:
|
||
refresh_soon()
|
||
|
||
|
||
def refresh_soon() -> None:
|
||
"""List again now (in the background) — after a change or a sign-in."""
|
||
with _lock:
|
||
if _state["running"]:
|
||
_state["again"] = True
|
||
return
|
||
_state["running"] = True
|
||
threading.Thread(target=_pass, daemon=True, name="mcp-list").start()
|
||
|
||
|
||
def patch_listing(key: str, name: str, **fields) -> None:
|
||
"""Show one server's new state at once, before the next full listing."""
|
||
with _lock:
|
||
got = _state["logins"].get(key)
|
||
for s in (got or {}).get("servers") or []:
|
||
if s.get("name") == name:
|
||
s.update(fields)
|
||
|
||
|
||
def _call(fn, *args, default=""):
|
||
try:
|
||
v = fn(*args)
|
||
return str(v) if v is not None else default
|
||
except Exception: # noqa: BLE001
|
||
return default
|
||
|
||
|
||
def report() -> dict | None:
|
||
"""``GET /mcp-servers``'s ``mcpServers``: the last listing of every login
|
||
(+ its live managed set); starts a background listing when it is older
|
||
than ``TTL_S``. None on a guest's computer."""
|
||
if not enabled():
|
||
return None
|
||
now = time.time()
|
||
with _lock:
|
||
stale = now - _state["at"] >= TTL_S and not _state["running"]
|
||
if stale:
|
||
_state["running"] = True
|
||
listed = {k: {**v, "servers": None if v.get("servers") is None
|
||
else [dict(s) for s in v["servers"]]}
|
||
for k, v in _state["logins"].items()}
|
||
checked = int(_state["at"]) or None
|
||
running = _state["running"]
|
||
if stale:
|
||
threading.Thread(target=_pass, daemon=True, name="mcp-list").start()
|
||
out = []
|
||
for a, acct in logins():
|
||
key = login_key(a.harness_id, acct)
|
||
got = listed.get(key) or {"listedAt": None, "listError": None, "servers": None}
|
||
out.append({"key": key, "harness": a.harness_id, "account": acct,
|
||
"configDir": _call(a.config_dir, acct),
|
||
"cwd": _call(getattr(a, "cwd", None) or (lambda _a: _cfg.DEFAULT_CWD), acct,
|
||
default=_cfg.DEFAULT_CWD),
|
||
"caps": caps_of(a), "managed": managed(key),
|
||
"listedAt": got.get("listedAt"), "listError": got.get("listError"),
|
||
"servers": got.get("servers")})
|
||
return {"version": 2, "checkedAt": checked, "running": running, "logins": out}
|
||
|
||
|
||
# ── changing ──────────────────────────────────────────────────────────────────
|
||
def apply(adapter, account: str, add: list[dict], remove: list[str]) -> dict:
|
||
"""Add / replace / remove the hub's servers on one login; answers
|
||
``{results: {name: {ok, error?, conflict?}}, report}``. A server of the
|
||
machine's own under the same name is a ``conflict``, left alone; only
|
||
names the hub added are replaced or removed."""
|
||
if not enabled():
|
||
raise forbidden()
|
||
hid = adapter.harness_id
|
||
key = login_key(hid, account)
|
||
transports = caps_of(adapter)["transports"]
|
||
results: dict[str, dict] = {}
|
||
with _apply_lock:
|
||
try:
|
||
own = set(adapter.own_names(account) or ())
|
||
except Exception as e: # noqa: BLE001
|
||
raise HTTPException(502, {"message": scrub(f"could not read {hid}'s MCP servers: "
|
||
f"{e}", 300), "kind": "apply_failed"})
|
||
mine = managed(key)
|
||
for item in add or []:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
name, cfg, h = item.get("name"), item.get("config"), item.get("hash")
|
||
if not isinstance(name, str) or not NAME_RE.match(name) or not valid_config(cfg):
|
||
results[str(name)[:64]] = {"ok": False, "error": "invalid server"}
|
||
continue
|
||
if cfg["type"] not in transports:
|
||
results[name] = {"ok": False,
|
||
"error": f"{hid} takes {' or '.join(transports)} servers"}
|
||
continue
|
||
h = h if isinstance(h, str) and h else config_hash(cfg)
|
||
if name in own and name not in mine:
|
||
results[name] = {"ok": False, "conflict": True,
|
||
"error": "a server of the machine's own has this name"}
|
||
continue
|
||
if mine.get(name) == h and name in own:
|
||
results[name] = {"ok": True}
|
||
continue
|
||
try:
|
||
if name in own:
|
||
adapter.delete(account, name)
|
||
own.discard(name)
|
||
adapter.write(account, name, cfg)
|
||
except McpError as e:
|
||
results[name] = {"ok": False, "error": e.message}
|
||
continue
|
||
except Exception as e: # noqa: BLE001 — never a 500 for one server
|
||
log.exception("mcp write %s %s", key, name)
|
||
results[name] = {"ok": False, "error": scrub(f"{type(e).__name__}: {e}", 300)}
|
||
continue
|
||
own.add(name)
|
||
set_managed(key, name, h)
|
||
mine[name] = h
|
||
results[name] = {"ok": True}
|
||
for name in remove or []:
|
||
if not isinstance(name, str) or name in results:
|
||
continue
|
||
if name not in mine:
|
||
results[name] = {"ok": True} # never one of the machine's own
|
||
continue
|
||
if name in own:
|
||
try:
|
||
adapter.delete(account, name)
|
||
except McpError as e:
|
||
results[name] = {"ok": False, "error": e.message}
|
||
continue
|
||
except Exception as e: # noqa: BLE001
|
||
log.exception("mcp delete %s %s", key, name)
|
||
results[name] = {"ok": False,
|
||
"error": scrub(f"{type(e).__name__}: {e}", 300)}
|
||
continue
|
||
set_managed(key, name, None)
|
||
mine.pop(name, None)
|
||
results[name] = {"ok": True}
|
||
refresh_soon()
|
||
return {"results": results, "report": report()}
|
||
|
||
|
||
def unsupported(what: str, harness: str) -> HTTPException:
|
||
return HTTPException(409, {"message": f"{harness} can't {what} here",
|
||
"kind": "unsupported"})
|
||
|
||
|
||
def approve(adapter, account: str, name: str) -> dict:
|
||
"""A server waiting for approval (Claude: a ``.mcp.json`` one): the
|
||
adapter approves it, the listing shows it checking."""
|
||
if not caps_of(adapter)["approve"]:
|
||
raise unsupported("approve an MCP server", adapter.harness_id)
|
||
if not isinstance(name, str) or not NAME_RE.match(name):
|
||
raise HTTPException(400, {"message": "invalid server name", "kind": "bad_name"})
|
||
try:
|
||
adapter.approve(account, name)
|
||
except McpError as e:
|
||
raise HTTPException(e.status, {"message": e.message, "kind": e.kind})
|
||
patch_listing(login_key(adapter.harness_id, account), name, status="unknown",
|
||
detail="approved — checking")
|
||
refresh_soon()
|
||
return {"ok": True, "report": report()}
|
||
|
||
|
||
# ── signing in ────────────────────────────────────────────────────────────────
|
||
class PtyLogin:
|
||
"""One harness CLI's ``mcp login`` on a pty, waiting for its callback."""
|
||
|
||
def __init__(self, harness: str, account: str, name: str, proc, master: int,
|
||
connector_hosts: tuple[str, ...] = ()):
|
||
self.id = secrets.token_hex(8)
|
||
self.harness, self.account, self.name = harness, account, name
|
||
self.proc, self.master = proc, master
|
||
self.connector_hosts = tuple(connector_hosts or ())
|
||
self.started = time.time()
|
||
self.url: str | None = None
|
||
self.port: int | None = None
|
||
self.path = "/callback"
|
||
self.state: str | None = None
|
||
self.kind = "callback"
|
||
self._buf: list[str] = []
|
||
self._lock = threading.Lock()
|
||
threading.Thread(target=self._pump, daemon=True, name="mcp-login").start()
|
||
self._timer = threading.Timer(LOGIN_TTL_S, self.kill)
|
||
self._timer.daemon = True
|
||
self._timer.start()
|
||
|
||
def _pump(self) -> None:
|
||
while True:
|
||
try:
|
||
chunk = os.read(self.master, 4096)
|
||
except OSError:
|
||
break
|
||
if not chunk:
|
||
break
|
||
with self._lock:
|
||
self._buf.append(chunk.decode(errors="replace"))
|
||
|
||
def output(self) -> str:
|
||
with self._lock:
|
||
return ANSI.sub("", "".join(self._buf))
|
||
|
||
def wait_url(self, timeout: float) -> str | None:
|
||
deadline = time.monotonic() + timeout
|
||
while time.monotonic() < deadline:
|
||
for u in URL_RE.findall(self.output()):
|
||
u = u.rstrip(").,]")
|
||
parts = urllib.parse.urlsplit(u)
|
||
q = urllib.parse.parse_qs(parts.query)
|
||
redirect = (q.get("redirect_uri") or [None])[0]
|
||
if redirect:
|
||
r = urllib.parse.urlsplit(redirect)
|
||
if r.hostname in ("localhost", "127.0.0.1") and r.port:
|
||
self.url, self.port, self.path = u, r.port, r.path or "/callback"
|
||
self.state = (q.get("state") or [None])[0]
|
||
return u
|
||
if parts.hostname and parts.hostname in self.connector_hosts:
|
||
# A connector: approved on its own site, nothing to paste.
|
||
self.url, self.kind = u, "connector"
|
||
return u
|
||
if self.proc.poll() is not None:
|
||
return None
|
||
time.sleep(0.1)
|
||
return None
|
||
|
||
def alive(self) -> bool:
|
||
return self.proc.poll() is None
|
||
|
||
def kill(self) -> None:
|
||
self._timer.cancel()
|
||
if self.proc.poll() is None:
|
||
try:
|
||
self.proc.kill()
|
||
self.proc.wait(timeout=5)
|
||
except (OSError, subprocess.TimeoutExpired):
|
||
pass
|
||
try:
|
||
os.close(self.master)
|
||
except OSError:
|
||
pass
|
||
|
||
def public(self) -> dict:
|
||
return {"loginId": self.id, "harness": self.harness, "account": self.account,
|
||
"name": self.name, "url": self.url, "kind": self.kind,
|
||
"callbackPort": self.port if self.kind == "callback" else None,
|
||
"startedAt": int(self.started),
|
||
"expiresAt": int(self.started + LOGIN_TTL_S)}
|
||
|
||
|
||
_logins: dict[str, PtyLogin] = {}
|
||
_logins_lock = threading.Lock()
|
||
|
||
|
||
def spawn_pty(args: list[str], env: dict, cwd: str | None = None) -> tuple:
|
||
master, slave = pty.openpty()
|
||
try:
|
||
proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave,
|
||
close_fds=True, start_new_session=True,
|
||
cwd=cwd or None, env=env)
|
||
finally:
|
||
os.close(slave)
|
||
return proc, master
|
||
|
||
|
||
def _label(argv: list[str]) -> str:
|
||
return " ".join([os.path.basename(str(argv[0])), *map(str, argv[1:3])]) if argv else "login"
|
||
|
||
|
||
def start_login(adapter, account: str, name: str, spawn: Callable | None = None) -> dict:
|
||
"""Start (or restart) the sign-in of one server; answers its URL."""
|
||
if not caps_of(adapter)["login"]:
|
||
raise unsupported("sign an MCP server in", adapter.harness_id)
|
||
if not isinstance(name, str) or not LISTED_NAME_RE.match(name) or name.startswith("-"):
|
||
raise HTTPException(400, {"message": "invalid server name", "kind": "bad_name"})
|
||
hid = adapter.harness_id
|
||
slot = f"{hid}\x00{account}\x00{name}"
|
||
with _logins_lock:
|
||
old = _logins.pop(slot, None)
|
||
if old:
|
||
old.kill()
|
||
try:
|
||
argv, env = adapter.login_argv(account, name)
|
||
except McpError as e:
|
||
raise HTTPException(e.status, {"message": e.message, "kind": e.kind})
|
||
label = _label(argv)
|
||
cwd = _call(getattr(adapter, "cwd", None) or (lambda _a: None), account, default="") or None
|
||
try:
|
||
proc, master = (spawn or functools.partial(spawn_pty, cwd=cwd))(argv, env)
|
||
except OSError as e:
|
||
raise HTTPException(500, {"message": f"could not start `{label}`: {e}",
|
||
"kind": "login"})
|
||
login = PtyLogin(hid, account, name, proc, master,
|
||
tuple(getattr(adapter, "connector_hosts", ()) or ()))
|
||
if not login.wait_url(URL_WAIT_S):
|
||
out = login.output().strip().splitlines()
|
||
login.kill()
|
||
msg = scrub(out[-1].strip(), 300) if out else "(no output)"
|
||
raise HTTPException(502, {"message": f"{label} printed no sign-in link: {msg}",
|
||
"kind": "login"})
|
||
if login.kind == "connector":
|
||
login.kill() # the CLI is done; the connector's site finishes it
|
||
else:
|
||
with _logins_lock:
|
||
_logins[slot] = login
|
||
return login.public()
|
||
|
||
|
||
def _find(login_id: str) -> PtyLogin | None:
|
||
with _logins_lock:
|
||
for lg in _logins.values():
|
||
if lg.id == login_id:
|
||
return lg
|
||
return None
|
||
|
||
|
||
def _drop(login: PtyLogin) -> None:
|
||
with _logins_lock:
|
||
for k, v in list(_logins.items()):
|
||
if v is login:
|
||
_logins.pop(k, None)
|
||
|
||
|
||
def parse_callback(raw: str, login: PtyLogin) -> str:
|
||
"""The pasted address → the path + query to replay to the CLI's port
|
||
(the whole query: ``code``, ``state``, ``iss``…). It must be the callback
|
||
this sign-in is waiting for."""
|
||
s = "".join((raw or "").split())
|
||
if s and "://" not in s and s.startswith(("localhost", "127.0.0.1")):
|
||
s = "http://" + s
|
||
try:
|
||
u = urllib.parse.urlsplit(s)
|
||
port = u.port
|
||
except ValueError:
|
||
u, port = None, None
|
||
if not u or u.scheme not in ("http", "https") or not u.query:
|
||
raise HTTPException(400, {"message": "paste the whole address your browser ended "
|
||
"on (it starts with http://localhost:)",
|
||
"kind": "bad_code"})
|
||
if u.hostname not in ("localhost", "127.0.0.1") or port != login.port \
|
||
or (u.path or "/") != login.path:
|
||
raise HTTPException(400, {"message": f"that address isn't this sign-in's (it should "
|
||
f"start with http://localhost:{login.port}"
|
||
f"{login.path}) — use the link from this one",
|
||
"kind": "bad_code"})
|
||
q = urllib.parse.parse_qs(u.query)
|
||
if login.state and (q.get("state") or [None])[0] != login.state:
|
||
raise HTTPException(400, {"message": "that address belongs to another sign-in "
|
||
"attempt — use the link from this one",
|
||
"kind": "bad_code"})
|
||
if not q.get("code") and not q.get("error"):
|
||
raise HTTPException(400, {"message": "the address has no sign-in code — paste it "
|
||
"after approving", "kind": "bad_code"})
|
||
return f"{login.path}?{u.query}"
|
||
|
||
|
||
def _get(url: str) -> None:
|
||
with urllib.request.urlopen(url, timeout=EXCHANGE_WAIT_S) as r:
|
||
r.read()
|
||
|
||
|
||
def finish_login(login_id: str, raw: str, get: Callable | None = None) -> dict:
|
||
"""Replay the pasted callback to the waiting CLI; answers once it ends."""
|
||
login = _find(login_id)
|
||
if not login or not login.alive():
|
||
raise HTTPException(404, {"message": "this sign-in expired — start again",
|
||
"kind": "login_expired"})
|
||
resolve(login.harness, login.account)
|
||
path = parse_callback(raw, login)
|
||
mark = len(login.output())
|
||
try:
|
||
(get or _get)(f"http://127.0.0.1:{login.port}{path}")
|
||
except urllib.error.HTTPError as e:
|
||
if login.alive():
|
||
raise HTTPException(400, {"message": f"the sign-in refused that address "
|
||
f"(HTTP {e.code}) — use the link from "
|
||
"this one", "kind": "bad_code"})
|
||
except (urllib.error.URLError, OSError) as e:
|
||
if login.alive():
|
||
raise HTTPException(502, {"message": f"the sign-in stopped listening: {e}",
|
||
"kind": "login_failed"})
|
||
deadline = time.monotonic() + EXCHANGE_WAIT_S
|
||
while time.monotonic() < deadline and login.alive():
|
||
time.sleep(0.1)
|
||
time.sleep(0.2)
|
||
tail = login.output()[mark:]
|
||
rc = login.proc.poll()
|
||
_drop(login)
|
||
login.kill()
|
||
if rc is None:
|
||
raise HTTPException(504, {"message": "the CLI didn't confirm the sign-in in time — "
|
||
"check the server's status and retry",
|
||
"kind": "login_timeout"})
|
||
if rc != 0:
|
||
raise HTTPException(502, {"message": last_line(tail) or f"sign-in failed (exit {rc})",
|
||
"kind": "login_failed"})
|
||
patch_listing(login_key(login.harness, login.account), login.name,
|
||
status="connected", detail=None)
|
||
refresh_soon()
|
||
return {"ok": True, "name": login.name, "account": login.account,
|
||
"harness": login.harness, "report": report()}
|
||
|
||
|
||
def cancel_login(login_id: str) -> bool:
|
||
login = _find(login_id)
|
||
if not login:
|
||
return False
|
||
_drop(login)
|
||
login.kill()
|
||
return True
|
||
|
||
|
||
# ── probes ────────────────────────────────────────────────────────────────────
|
||
def _initialize() -> dict:
|
||
return {"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
||
"params": {"protocolVersion": PROTOCOL_VERSION, "capabilities": {},
|
||
"clientInfo": {"name": "ai-agent", "version": CLIENT_VERSION}}}
|
||
|
||
|
||
def _origin(u: str) -> tuple:
|
||
p = urllib.parse.urlsplit(u)
|
||
return (p.scheme, (p.hostname or "").lower(), p.port or (443 if p.scheme == "https" else 80))
|
||
|
||
|
||
class _SameOriginRedirects(urllib.request.HTTPRedirectHandler):
|
||
"""Follows a 307 / 308 on the same origin (the body and headers re-sent);
|
||
anything else — another host above all, which would get the headers — is
|
||
not followed (the 3xx comes back as the answer)."""
|
||
|
||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||
if code not in (307, 308) or _origin(newurl) != _origin(req.full_url):
|
||
return None
|
||
return urllib.request.Request(newurl, data=req.data, method=req.get_method(),
|
||
headers=dict(req.header_items()))
|
||
|
||
|
||
def _opener():
|
||
return urllib.request.build_opener(_SameOriginRedirects())
|
||
|
||
|
||
def _err(e: BaseException) -> str:
|
||
if isinstance(e, TimeoutError) or "timed out" in str(e):
|
||
return "timed out"
|
||
reason = getattr(e, "reason", None)
|
||
return scrub(str(reason if reason is not None else e) or type(e).__name__) or "error"
|
||
|
||
|
||
def probe_http(url: str, headers: dict | None = None, timeout: float = 10,
|
||
*, opener=None) -> tuple[str, str | None]:
|
||
"""POST an MCP ``initialize``: 2xx → ``connected`` (the session it opened
|
||
is closed, best effort); 401 / 403 → ``needs_auth``; else ``failed`` with
|
||
``HTTP <code>`` or the error. Never follows a redirect to another host."""
|
||
op = opener or _opener()
|
||
hdrs = {"Content-Type": "application/json",
|
||
"Accept": "application/json, text/event-stream", **(headers or {})}
|
||
req = urllib.request.Request(url, data=json.dumps(_initialize()).encode(), headers=hdrs,
|
||
method="POST")
|
||
try:
|
||
with op.open(req, timeout=timeout) as r:
|
||
session = r.headers.get("Mcp-Session-Id")
|
||
final = r.geturl() or url
|
||
except urllib.error.HTTPError as e:
|
||
try:
|
||
if e.code in (401, 403):
|
||
return "needs_auth", _relay_message(e) or (None if e.code == 401 else "HTTP 403")
|
||
if 300 <= e.code < 400:
|
||
return "failed", f"HTTP {e.code} (redirect not followed)"
|
||
return "failed", f"HTTP {e.code}"
|
||
finally:
|
||
e.close()
|
||
except (urllib.error.URLError, OSError, ValueError) as e:
|
||
return "failed", _err(e)
|
||
if session:
|
||
try:
|
||
d = urllib.request.Request(final, method="DELETE",
|
||
headers={**(headers or {}), "Mcp-Session-Id": session})
|
||
with op.open(d, timeout=min(timeout, 5)):
|
||
pass
|
||
except (urllib.error.URLError, OSError, ValueError):
|
||
pass
|
||
return "connected", None
|
||
|
||
|
||
def _relay_message(e: urllib.error.HTTPError) -> str | None:
|
||
"""The hub gateway's refusal (a 403 since 2026-11-26) says why
|
||
(``relay_unauthorized``: signed out on the hub) — any other server's
|
||
401 / 403 says nothing worth showing."""
|
||
try:
|
||
body = json.loads(e.read(4096) or b"{}")
|
||
except (OSError, ValueError):
|
||
return None
|
||
if isinstance(body, dict) and body.get("error") == "relay_unauthorized":
|
||
return scrub(body.get("message")) or None
|
||
return None
|
||
|
||
|
||
def probe_stdio(command: str, args: list[str] | None = None, env: dict | None = None,
|
||
timeout: float = 20, *, cwd: str | None = None,
|
||
base_env: dict | None = None) -> tuple[str, str | None]:
|
||
"""Start the server, write ``initialize`` + newline, read its answer (one
|
||
JSON line with id 1), kill it. A missing program is ``failed``."""
|
||
full_env = {**(os.environ if base_env is None else base_env), **(env or {})}
|
||
prog = os.path.basename(command or "") or "?"
|
||
try:
|
||
p = subprocess.Popen([command, *(args or [])], stdin=subprocess.PIPE,
|
||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||
cwd=cwd or None, env=full_env, start_new_session=True)
|
||
except FileNotFoundError:
|
||
return "failed", f"{prog}: command not found"
|
||
except OSError as e:
|
||
return "failed", scrub(f"{prog}: {e.strerror or e}")
|
||
sel = selectors.DefaultSelector()
|
||
try:
|
||
try:
|
||
p.stdin.write(json.dumps(_initialize()).encode() + b"\n")
|
||
p.stdin.flush()
|
||
except OSError:
|
||
pass
|
||
sel.register(p.stdout, selectors.EVENT_READ)
|
||
buf = b""
|
||
deadline = time.monotonic() + timeout
|
||
while True:
|
||
left = deadline - time.monotonic()
|
||
if left <= 0:
|
||
return "failed", f"no answer in {timeout:g} s"
|
||
if not sel.select(left):
|
||
continue
|
||
chunk = os.read(p.stdout.fileno(), 65536)
|
||
if not chunk:
|
||
try:
|
||
rc = p.wait(timeout=1)
|
||
except subprocess.TimeoutExpired:
|
||
rc = None
|
||
return "failed", "exited before answering" + (f" (exit {rc})"
|
||
if rc is not None else "")
|
||
buf += chunk
|
||
while b"\n" in buf:
|
||
line, buf = buf.split(b"\n", 1)
|
||
try:
|
||
msg = json.loads(line)
|
||
except ValueError:
|
||
continue
|
||
if not isinstance(msg, dict) or msg.get("id") != 1:
|
||
continue
|
||
if "result" in msg:
|
||
return "connected", None
|
||
err = msg.get("error") if isinstance(msg.get("error"), dict) else {}
|
||
return "failed", scrub(err.get("message")) or "initialize refused"
|
||
if len(buf) > 1 << 20:
|
||
buf = b""
|
||
finally:
|
||
sel.close()
|
||
_kill_group(p)
|
||
|
||
|
||
def _kill_group(p: subprocess.Popen) -> None:
|
||
if p.poll() is None:
|
||
try:
|
||
os.killpg(p.pid, signal.SIGKILL)
|
||
except OSError:
|
||
try:
|
||
p.kill()
|
||
except OSError:
|
||
pass
|
||
try:
|
||
p.wait(timeout=5)
|
||
except subprocess.TimeoutExpired:
|
||
pass
|
||
for f in (p.stdin, p.stdout):
|
||
try:
|
||
f and f.close()
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def probe(cfg: dict, **kw) -> tuple[str, str | None]:
|
||
"""A canonical config's probe (``probe_http`` / ``probe_stdio``)."""
|
||
if not valid_config(cfg):
|
||
return "failed", "invalid server"
|
||
if cfg["type"] in ("http", "sse"):
|
||
return probe_http(cfg["url"], cfg.get("headers") or {})
|
||
return probe_stdio(cfg["command"], cfg.get("args") or [], cfg.get("env") or {}, **kw)
|
||
|
||
|
||
def probe_all(configs: dict[str, dict], **kw) -> dict[str, tuple[str, str | None]]:
|
||
"""``{name: canonical config}`` → ``{name: (status, detail)}``, probed a
|
||
few at a time."""
|
||
if not configs:
|
||
return {}
|
||
out: dict[str, tuple[str, str | None]] = {}
|
||
with concurrent.futures.ThreadPoolExecutor(
|
||
max_workers=min(PROBE_WORKERS, len(configs)), thread_name_prefix="mcp-probe") as ex:
|
||
futs = {ex.submit(probe, c, **kw): n for n, c in configs.items()}
|
||
for f in concurrent.futures.as_completed(futs):
|
||
try:
|
||
out[futs[f]] = f.result()
|
||
except Exception as e: # noqa: BLE001
|
||
out[futs[f]] = ("failed", _err(e))
|
||
return out
|