Files
ai-agent/backend/plugins/hubsignals.py
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

152 lines
6.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""``notify.ask`` and ``security.record`` — a plugin's question to the owner
and its line in the Security log (since 2026-11-28; the ``hub-mcp`` plugin's
number-matching approval and its "an AI app connected" line, which were
core's ``mcpserver/``). Docs: docs/plugins.md → "HTTP endpoints, the hub's API
and asks".
* ``POST …/plugins/{pid}/hub/ask`` ``{question, options: [2–3], url?, type?,
timeoutSecs?}`` → ``{id}``; ``GET …/hub/ask/{id}`` → ``{id, status,
answer}``; ``POST …/hub/ask/{id}/close`` ``{note?}``. Only an ask the plugin
raised (its record carries ``plugin``).
* ``POST …/plugins/{pid}/hub/security`` ``{event, detail, who?, ip?, push?}``
→ a ``plugin_event`` line.
Owner's install only, operator approval, the plugin's own handlers only.
"""
from __future__ import annotations
import re
from fastapi import APIRouter, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from plugins.proxyroutes import _active_plugin, _error, _who
router = APIRouter(include_in_schema=False)
ASK_CAP = "notify.ask"
SECURITY_CAP = "security.record"
_ASK_RE = re.compile(r"^ask_[0-9a-f]{12}$")
_EVENT_RE = re.compile(r"^[a-z][a-z0-9_]{0,31}$")
MAX_QUESTION = 600
MAX_OPTION = 40
MAX_DETAIL = 400
def _bridge(request: Request, pid: str, cap: str):
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
async def _json(request: Request) -> dict:
try:
body = await request.json()
except Exception:
return {}
return body if isinstance(body, dict) else {}
# ── notify.ask ───────────────────────────────────────────────────────────────
def _own_ask(deps, pid: str, aid: str) -> dict | None:
if not _ASK_RE.match(aid or ""):
return None
ask = deps.notify_store.ask_status(aid)
return ask if ask and ask.get("plugin") == pid else None
@router.post("/proxy/tools/plugins/{pid}/hub/ask")
async def plugin_hub_ask(pid: str, request: Request):
_rec, err = _bridge(request, pid, ASK_CAP)
if err:
return err
body = await _json(request)
question = " ".join(str(body.get("question") or "").split())[:MAX_QUESTION]
options = body.get("options")
if not question or not isinstance(options, list) or not 2 <= len(options) <= 3 \
or not all(isinstance(o, (str, int)) and str(o).strip() for o in options):
return _error(400, "need a question and 2-3 options", "bad_request")
try:
timeout = int(body.get("timeoutSecs") or 0)
except (TypeError, ValueError):
timeout = 0
d = {"question": question, "options": [str(o).strip()[:MAX_OPTION] for o in options],
"url": str(body.get("url") or "")[:500], "type": str(body.get("type") or "")[:24]}
if timeout:
d["timeoutSecs"] = max(30, min(timeout, 6 * 3600))
deps = request.app.state.ai
def create() -> dict:
from notifications.service import _create_ask
out = _create_ask(deps, d)
deps.notify_store.tag_plugin(out["id"], pid)
return out
try:
out = await run_in_threadpool(create)
except HTTPException as e:
return _error(e.status_code, str(e.detail), "bad_request")
return {"ok": True, "id": out["id"], "delivered": bool(out.get("ok"))}
@router.get("/proxy/tools/plugins/{pid}/hub/ask/{aid}")
async def plugin_hub_ask_status(pid: str, aid: str, request: Request):
_rec, err = _bridge(request, pid, ASK_CAP)
if err:
return err
ask = _own_ask(request.app.state.ai, pid, aid)
if not ask:
return _error(404, "no such ask", "not_found")
return {"id": aid, "status": ask.get("status"), "answer": ask.get("answer"),
"answeredAt": ask.get("answeredAt"), "expiresAt": ask.get("expiresAt")}
@router.post("/proxy/tools/plugins/{pid}/hub/ask/{aid}/close")
async def plugin_hub_ask_close(pid: str, aid: str, request: Request):
_rec, err = _bridge(request, pid, ASK_CAP)
if err:
return err
deps = request.app.state.ai
ask = _own_ask(deps, pid, aid)
if not ask:
return _error(404, "no such ask", "not_found")
body = await _json(request)
note = " ".join(str(body.get("note") or "").split())[:120] or "Answered elsewhere"
if ask.get("status") == "pending":
from notifications.service import close_ask
await run_in_threadpool(close_ask, deps, aid, note)
return {"ok": True, "id": aid}
# ── security.record ──────────────────────────────────────────────────────────
@router.post("/proxy/tools/plugins/{pid}/hub/security")
async def plugin_hub_security(pid: str, request: Request):
rec, err = _bridge(request, pid, SECURITY_CAP)
if err:
return err
body = await _json(request)
event = str(body.get("event") or "").strip()
if not _EVENT_RE.match(event):
return _error(400, "event: [a-z][a-z0-9_]{0,31}", "bad_request")
detail = " ".join(str(body.get("detail") or "").split())[:MAX_DETAIL]
name = rec["manifest"].get("name") or pid
deps = request.app.state.ai
from security.service import record_plugin
await run_in_threadpool(
record_plugin, deps, pid, name, event, detail,
who=str(body.get("who") or "")[:64] or None,
ip=str(body.get("ip") or "")[:64] or None, push=bool(body.get("push")))
return {"ok": True}