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>
156 lines
6.2 KiB
Python
156 lines
6.2 KiB
Python
"""``hub.api`` — the hub's own API for a plugin's handlers, as a person
|
|
(since 2026-11-28; the ``hub-mcp`` plugin, whose tools are the ``ai-agent``
|
|
CLI's). Docs: docs/plugins.md → "HTTP endpoints, the hub's API and asks".
|
|
|
|
* ``ANY …/plugins/{pid}/hub/api/{path}`` → this backend's ``/api/{path}``
|
|
over loopback, the query and body passed through, the status and answer
|
|
passed back. No header: **the owner**, as his CLI is. ``X-AIA-As-User:
|
|
<uid>``: that guest through the ``cli`` scope, while the plugin is theirs
|
|
(plugins/actas.py — the gate decides, this route only relays the name).
|
|
``X-AIA-Read-Only: 1``: safe methods only.
|
|
* ``POST …/plugins/{pid}/hub/via`` ``{sessionId, app, connection?}`` → stamps
|
|
a conversation with where it came from (``meta.via``): the card's
|
|
"via Claude.ai" pill.
|
|
|
|
Owner's install only, operator approval, the plugin's own handlers only. The
|
|
handler gets the CLI as a library to drive it: ``AIA_CLI_DIR`` (plugins/runner.py).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import pathlib
|
|
import re
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, Request
|
|
from fastapi.responses import Response
|
|
|
|
from plugins.actas import AS_USER_HEADER, VIA_PLUGIN_HEADER
|
|
from plugins.proxyroutes import _active_plugin, _error, _who
|
|
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
CAP = "hub.api"
|
|
READ_ONLY_HEADER = "x-aia-read-only"
|
|
_SAFE = ("GET", "HEAD")
|
|
TIMEOUT_S = 130.0
|
|
MAX_BODY = 4 * 1024 * 1024
|
|
_SID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
_UID_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
|
|
|
|
_ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
# The image ships the CLI as /app/cli (beside the backend's modules); in the
|
|
# repo it is ../cli.
|
|
CLI_DIR = next((d for d in (_ROOT / "cli", _ROOT.parent / "cli")
|
|
if (d / "ai_agent.py").is_file()), None)
|
|
|
|
|
|
def self_url() -> str:
|
|
"""The backend's own address inside the container — a loopback caller is
|
|
the gate's trusted peer."""
|
|
return (os.environ.get("HUB_SELF_URL")
|
|
or f"http://127.0.0.1:{os.environ.get('PORT', '8080')}").rstrip("/")
|
|
|
|
|
|
def _bridge(request: Request, pid: str):
|
|
"""(rec, error): the plugin's own handler, run for the owner, holding the cap."""
|
|
who, err = _who(request, pid)
|
|
if err:
|
|
return None, err
|
|
if who.handler != pid:
|
|
return None, _error(403, f"{CAP} is only available to the plugin's own handlers",
|
|
"handler_only")
|
|
if not who.is_owner:
|
|
return None, _error(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, _error(403, f"plugin lacks {CAP} capability", "capability")
|
|
return rec, None
|
|
|
|
|
|
_client: httpx.AsyncClient | None = None
|
|
|
|
|
|
def _http() -> httpx.AsyncClient:
|
|
global _client
|
|
if _client is None:
|
|
_client = httpx.AsyncClient(timeout=httpx.Timeout(TIMEOUT_S, connect=5.0),
|
|
limits=httpx.Limits(max_connections=32))
|
|
return _client
|
|
|
|
|
|
@router.api_route("/proxy/tools/plugins/{pid}/hub/api/{rest:path}",
|
|
methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
|
|
async def plugin_hub_api(pid: str, rest: str, request: Request):
|
|
_rec, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
if request.headers.get(READ_ONLY_HEADER) and request.method not in _SAFE:
|
|
return _error(403, "this call is read-only", "read_only")
|
|
if ".." in rest.split("/") or rest.startswith("/"):
|
|
return _error(400, "bad path", "bad_request")
|
|
headers: dict[str, str] = {}
|
|
ctype = request.headers.get("content-type")
|
|
if ctype:
|
|
headers["Content-Type"] = ctype
|
|
if AS_USER_HEADER in request.headers:
|
|
# sent but empty is a call for nobody — never quietly the owner's
|
|
as_user = (request.headers.get(AS_USER_HEADER) or "").strip()
|
|
if not _UID_RE.match(as_user):
|
|
return _error(400, "bad user id", "bad_request")
|
|
headers[AS_USER_HEADER] = as_user
|
|
headers[VIA_PLUGIN_HEADER] = pid
|
|
from core.auth import INTERNAL_API_TOKEN
|
|
if INTERNAL_API_TOKEN:
|
|
# the hub calling itself: never a tokenless loopback call in the audit
|
|
headers["X-Internal-Auth"] = INTERNAL_API_TOKEN
|
|
body = await request.body()
|
|
if len(body) > MAX_BODY:
|
|
return _error(413, "request too large", "too_large")
|
|
url = f"{self_url()}/api/{rest}"
|
|
query = (request.scope.get("query_string") or b"").decode("latin-1")
|
|
if query:
|
|
url += "?" + query
|
|
try:
|
|
r = await _http().request(request.method, url, headers=headers, content=body or None)
|
|
except httpx.TimeoutException:
|
|
return _error(504, "the hub took too long to answer", "timeout")
|
|
except httpx.HTTPError as e:
|
|
return _error(502, f"the hub's API didn't answer: {type(e).__name__}", "unreachable")
|
|
return Response(r.content, status_code=r.status_code,
|
|
media_type=r.headers.get("content-type") or "application/json",
|
|
headers={"Cache-Control": "no-store"})
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/via")
|
|
async def plugin_hub_via(pid: str, request: Request):
|
|
rec, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
try:
|
|
body = await request.json()
|
|
except Exception:
|
|
body = None
|
|
if not isinstance(body, dict):
|
|
return _error(400, "JSON object required", "bad_request")
|
|
sid = str(body.get("sessionId") or "").strip()
|
|
if not _SID_RE.match(sid):
|
|
return _error(400, "sessionId: a session id", "bad_request")
|
|
deps = request.app.state.ai
|
|
meta = deps.meta_store.peek(sid)
|
|
if not meta:
|
|
return _error(404, "no such conversation", "not_found")
|
|
if meta.get("via"):
|
|
return {"ok": True, "sessionId": sid, "via": meta["via"], "existing": True}
|
|
app = " ".join(str(body.get("app") or "").split())[:80] or rec["manifest"].get("name") or pid
|
|
via = {"kind": "plugin", "plugin": pid, "app": app}
|
|
conn = str(body.get("connection") or "").strip()[:64]
|
|
if conn:
|
|
via["connection"] = conn
|
|
deps.meta_store.update(sid, {"via": via})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
return {"ok": True, "sessionId": sid, "via": via}
|