Files
gabrielvidalandClaude Fable 5.2 df9c0ac5f3 feat(plugins): the MCP server leaves core for the hub-mcp plugin; a worker's CLI gets Full
The hub as an MCP server (OAuth 2.1, the consent page, /mcp, Settings → AI
apps) is the `hub-mcp` live plugin now (ai-agent-plugins). Core keeps nothing
about MCP: four generic plugin contracts replace backend/mcpserver/.
Gabriel's picks: form move-the-hub-mcp-server-into-a-plugin_2od10i.

New contracts (docs/plugins.md → "HTTP endpoints, the hub's API and asks"):
- `endpoints[]` (plugins/endpoints.py): HTTP a plugin answers on the hub's own
  address — under /x/<pluginId>/… or a protocol path (/mcp, /oauth/…,
  /.well-known/…). The request goes to the endpoint's action with what the
  host vouches for (client address, surface, and `caller`: who the browser is
  signed in as, by the gate's own rules — core/auth.identify); the answer
  comes back through header and type allowlists, and HTML never runs a script
  (forced CSP). Body cap, per-address rate, 16 runs at once on their own
  threads. An endpoint's action answers HTTP only: the action routes refuse it
  and the manifest can't wire it to anything else — its payload is the host's
  word on who is asking.
- `hub.api` (plugins/hubapi.py, plugins/actas.py): the hub's API for the
  plugin's handlers, as the owner or — `X-AIA-As-User`, the `cli` scope — as a
  guest the plugin is granted to. The CLI is its library (AIA_CLI_DIR; the
  names a plugin leans on are pinned by cli/test_library_surface.py).
  `hub/via` stamps meta.via = {kind: "plugin", …}: the "via Claude.ai" pill.
- `notify.ask` and `security.record` (plugins/hubsignals.py): a tappable
  question to the owner and its answer; a `plugin_event` Security log line.

Removed: backend/mcpserver/, schemas/mcp.py, cli/mcp_tools.py + mcp_server.py,
the frontend's business/aiApps (Settings → AI apps, /connect/<id> — both old
addresses redirect), /api/mcp*, /api/me/ai-apps, the `mcp` SSE event, the
mcp.connect / mcp.manage permissions and the per-guest AI apps switch (the
plugin's managed grant). A retired permission still in a record reads without
it and is never refused (authz/catalog.RETIRED).

Carry-over (carryover.hub_mcp, at start and after the plugin's install):
/data/mcp.json → the plugin's store, same shape, so connected apps keep
working — minus the connections bound to a worker, which are dropped with
their tokens rather than left as plain owner connections; every guest who
held mcp.connect gets the grant; whoever was pushed about mcp_connected is
pushed about plugin events.

Workers: the `ai-agent` CLI switch gains Full — the lab's CLI as the owner
(every command but worktrees, any machine, the plugins' commands), what the
EVOX2's unbound MCP connection gave. The worker-side CLI no longer filters
commands: the hub's switch decides. "Acts as" is gone; workers/bound.py stays
as the CLI's narrowing.

Until the plugin is installed after a deploy, /mcp and /oauth/* answer 404.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 13:50:25 +01:00

262 lines
11 KiB
Python

"""What the two pages read: the Hub card (``/dashboards/performance``) and the
Usage dashboard (``/dashboards/usage``). Plain dicts, shaped by
``schemas/telemetry.py``."""
from __future__ import annotations
import time
from conversations.ids import uid_time
from users.caller import OWNER_ID, OWNER_NAME
from .middleware import Hist
from .store import _hist_from, _quantile
#: range → (span, bucket) in seconds.
HUB_RANGES = {"24h": (86400, 300), "7d": (7 * 86400, 3600), "30d": (30 * 86400, 4 * 3600)}
USAGE_RANGES = {"7d": 7, "30d": 30, "90d": 90}
#: Where a conversation came from (:func:`run_origin`), in display order.
ORIGINS = ("app", "script", "cron", "scheduled", "child", "mcp", "handoff", "fork",
"newProject", "unknown")
def _iso_day(t: float) -> str:
return time.strftime("%Y-%m-%d", time.localtime(t))
# ── the Hub card ─────────────────────────────────────────────────────────────
def hub(deps, rng: str, now: float | None = None) -> dict:
now = now or time.time()
span, step = HUB_RANGES[rng]
since = now - span
st = deps.telemetry
buckets: dict[int, dict] = {}
total = Hist()
minute_lags: list[float] = []
lag_max = 0.0
for (t, n, err, sum_ms, max_ms, b, lag_p95, lag_mx, sse, busy, rss, cpu) in st.query(
"SELECT t, n, err, sum_ms, max_ms, b, lag_p95, lag_max, sse, busy, rss, cpu "
"FROM hub_minutes WHERE t >= ? ORDER BY t", (since,)):
k = int(t // step * step)
e = buckets.setdefault(k, {"h": Hist(), "lag": [], "lagMax": 0.0, "sse": 0,
"rss": 0, "cpu": []})
if n:
h = _hist_from(b, n, err, sum_ms, max_ms)
e["h"].merge(h)
total.merge(h)
if lag_p95 is not None:
e["lag"].append(lag_p95)
minute_lags.append(lag_p95)
if lag_mx is not None:
e["lagMax"] = max(e["lagMax"], lag_mx)
lag_max = max(lag_max, lag_mx)
e["sse"] = max(e["sse"], sse or 0)
e["rss"] = max(e["rss"], rss or 0)
if cpu is not None:
e["cpu"].append(cpu)
series = [{
"t": k, "n": e["h"].n, "err": e["h"].err,
"p50": e["h"].quantile(.5), "p95": e["h"].quantile(.95),
"lagP95": _quantile(e["lag"], .95), "lagMax": round(e["lagMax"], 1),
"sse": e["sse"], "rss": e["rss"] or None,
"cpu": round(sum(e["cpu"]) / len(e["cpu"]), 1) if e["cpu"] else None,
} for k, e in sorted(buckets.items())]
per_route: dict[str, Hist] = {}
for route, n, err, sum_ms, max_ms, b in st.query(
"SELECT route, n, err, sum_ms, max_ms, b FROM hub_routes WHERE t >= ?",
(since - 3600,)):
per_route.setdefault(route, Hist()).merge(_hist_from(b, n, err, sum_ms, max_ms))
routes = sorted(({
"route": r, "n": h.n, "err": h.err, "p50": h.quantile(.5), "p95": h.quantile(.95),
"max": round(h.max, 1), "sumMs": round(h.sum),
} for r, h in per_route.items() if h.n), key=lambda x: -x["sumMs"])[:25]
vitals: dict[tuple[str, str], list[float]] = {}
for name, device, value in st.query(
"SELECT name, device, value FROM web_vitals WHERE t >= ?", (since,)):
vitals.setdefault((name, device), []).append(value)
vitals.setdefault((name, "all"), []).append(value)
web = [{"name": name, "device": device, "n": len(v), "p75": _quantile(v, .75)}
for (name, device), v in sorted(vitals.items())]
errors = [{"message": m, "page": p, "n": n, "last": last, "source": src}
for m, p, n, last, src in st.query(
"SELECT message, page, SUM(n), MAX(last), MAX(source) FROM web_errors "
"WHERE day >= ? GROUP BY message, page ORDER BY SUM(n) DESC LIMIT 10",
(_iso_day(since),))]
return {
"range": rng, "step": step, "series": series,
"totals": {"n": total.n, "err": total.err, "p50": total.quantile(.5),
"p95": total.quantile(.95), "max": round(total.max, 1),
"lagP95": _quantile(minute_lags, .95), "lagMax": round(lag_max, 1)},
"routes": routes, "web": web, "errors": errors,
"now": {"sse": deps.hub.subscriber_count()},
}
# ── the Usage dashboard ──────────────────────────────────────────────────────
def run_origin(m: dict) -> str:
"""Where a conversation was started from, read off its meta. ``app`` /
``script`` are stamped by ``/api/spawn`` since telemetry began; before
that, and for a session started in a terminal, it is ``unknown``."""
if m.get("cron"):
return "cron"
if m.get("scheduled"):
return "scheduled"
if m.get("spawnedBy"):
return "child"
via = m.get("via")
if isinstance(via, dict) and via.get("kind") in ("mcp", "plugin"):
return "mcp"
if m.get("forkedFrom"):
return "fork"
if m.get("newProject"):
return "newProject"
o = m.get("origin")
# ``handoff``: stamped by /api/spawn from 2026-11-24 until handoffs left the
# core for the handoff plugin (2026-11-26) — its successors are ``script``s now.
return o if o in ("app", "script", "handoff") else "unknown"
def _who(deps, who: str) -> set[str] | None:
"""``all`` → None (everyone); ``owner``; ``guests``; ``guest:<uid>``."""
if who == "owner":
return {OWNER_ID}
guests = {u["id"] for u in deps.users.all()}
if who == "guests":
return guests
if who.startswith("guest:"):
uid = who[6:]
return {uid} if uid in guests else set()
return None
def usage(deps, rng: str, who: str = "all", now: float | None = None) -> dict:
now = now or time.time()
days = USAGE_RANGES[rng]
since_t = now - days * 86400
since = _iso_day(since_t)
uids = _who(deps, who)
st = deps.telemetry
feats: dict[tuple[str, str], dict] = {}
for kind, name, uid, device, n in st.query(
"SELECT kind, name, uid, device, SUM(n) FROM usage_daily WHERE day >= ? "
"GROUP BY kind, name, uid, device", (since,)):
if uids is not None and uid not in uids:
continue
f = feats.setdefault((kind, name), {"kind": kind, "name": name, "n": 0,
"byUser": {}, "byDevice": {}})
f["n"] += n
f["byUser"][uid] = f["byUser"].get(uid, 0) + n
f["byDevice"][device] = f["byDevice"].get(device, 0) + n
# First and last use ever, per person: adoption after a What's new entry.
first: dict[tuple[str, str], dict[str, list[str]]] = {}
for kind, name, uid, d0, d1 in st.query(
"SELECT kind, name, uid, MIN(day), MAX(day) FROM usage_daily "
"WHERE kind != 'api' GROUP BY kind, name, uid"):
if uids is not None and uid not in uids:
continue
first.setdefault((kind, name), {})[uid] = [d0, d1]
for key, f in feats.items():
f["users"] = len(f["byUser"])
f["firstUse"] = {u: v[0] for u, v in first.get(key, {}).items()}
f["lastDay"] = max((v[1] for v in first.get(key, {}).values()), default=None)
features = sorted(feats.values(), key=lambda f: -f["n"])
devices: dict[str, int] = {}
for f in features:
if f["kind"] == "api":
continue
for d, n in f["byDevice"].items():
devices[d] = devices.get(d, 0) + n
# The guests' What's new entries and who saw each — the whats-new plugin's
# (plugins/whatsnew_bridge.py; none without it).
from plugins import whatsnew_bridge
whats_new = whatsnew_bridge.entries(deps)[:12]
runs: dict[str, dict] = {}
for cid, m in deps.meta_store.items():
t = uid_time(cid)
if t is None or t < since_t:
continue
if m.get("test"):
continue
uid = m.get("owner") or OWNER_ID
if uids is not None and uid not in uids:
continue
o = run_origin(m)
r = runs.setdefault(o, {"origin": o, "n": 0, "byUser": {}})
r["n"] += 1
r["byUser"][uid] = r["byUser"].get(uid, 0) + 1
origins = sorted(runs.values(), key=lambda r: ORIGINS.index(r["origin"]))
people = [{"id": OWNER_ID, "name": OWNER_NAME, "guest": False}] + [
{"id": u["id"], "name": u.get("name") or u.get("email") or u["id"], "guest": True}
for u in deps.users.all() if not u.get("disabled")]
span = st.query("SELECT MIN(day) FROM usage_daily")
return {"range": rng, "who": who, "features": features, "devices": devices,
"whatsNew": whats_new, "runs": origins, "people": people,
"trackedSince": span[0][0] if span and span[0][0] else None}
# ── the feature registry ─────────────────────────────────────────────────────
_REGISTRY: list | None = None
def registry(deps=None) -> list[dict]:
"""The app's feature registry (lib/telemetry/features.ts — every page and
client feature it knows by name), as ``features.json`` beside this module:
generated from the TypeScript, which ``src/lib/telemetry/features.test.ts``
keeps in step (``UPDATE_FEATURES=1 npx vitest run`` rewrites it) — plus,
given ``deps``, every installed plugin's pages (``plugin_features``). The
App usage plugin joins it with the counts to label rows and list what goes
unused."""
global _REGISTRY
if _REGISTRY is None:
import json
import pathlib
try:
data = json.loads((pathlib.Path(__file__).with_name("features.json")).read_text(encoding="utf-8"))
_REGISTRY = [f for f in data if isinstance(f, dict) and isinstance(f.get("id"), str)]
except (OSError, ValueError):
_REGISTRY = []
if deps is None:
return _REGISTRY
known = {f["id"] for f in _REGISTRY}
return _REGISTRY + [f for f in plugin_features(deps) if f["id"] not in known]
# A plugin page's App usage area, by the section its ``nav`` puts it in.
_PLUGIN_AREAS = {"files": "Lab", "settings": "Settings"}
def plugin_features(deps) -> list[dict]:
"""One view feature per page of every installed plugin (anyone's, once
per id): its id the page's ``feature`` — the one it counted under before
it was a plugin's, so its history carries on — else
``plugin.<plugin>.<page>``. The frontend records the same id
(lib/telemetry ``pageOf``)."""
out: dict[str, dict] = {}
try:
installed = deps.plugin_store.all_installed()
except Exception: # noqa: BLE001 — no store, no plugin pages
return []
for _uid, rec in installed:
mf = rec.get("manifest") or {}
pid = rec.get("id") or mf.get("id") or ""
for pg in (mf.get("ui") or {}).get("pages") or []:
if pg.get("nav") == "none" or not pid:
continue
fid = pg.get("feature") or f"plugin.{pid}.{pg['id']}"
if fid in out:
continue
out[fid] = {"id": fid, "label": pg.get("label") or pg["id"],
"area": _PLUGIN_AREAS.get(pg.get("nav") or "", "Dashboards"),
"kind": "view", **({"ownerOnly": True} if pg.get("perm") else {})}
return list(out.values())