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

242 lines
11 KiB
Python

"""Roles: named bundles of permissions (``authz/catalog.py``).
Five are built in, each with a ceiling it can never exceed:
========= ========================== =========== ==========
role holds assignable editable
========= ========================== =========== ==========
operator everything (the owner) no no
admin person + admin tiers not yet yes
member person tier yes yes
guest today's guest defaults yes yes
viewer read what's theirs yes yes
========= ========================== =========== ==========
*Admin* is the hub's administration without the machine (no host-tier
permission). Nobody in ``users.json`` can hold it yet: most handlers still
tell the owner from a guest by identity, so it comes with team mode.
Custom roles are clones (Settings → Users → Roles → *Clone*), always within the
person tier. A built-in's edits and every custom role live in ``roles.json``
(``ROLES_PATH``), a whole-file rewrite like ``users.json``; a built-in nobody
edited is not stored, so its defaults can improve in code.
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import threading
from authz import catalog as cat
ROLES_PATH = pathlib.Path(os.environ.get("ROLES_PATH", "/data/roles.json"))
OPERATOR, ADMIN, MEMBER, GUEST, VIEWER = "operator", "admin", "member", "guest", "viewer"
DEFAULT_ROLE = GUEST
GUEST_DEFAULT = frozenset({
"whoami", "self", "app.read", "self.claude",
"conversations.read", "conversations.edit", "conversations.share",
"runs.start", "runs.scratch.bash", "runs.codemode", "cli.use",
"inbox.read", "inbox.answer", "projects.read", "files.upload", "cron.own",
"plugins.use",
})
BUILTIN: dict[str, dict] = {
OPERATOR: {"name": "Operator", "ceiling": cat.ALL, "perms": cat.ALL,
"assignable": False, "editable": False,
"description": "The machine's owner: everything, host-level included."},
ADMIN: {"name": "Admin", "ceiling": cat.ADMIN_PERMS, "perms": cat.ADMIN_PERMS,
"assignable": False, "editable": True,
"description": "Runs the hub — people, settings, every conversation — "
"but not the machine. Assignable with team mode."},
MEMBER: {"name": "Member", "ceiling": cat.PERSON_PERMS, "perms": cat.PERSON_PERMS,
"assignable": True, "editable": True,
"description": "A teammate: their own conversations and logins, "
"every person-level feature."},
GUEST: {"name": "Guest", "ceiling": cat.PERSON_PERMS, "perms": GUEST_DEFAULT,
"assignable": True, "editable": True,
"description": "Someone you invited into a few projects."},
VIEWER: {"name": "Viewer", "ceiling": cat.PERSON_PERMS,
"perms": frozenset({"whoami", "self", "app.read", "conversations.read",
"inbox.read", "projects.read"}),
"assignable": True, "editable": True,
"description": "Reads what is shared with them; starts nothing."},
}
ORDER = (OPERATOR, ADMIN, MEMBER, GUEST, VIEWER)
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
def _slug(name: str) -> str:
s = re.sub(r"[^a-z0-9]+", "-", (name or "").lower()).strip("-")[:32]
return s or "role"
class RolesStore:
def __init__(self, path: pathlib.Path = ROLES_PATH):
self.path = pathlib.Path(path)
self._lock = threading.RLock()
self._data = self._load()
self.version = 0
def _load(self) -> dict:
try:
raw = json.loads(self.path.read_text())
except (OSError, ValueError):
raw = {}
roles = raw.get("roles") if isinstance(raw, dict) else None
return {"roles": roles if isinstance(roles, dict) else {}}
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
tmp.write_text(json.dumps(self._data, indent=1, sort_keys=True))
os.replace(tmp, self.path)
self.version += 1
# ── reads ────────────────────────────────────────────────────────────────
def get(self, rid: str | None) -> dict | None:
"""A role as ``{id, name, description, perms (frozenset), builtin,
assignable, editable, ceiling}``, or None."""
with self._lock:
stored = self._data["roles"].get(rid or "")
if rid in BUILTIN:
b = BUILTIN[rid]
perms = b["perms"]
if stored and b["editable"] and isinstance(stored.get("perms"), list):
perms = frozenset(stored["perms"])
return {"id": rid, "name": b["name"],
"description": (stored or {}).get("description") or b["description"],
"perms": (perms & b["ceiling"]) | cat.CORE,
"builtin": True, "assignable": b["assignable"],
"editable": b["editable"], "ceiling": b["ceiling"],
"edited": bool(stored)}
if not stored:
return None
return {"id": rid, "name": stored.get("name") or rid,
"description": stored.get("description") or "",
"perms": (frozenset(stored.get("perms") or ()) & cat.PERSON_PERMS) | cat.CORE,
"builtin": False, "assignable": True, "editable": True,
"ceiling": cat.PERSON_PERMS, "edited": True,
"from": stored.get("from")}
def stored_perms(self, rid: str | None) -> list[str] | None:
"""A role's permission list as it was written — a since-retired
permission still in it — or None for a role nobody edited (a
carry-over reading an old permission: plugins/carryover.py)."""
with self._lock:
perms = (self._data["roles"].get(rid or "") or {}).get("perms")
return list(perms) if isinstance(perms, list) else None
def all(self) -> list[dict]:
with self._lock:
custom = sorted((k for k in self._data["roles"] if k not in BUILTIN),
key=lambda k: (self._data["roles"][k].get("name") or k).lower())
return [r for r in (self.get(k) for k in (*ORDER, *custom)) if r]
def assignable(self, rid: str | None) -> bool:
r = self.get(rid)
return bool(r and r["assignable"])
def perms(self, rid: str | None) -> frozenset[str]:
"""A role's permissions; an unknown or unassignable role is the guest's
(a person never holds admin or operator through a hand-edited file)."""
r = self.get(rid)
if not r or not r["assignable"]:
r = self.get(DEFAULT_ROLE)
return r["perms"]
# ── writes ───────────────────────────────────────────────────────────────
def update(self, rid: str, *, perms=None, name=None, description=None) -> dict:
with self._lock:
r = self.get(rid)
if not r:
raise KeyError(rid)
if not r["editable"]:
raise ValueError(f"the {r['name']} role can't be changed")
rec = dict(self._data["roles"].get(rid) or {})
if perms is not None:
bad = set(perms) - r["ceiling"] - cat.CORE
if bad - cat.ALL:
raise ValueError(f"unknown permissions: {sorted(bad - cat.ALL)}")
if bad:
raise ValueError(f"the {r['name']} role can't hold: {sorted(bad)}")
rec["perms"] = cat.clean(set(perms) | cat.CORE, r["ceiling"] | cat.CORE)
elif r["builtin"] and "perms" not in rec:
rec["perms"] = cat.clean(r["perms"])
if description is not None:
rec["description"] = " ".join(str(description).split())[:200]
if name is not None and not r["builtin"]:
n = " ".join(str(name).split())[:40]
if not n:
raise ValueError("a role needs a name")
rec["name"] = n
self._data["roles"][rid] = rec
self._save()
return self.get(rid)
def clone(self, src: str, name: str) -> dict:
with self._lock:
r = self.get(src)
if not r:
raise KeyError(src)
n = " ".join(str(name or "").split())[:40]
if not n:
raise ValueError("a role needs a name")
if any(x["name"].lower() == n.lower() for x in self.all()):
raise ValueError("a role with this name already exists")
base, rid, i = _slug(n), "", 1
while not rid or rid in BUILTIN or rid in self._data["roles"]:
rid = base if i == 1 else f"{base}-{i}"
i += 1
if not _ID_RE.match(rid):
raise ValueError("bad role name")
self._data["roles"][rid] = {
"name": n, "description": r["description"] if not r["builtin"] else
f"Made from {r['name']}.", "from": src,
"perms": cat.clean(r["perms"], cat.PERSON_PERMS | cat.CORE)}
self._save()
return self.get(rid)
def reset(self, rid: str) -> dict:
"""A built-in back to its defaults."""
with self._lock:
if rid not in BUILTIN:
raise ValueError("only a built-in role has defaults")
self._data["roles"].pop(rid, None)
self._save()
return self.get(rid)
def delete(self, rid: str) -> None:
with self._lock:
if rid in BUILTIN:
raise ValueError("a built-in role can't be deleted")
if rid not in self._data["roles"]:
raise KeyError(rid)
del self._data["roles"][rid]
self._save()
_STORE: RolesStore | None = None
_STORE_LOCK = threading.Lock()
def store() -> RolesStore:
"""The process's roles store (``ROLES_PATH``)."""
global _STORE
with _STORE_LOCK:
if _STORE is None:
_STORE = RolesStore()
return _STORE
def public(r: dict, members: int = 0) -> dict:
return {"id": r["id"], "name": r["name"], "description": r["description"],
"perms": cat.clean(r["perms"]), "ceiling": cat.clean(r["ceiling"]),
"builtin": r["builtin"], "assignable": r["assignable"],
"editable": r["editable"], "edited": r["edited"],
"clonedFrom": r.get("from"), "members": members}