Files
ai-agent/backend/mcpserver/routes.py
gabrielvidalandClaude Opus 5.5 ff1cb0e2e4 feat(mcp): a connection bound to a worker replaces the ai-agent CLI through the outbox
Gabriel's call (2026-11-18 form): Claude Code on the Orus MacBook drives the
hub through the MCP server, not the `ai-agent` CLI carried by the worker's
outbox (0226ffa..9031162, 2026-11-16).

- An owner MCP connection can be bound to one of his workers (grant.worker,
  PATCH /api/mcp/connections/{id} {worker}, "" unbinds; logged mcp_bound).
  Its loopback calls carry X-AIA-As-Worker + X-AIA-As-Worker-Mode (run for a
  full connection, read otherwise) and the gate answers them as
  workers/bound.py worker_caller: the owner narrowed to that worker's
  profile, its routes, runs on that machine only. Its tools are
  WORKER_TOOLS; browse keeps scheduled / models / workers / usage / budget.
- The narrowing the CLI path introduced (access.py, runs / scheduled /
  conversation-meta pinning) stays, moved to workers/bound.py.
- Removed for every worker: the `cli` outbox item and CliJobs, the per-worker
  `cli` switch, the CLI's outbox forwarding. On a worker the CLI keeps only
  `past` (the outbox lookup, still narrowed to the worker's profile) and its
  refusal points to the MCP tools. The installer keeps the notify shims and
  deletes its old `ai-agent` shim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:31:25 +01:00

819 lines
38 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.
"""The hub as a remote MCP server: ``/mcp`` (Streamable HTTP, stateless,
JSON responses) behind OAuth 2.1 — what Claude.ai, ChatGPT, Le Chat, Cursor…
plug in as a *custom connector*. Docs: docs/mcp.md.
The tools are the ``ai-agent`` CLI's (``cli/mcp_tools.py``), run against this
backend's own API over loopback as the connection's caller.
Endpoints (none under ``/api``, so the trusted-caller gate never sees them —
each checks its own credential, like ``/proxy/``):
* ``/.well-known/oauth-protected-resource[/mcp]`` (RFC 9728) and
``/.well-known/oauth-authorization-server`` (RFC 8414): where to log in.
* ``POST /oauth/register`` (RFC 7591): any app may register — registering
grants nothing.
* ``GET /oauth/authorize``: checks the request (PKCE S256 required, the
redirect URI exactly as registered) and parks it; the browser lands on the
PWA's ``/connect/<id>``, where the owner approves it — signed in through
Authelia on the admin host, or from his phone by **number matching** (the
page shows a two-digit number, the push offers three: only the one on the
page approves) — or a guest, for themselves.
* ``POST /oauth/token``: code → tokens (1 h access, 90-day rolling refresh);
refresh. ``POST /oauth/revoke`` (RFC 7009).
* ``POST /mcp``: bearer token → the tools.
A guest the owner switched it on for (Settings → Users → <guest> → Access →
*AI apps*) approves a connection for themselves on the consent page, signed in
on the guest host; their calls are then theirs (mcpserver/caller.py).
Owner-only under ``/api/mcp/*`` (the gate's OwnerDep): the connections and the
tool groups — Settings → AI apps.
"""
from __future__ import annotations
import asyncio
import base64
import concurrent.futures
import json
import logging
import os
import re
import secrets
import threading
import time
import urllib.parse
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse, Response
from pydantic import BaseModel
from starlette.concurrency import run_in_threadpool
import schemas
from core.http import _r
from mcpserver import tools as mtools
from mcpserver.caller import AS_USER_HEADER, mcp_caller
from mcpserver.store import SCOPES
from users.caller import OWNER_ID, CallerDep, OwnerDep
from users.cli import Refused
from users.deliver import GUEST_PUBLIC_URL
from workers import bound as worker_bound
log = logging.getLogger(__name__)
router = APIRouter()
# Where apps reach the server: the internet-facing guest host (the raspy2
# passthrough → Traefik `public`). Every URL the metadata gives is built from
# this, never from the request's Host header.
PUBLIC_URL = (os.environ.get("MCP_PUBLIC_URL") or GUEST_PUBLIC_URL
or "https://ai-agent.gabvdl.xyz").rstrip("/")
RESOURCE = PUBLIC_URL + "/mcp"
# The admin host (Authelia): where the owner approves a connection.
OWNER_URL = os.environ.get("AI_AGENT_VIEW_URL", "https://ai-agent.lab.gabvdl.xyz").rstrip("/")
# Redirect URIs an app may register: https anywhere, http only to loopback,
# or an app's own scheme (cursor://, vscode://…) — never a script scheme.
_BAD_SCHEMES = {"javascript", "data", "file", "vbscript", "about", "blob"}
# The apps people plug in — the consent page shows any other redirect host
# with a warning.
KNOWN_REDIRECT_HOSTS = ("claude.ai", "claude.com", "chatgpt.com", "chat.openai.com",
"chat.mistral.ai", "localhost", "127.0.0.1", "vscode.dev",
"insiders.vscode.dev")
# Registration, /authorize and the consent page are open to the internet, so
# everything an anonymous caller can pile up is capped **per address** first
# (one address can't take the whole allowance and lock the owner's own
# request out), then overall.
MAX_PENDING, PENDING_PER_IP = 20, 3 # approvals waiting at once
REG_PER_IP, REG_WINDOW_S = 10, 86400 # app registrations
PUSH_EVERY_S = 30 # a push per request at most this often
# The owner's phone must not be a spam target (and a day of pushes is a
# finite thing — the HA relay stops at 500): a couple per address and a few
# overall in ten minutes, and a hard stop per day. Past it the page says to
# approve on the admin host.
PUSH_PER_IP, PUSH_BURST, PUSH_WINDOW_S = 2, 6, 600
PUSH_DAILY = 20
_pushes: list[tuple[float, str]] = [] # (when, address)
_registrations: dict[str, list[float]] = {}
_limits_lock = threading.Lock()
# Bodies an anonymous caller may send (uvicorn itself has no limit).
MAX_REGISTER_BODY, MAX_TOKEN_BODY, MAX_MCP_BODY = 64 * 1024, 16 * 1024, 2 * 1024 * 1024
# Tool calls run here, off the event loop and off anyio's shared pool — a
# `wait` holds its thread up to ~50 s while the nested API calls need theirs.
_pool = concurrent.futures.ThreadPoolExecutor(max_workers=8, thread_name_prefix="mcp")
def _store(request: Request):
return request.app.state.ai.mcp
def _record(request: Request, kind: str, **kw) -> None:
from security.service import record
record(request.app.state.ai, kind, request=request, **kw)
def _ip(request: Request) -> str:
"""The caller's address — Traefik's word for it when Traefik is the peer
(the public entrypoint reads PROXY v2: the real client)."""
from security.service import client_ip
return client_ip(request) or "?"
class _TooLarge(Exception):
pass
async def _body(request: Request, cap: int) -> bytes:
"""The request body, refused past ``cap`` bytes without reading the rest."""
try:
if int(request.headers.get("content-length") or 0) > cap:
raise _TooLarge
except ValueError:
raise _TooLarge from None
out = bytearray()
async for chunk in request.stream():
out += chunk
if len(out) > cap:
raise _TooLarge
return bytes(out)
def _registration_allowed(ip: str) -> bool:
now = time.time()
with _limits_lock:
for k in [k for k, ts in _registrations.items() if not ts or now - ts[-1] > REG_WINDOW_S]:
del _registrations[k]
mine = [t for t in _registrations.get(ip, []) if now - t < REG_WINDOW_S]
if len(mine) >= REG_PER_IP:
_registrations[ip] = mine
return False
_registrations[ip] = mine + [now]
return True
def _push_allowed(ip: str) -> str | None:
"""None when one more approval push may go out for ``ip``, else why not."""
now = time.time()
with _limits_lock:
_pushes[:] = [(t, a) for t, a in _pushes if now - t < 86400]
recent = [(t, a) for t, a in _pushes if now - t < PUSH_WINDOW_S]
if len(_pushes) >= PUSH_DAILY or len(recent) >= PUSH_BURST \
or sum(1 for _, a in recent if a == ip) >= PUSH_PER_IP:
return "too many approval requests — open this page on ai-agent.lab instead"
_pushes.append((now, ip))
return None
# ── discovery ────────────────────────────────────────────────────────────────
def _resource_metadata() -> dict:
return {"resource": RESOURCE, "authorization_servers": [PUBLIC_URL],
"scopes_supported": list(SCOPES), "bearer_methods_supported": ["header"],
"resource_name": "ai-agent", "resource_documentation": OWNER_URL + "/settings/ai-apps"}
def _as_metadata() -> dict:
return {
"issuer": PUBLIC_URL,
"authorization_endpoint": PUBLIC_URL + "/oauth/authorize",
"token_endpoint": PUBLIC_URL + "/oauth/token",
"registration_endpoint": PUBLIC_URL + "/oauth/register",
"revocation_endpoint": PUBLIC_URL + "/oauth/revoke",
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code", "refresh_token"],
"code_challenge_methods_supported": ["S256"],
"token_endpoint_auth_methods_supported": ["none", "client_secret_post",
"client_secret_basic"],
"revocation_endpoint_auth_methods_supported": ["none", "client_secret_post",
"client_secret_basic"],
"scopes_supported": list(SCOPES),
"service_documentation": OWNER_URL + "/settings/ai-apps",
}
@router.get("/.well-known/oauth-protected-resource", include_in_schema=False)
@router.get("/.well-known/oauth-protected-resource/mcp", include_in_schema=False)
def protected_resource():
return JSONResponse(_resource_metadata(), headers={"Access-Control-Allow-Origin": "*"})
@router.get("/.well-known/oauth-authorization-server", include_in_schema=False)
@router.get("/.well-known/oauth-authorization-server/mcp", include_in_schema=False)
@router.get("/.well-known/openid-configuration", include_in_schema=False)
def authorization_server():
return JSONResponse(_as_metadata(), headers={"Access-Control-Allow-Origin": "*"})
# ── registration (RFC 7591) ──────────────────────────────────────────────────
_SCHEME_RE = re.compile(r"^[a-z][a-z0-9+.-]*$")
# A web redirect's authority: a plain lower-case host name (or [::1]) and an
# optional port — no userinfo, nothing a browser could read differently.
_NETLOC_RE = re.compile(r"^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\[::1\])(?::\d{1,5})?$")
def _redirect_ok(uri: str) -> bool:
"""May an app register this redirect URI? What we show (the host) must be
what a browser goes to, so anything two URL parsers could read two ways
is refused: ``https://evil.example\\@claude.ai/cb`` is claude.ai to
Python and evil.example to a browser (``\\`` is ``/`` there)."""
if not isinstance(uri, str) or not uri.isascii() or "\\" in uri \
or any(c <= " " or c == "\x7f" for c in uri):
return False
try:
u = urllib.parse.urlsplit(uri)
if urllib.parse.urlunsplit(u) != uri: # the parser dropped or moved something
return False
except ValueError:
return False
if not _SCHEME_RE.match(u.scheme) or u.fragment or "#" in uri \
or u.scheme in _BAD_SCHEMES or "@" in u.netloc:
return False
if u.scheme in ("http", "https"):
if not _NETLOC_RE.match(u.netloc) or not u.hostname:
return False
return u.scheme == "https" or u.hostname in ("localhost", "127.0.0.1", "::1")
return True # an app's own scheme: cursor://…, vscode://…
def _oauth_error(code: str, desc: str, status: int = 400) -> JSONResponse:
return JSONResponse({"error": code, "error_description": desc}, status_code=status,
headers={"Cache-Control": "no-store"})
@router.post("/oauth/register", include_in_schema=False)
async def register(request: Request):
try:
body = json.loads(await _body(request, MAX_REGISTER_BODY))
except _TooLarge:
return _oauth_error("invalid_client_metadata", "body too large", 413)
except ValueError:
return _oauth_error("invalid_client_metadata", "body must be JSON")
if not isinstance(body, dict):
return _oauth_error("invalid_client_metadata", "body must be a JSON object")
uris = body.get("redirect_uris")
if not isinstance(uris, list) or not uris or len(uris) > 10 \
or not all(isinstance(u, str) and len(u) <= 500 and _redirect_ok(u) for u in uris):
return _oauth_error("invalid_redirect_uri",
"redirect_uris: https, http on loopback, or an app scheme")
method = body.get("token_endpoint_auth_method") or "client_secret_basic"
if method not in ("none", "client_secret_post", "client_secret_basic"):
return _oauth_error("invalid_client_metadata", f"unsupported auth method {method}")
grants = body.get("grant_types") or ["authorization_code", "refresh_token"]
if "authorization_code" not in grants:
return _oauth_error("invalid_client_metadata", "authorization_code is the only flow")
name = " ".join(str(body.get("client_name") or "").split())[:80] or "An AI app"
if not _registration_allowed(_ip(request)):
return _oauth_error("temporarily_unavailable", "too many registrations from this "
"address today", 429)
try:
cid, secret = await run_in_threadpool(
_store(request).register, name=name, redirect_uris=uris, auth_method=method,
uri=str(body.get("client_uri") or ""))
except OverflowError:
return _oauth_error("temporarily_unavailable", "too many registered apps", 503)
out = {"client_id": cid, "client_id_issued_at": int(time.time()), "client_name": name,
"redirect_uris": uris, "grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"], "token_endpoint_auth_method": method}
if secret:
out.update(client_secret=secret, client_secret_expires_at=0)
return JSONResponse(out, status_code=201, headers={"Cache-Control": "no-store"})
# ── authorization ────────────────────────────────────────────────────────────
def _redirect_with(uri: str, **params) -> str:
u = urllib.parse.urlsplit(uri)
q = urllib.parse.parse_qsl(u.query, keep_blank_values=True)
q += [(k, v) for k, v in params.items() if v not in (None, "")]
return urllib.parse.urlunsplit(u._replace(query=urllib.parse.urlencode(q)))
def _scope_of(raw: str | None) -> str:
"""An app's requested scope → ours: `read` only when it asked for read
alone; the owner picks on the consent page anyway."""
words = set((raw or "").split())
return "read" if words == {"read"} else "full"
@router.get("/oauth/authorize", include_in_schema=False)
def authorize(request: Request, response_type: str = "", client_id: str = "",
redirect_uri: str = "", state: str = "", code_challenge: str = "",
code_challenge_method: str = "", scope: str = "", resource: str = ""):
store = _store(request)
client = store.client(client_id)
# Nothing is redirected until the client and its redirect URI check out
# (RFC 6749 §4.1.2.1): an error page instead.
if not client:
return _page_error("This app isn't registered (or its registration expired) — "
"remove the connector and add it again.")
uris = client.get("redirectUris") or []
if not redirect_uri and len(uris) == 1:
redirect_uri = uris[0]
# …and a registration from before the stricter rules gets no pass.
if redirect_uri not in uris or not _redirect_ok(redirect_uri):
return _page_error("The redirect address doesn't match the one this app registered.")
def refuse(error: str, msg: str, **extra) -> Response:
"""A request refused before anyone consented. Only the usual apps'
callbacks get the OAuth error redirect: for any other address this
would be a link on our host that sends a browser wherever whoever
registered it likes, with no question asked."""
if _host(redirect_uri) in KNOWN_REDIRECT_HOSTS:
return RedirectResponse(_redirect_with(redirect_uri, error=error, state=state,
**extra), 302)
return _page_error(msg)
if response_type != "code":
return refuse("unsupported_response_type", "This app asked for a kind of sign-in "
"ai-agent doesn't do.")
if not code_challenge or code_challenge_method != "S256":
return refuse("invalid_request", "This app didn't send what a safe sign-in needs "
"(PKCE).", error_description="PKCE S256 is required")
if resource and resource.rstrip("/") not in (RESOURCE, PUBLIC_URL):
return refuse("invalid_target", "This app asked to connect to something else "
"than ai-agent.")
if len(state) > 2000 or len(code_challenge) > 200 or len(resource) > 500:
return refuse("invalid_request", "This app's request is malformed.")
ip = _ip(request)
waiting = store.pending_list()
if len(waiting) >= MAX_PENDING \
or sum(1 for r in waiting if r.get("ip") == ip) >= PENDING_PER_IP:
return refuse("temporarily_unavailable", "Too many connection requests are waiting "
"— answer or close those first, or try again in a few minutes.")
rid = store.add_pending({"client": client_id, "name": client.get("name"),
"redirectUri": redirect_uri, "state": state,
"challenge": code_challenge, "scope": _scope_of(scope),
"resource": resource, "ip": ip})
return RedirectResponse(f"/connect/{rid}", 302)
def _page_error(msg: str) -> Response:
"""A plain error page — the PWA's /connect can't show a request that
never parked."""
from html import escape
body = (f"<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'>"
f"<title>ai-agent</title><body style='font:15px system-ui;max-width:28rem;margin:4rem auto;"
f"padding:0 1rem;color:#334'><h1 style='font-size:18px'>Can't connect</h1>"
f"<p>{escape(msg)}</p></body>")
return Response(body, status_code=400, media_type="text/html")
def _host(uri: str) -> str:
try:
u = urllib.parse.urlsplit(uri)
except ValueError:
return uri
return u.hostname or (u.scheme + ":")
def _view(req: dict, rid: str) -> dict:
"""What the consent page shows of a parked request."""
host = _host(req.get("redirectUri") or "")
return {"id": rid, "app": req.get("name") or "An AI app", "redirectHost": host,
"knownHost": host in KNOWN_REDIRECT_HOSTS, "scope": req.get("scope") or "full",
"status": req.get("status"), "createdAt": req.get("created"),
"expiresAt": req.get("exp"), "pushed": bool(req.get("askId")),
"ownerUrl": f"{OWNER_URL}/connect/{rid}"}
def _finish(r: dict) -> dict:
"""A request just decided (``store.decide``) → where this browser goes
next: the app's redirect, with the code or the denial. Only the caller
whose request decided it ever gets here — the code is nowhere else.
A denial is only sent back to the usual apps: to any other address it
would be an open redirect (anyone may register one), so the page just
says it was refused."""
if r.get("status") == "approved":
url = _redirect_with(r["redirectUri"], code=r["code"], state=r.get("state"),
iss=PUBLIC_URL)
elif _host(r.get("redirectUri") or "") in KNOWN_REDIRECT_HOSTS:
url = _redirect_with(r["redirectUri"], error="access_denied", state=r.get("state"))
else:
url = None
return {"status": r.get("status"), "redirect": url}
def _approved(request: Request, rid: str, r: dict, via: str) -> None:
_record(request, "mcp_connected", who=r.get("user"),
detail=f"{r.get('name')} ({r.get('scope')}) → {_host(r.get('redirectUri') or '')}, "
f"approved {via}")
request.app.state.ai.hub.publish({"type": "mcp"})
def _match_numbers() -> tuple[str, list[str]]:
"""The two-digit number the consent page shows, and the three the push
offers (it among them, in random order)."""
rng = secrets.SystemRandom()
three = [str(n) for n in rng.sample(range(10, 100), 3)]
return rng.choice(three), three
def _poll_push(request: Request, rid: str, r: dict) -> dict:
"""The owner answered the push. **Only the number the consent page shows
approves** — he has to be looking at the page that asked, so a push
somebody else raised can't be approved by reflex. Any other answer (a
wrong number, or no label at all) refuses the request and closes it."""
deps = request.app.state.ai
ask = deps.notify_store.ask_status(r["askId"])
if not ask or ask.get("status") != "answered":
return r
answer, want = ask.get("answer"), r.get("number")
if isinstance(answer, str) and want and secrets.compare_digest(answer.strip(), str(want)):
out = _store(request).decide(rid, approve=True, user=OWNER_ID,
scope=r.get("scope") or "full", via="push")
if out:
_approved(request, rid, out, "from the phone (number matched)")
return out or r
return _store(request).decide(rid, approve=False, user=OWNER_ID, via="push") or r
def _guest(request: Request):
"""The guest signed in on this browser (the guest host's session cookie),
never the owner impersonating one."""
from core.auth import _guest_session
g = _guest_session(request)
return g if g is not None and g.impersonator is None else None
def _guest_view(request: Request) -> dict | None:
g = _guest(request)
if g is None:
return None
return {"name": g.name, "allowed": g.mcp
and not request.app.state.ai.security_state.guests_locked()}
@router.get("/oauth/consent/{rid}", responses=_r(schemas.McpRequest))
def consent(request: Request, rid: str):
"""The consent page's poll: the request, and once decided, where to go."""
r = _store(request).pending(rid)
if not r:
raise HTTPException(404, "this request is gone — start again from the app")
if r.get("status") == "pending" and r.get("askId"):
r = _poll_push(request, rid, r)
if r.get("status") in ("approved", "denied"):
return {**_view(r, rid), **_finish(r)}
return {**_view(r, rid), "guest": _guest_view(request)}
class ConsentAction(BaseModel):
action: str # "push" | "deny" | "guest"
scope: str | None = None
def _same_origin(request: Request) -> bool:
from core.auth import _same_origin as same
return same(request)
@router.post("/oauth/consent/{rid}", responses=_r(schemas.McpRequest))
def consent_action(request: Request, rid: str, body: ConsentAction):
"""From the public consent page: send the approval to the owner's phone,
allow it as the signed-in guest, or say no. The owner approves only on
the admin host or by tapping, on his phone, the number this page shows
(``matchNumber``, in this answer only) — never here."""
store = _store(request)
r = store.pending(rid)
if not r or r.get("status") != "pending":
raise HTTPException(404, "this request is gone — start again from the app")
if not _same_origin(request):
raise HTTPException(403, "cross-site request refused")
if body.action == "deny":
out = store.decide(rid, approve=False, user="", via="page")
if not out:
raise HTTPException(404, "this request is gone — start again from the app")
return {**_view(out, rid), **_finish(out)}
if body.action == "guest":
g = _guest(request)
if g is None:
raise HTTPException(401, "sign in first")
if not (_guest_view(request) or {}).get("allowed"):
raise HTTPException(403, "AI apps aren't open to you — the owner can switch them on")
out = store.decide(rid, approve=True, user=g.id,
scope=body.scope if body.scope in SCOPES else None, via="guest")
if not out:
raise HTTPException(409, "this request was already answered or has expired")
_approved(request, rid, out, f"by {g.name}")
return {**_view(out, rid), **_finish(out)}
if body.action != "push":
raise HTTPException(400, "action: push, guest or deny")
now = time.time()
if now - (r.get("pushedAt") or 0) < PUSH_EVERY_S:
return _view(r, rid)
why = _push_allowed(_ip(request))
if why:
raise HTTPException(429, why)
# The access is picked on the page, before the push: the push only asks
# for the number, and says what tapping it allows.
scope = body.scope if body.scope in SCOPES else r.get("scope") or "full"
number, offered = _match_numbers()
from notifications.service import _create_ask
host = _host(r.get("redirectUri") or "")
warn = "" if host in KNOWN_REDIRECT_HOSTS else " ⚠ unknown address"
q = (f"{r.get('name') or 'An app'} wants {'read-only' if scope == 'read' else 'full'} "
f"access to ai-agent (it returns to {host}{warn}). Tap the number on the page you "
f"started this from — if you didn't just start it, ignore this.")
ask = _create_ask(request.app.state.ai, {
"question": q, "options": offered,
"url": f"{OWNER_URL}/connect/{rid}", "type": "auth", "timeoutSecs": 15 * 60})
r = store.update_pending(rid, {"askId": ask["id"], "pushedAt": time.time(), "scope": scope,
"number": number})
if not r:
raise HTTPException(404, "this request is gone — start again from the app")
# The number goes to the browser that asked for the push, here and only
# here: the poll never repeats it.
return {**_view(r, rid), "matchNumber": number}
# ── the owner approves (admin host, Authelia) ───────────────────────────────
@router.get("/api/mcp/pending/{rid}", responses=_r(schemas.McpRequest))
def owner_pending(request: Request, rid: str, _: OwnerDep):
r = _store(request).pending(rid)
if not r:
raise HTTPException(404, "this request is gone — start again from the app")
return _view(r, rid)
class Decision(BaseModel):
approve: bool
scope: str | None = None
@router.post("/api/mcp/pending/{rid}", responses=_r(schemas.McpRequest))
def owner_decide(request: Request, rid: str, body: Decision, _: OwnerDep):
if not _same_origin(request):
raise HTTPException(403, "cross-site request refused")
store = _store(request)
r = store.decide(rid, approve=body.approve, user=OWNER_ID,
scope=body.scope if body.scope in SCOPES else None, via="admin")
if not r:
raise HTTPException(409, "this request was already answered or has expired")
if body.approve:
_approved(request, rid, r, "on the admin host")
if r.get("askId"): # the push it raised is moot now
try:
request.app.state.ai.notify_store.answer_ask(
r["askId"], None, "Allowed on ai-agent.lab" if body.approve
else "Denied on ai-agent.lab")
except Exception: # noqa: BLE001
pass
return {**_view(r, rid), **_finish(r)}
# ── tokens ───────────────────────────────────────────────────────────────────
async def _form(request: Request) -> dict:
"""The token / revoke request's fields (:class:`_TooLarge` past the cap)."""
raw = await _body(request, MAX_TOKEN_BODY)
if "json" in (request.headers.get("content-type") or ""):
try:
d = json.loads(raw)
return d if isinstance(d, dict) else {}
except ValueError:
return {}
return dict(urllib.parse.parse_qsl(raw.decode(errors="replace"), keep_blank_values=True))
def _client_auth(request: Request, form: dict) -> tuple[str, str | None]:
"""client_secret_basic (Authorization: Basic) or _post / none (the form)."""
auth = request.headers.get("authorization") or ""
if auth.lower().startswith("basic "):
try:
cid, _, secret = base64.b64decode(auth[6:]).decode().partition(":")
return urllib.parse.unquote(cid), urllib.parse.unquote(secret)
except (ValueError, UnicodeDecodeError):
return "", None
return form.get("client_id") or "", form.get("client_secret")
@router.post("/oauth/token", include_in_schema=False)
async def token(request: Request):
try:
form = await _form(request)
except _TooLarge:
return _oauth_error("invalid_request", "body too large", 413)
store = _store(request)
cid, secret = _client_auth(request, form)
if not store.client_ok(cid, secret):
# 401 invalid_client makes Claude.ai register again (its docs).
return _oauth_error("invalid_client", "unknown client or bad secret", 401)
grant = form.get("grant_type")
if grant == "authorization_code":
# The store rewrites its file: off the event loop.
out = await run_in_threadpool(
store.redeem, form.get("code") or "", client=cid,
redirect_uri=form.get("redirect_uri") or "",
verifier=form.get("code_verifier") or "")
if not out:
return _oauth_error("invalid_grant", "code expired, used, or PKCE mismatch")
return JSONResponse(out, headers={"Cache-Control": "no-store", "Pragma": "no-cache"})
if grant == "refresh_token":
out = await run_in_threadpool(store.refresh, form.get("refresh_token") or "",
client=cid)
if not out:
return _oauth_error("invalid_grant", "refresh token expired or revoked")
return JSONResponse(out, headers={"Cache-Control": "no-store", "Pragma": "no-cache"})
return _oauth_error("unsupported_grant_type", f"unsupported grant_type {grant!r}")
@router.post("/oauth/revoke", include_in_schema=False)
async def revoke(request: Request):
try:
form = await _form(request)
except _TooLarge:
return _oauth_error("invalid_request", "body too large", 413)
if await run_in_threadpool(_store(request).revoke_token, form.get("token") or ""):
request.app.state.ai.hub.publish({"type": "mcp"}) # a connection ended
return Response(status_code=200)
# ── /mcp ─────────────────────────────────────────────────────────────────────
def _challenge(error: str | None = None) -> dict:
meta = PUBLIC_URL + "/.well-known/oauth-protected-resource/mcp"
v = f'Bearer resource_metadata="{meta}"'
if error:
v += f', error="{error}"'
return {"WWW-Authenticate": v}
def _bearer(request: Request) -> str:
auth = request.headers.get("authorization") or ""
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
def _ctx(request: Request, grant: dict, caller):
deps = request.app.state.ai
settings = deps.mcp.settings()
groups = frozenset(settings["groups"]) & frozenset(mtools.tools.GROUPS)
guest = not caller.is_owner
headers = {AS_USER_HEADER: caller.id} if guest else None
# Bound to a worker (Settings → AI apps → *Acts as*): every call is the
# owner narrowed to it at the gate (workers/bound.py) — a read-only
# connection to its read routes.
worker = (grant.get("worker") or "") if not guest else ""
if worker:
headers = {worker_bound.AS_WORKER_HEADER: worker,
worker_bound.AS_WORKER_MODE_HEADER:
worker_bound.RUN if grant.get("scope") == "full" else worker_bound.READ}
def on_spawn(sid: str) -> None:
deps.meta_store.update(sid, {"via": {"kind": "mcp", "app": grant.get("name"),
"connection": grant["id"]}})
deps.hub.publish({"type": "meta", "id": sid})
return mtools.tools.Ctx(hub=mtools.hub_for(grant, headers),
view_url=(GUEST_PUBLIC_URL or PUBLIC_URL) if guest else OWNER_URL,
scope=grant.get("scope") or "read", groups=groups,
max_wait_s=settings["maxWaitS"], on_spawn=on_spawn, guest=guest,
worker=worker or None)
@router.post("/mcp", include_in_schema=False)
async def mcp(request: Request):
if mtools.tools is None:
return JSONResponse({"error": "the MCP tools aren't installed (no cli/)"}, status_code=503)
token = _bearer(request)
grant = _store(request).authenticate(token) if token else None
if not grant:
return JSONResponse({"error": "invalid_token" if token else "unauthorized"},
status_code=401,
headers=_challenge("invalid_token" if token else None))
try:
caller = mcp_caller(request.app.state.ai, grant.get("user") or "")
except Refused as e:
msg = e.detail.get("message") if isinstance(e.detail, dict) else str(e.detail)
return JSONResponse({"error": "forbidden", "error_description": msg}, status_code=403)
try:
body = json.loads(await _body(request, MAX_MCP_BODY) or b"null")
except _TooLarge:
return JSONResponse({"error": "request too large"}, status_code=413)
except ValueError:
return JSONResponse(mtools.server._error(None, mtools.server.PARSE_ERROR, "invalid JSON"),
status_code=400)
ctx = _ctx(request, grant, caller)
def log_call(event: str, **kw) -> None:
log.info("mcp %s %s %s", grant.get("name"), kw.get("name"), "ok" if kw.get("ok") else "error")
loop = asyncio.get_running_loop()
out = await loop.run_in_executor(_pool, mtools.server.handle_body, body, ctx, log_call)
if out is None:
return Response(status_code=202)
return JSONResponse(out, headers={"Cache-Control": "no-store"})
@router.get("/mcp", include_in_schema=False)
@router.delete("/mcp", include_in_schema=False)
def mcp_no_stream():
"""No server-initiated stream and no sessions to end (stateless)."""
return Response(status_code=405, headers={"Allow": "POST"})
# ── Settings → AI apps (owner) ───────────────────────────────────────────────
def _grant_view(g: dict, users=None, workers=None) -> dict:
out = {k: g.get(k) for k in ("id", "name", "user", "scope", "created", "lastUsed",
"redirectHost", "worker")}
if users is not None and g.get("user") and g["user"] != OWNER_ID:
u = users.get(g["user"]) or {}
out["userName"] = u.get("name") or g["user"]
if workers is not None and g.get("worker"):
out["workerName"] = (workers.get(g["worker"]) or {}).get("name") or g["worker"]
return out
@router.get("/api/mcp", responses=_r(schemas.McpOverview))
def mcp_overview(request: Request, _: OwnerDep):
store = _store(request)
return {"endpoint": RESOURCE, "settings": store.settings(),
"groups": [{"id": g, "tools": [t.name for t in mtools.tools.TOOLS.values()
if t.group == g]}
for g in (mtools.tools.GROUPS if mtools.tools else ())],
"connections": [_grant_view(g, request.app.state.ai.users,
request.app.state.ai.worker_store)
for g in store.grants()],
"pending": [_view(r, r["id"]) for r in store.pending_list()]}
class SettingsPatch(BaseModel):
groups: list[str] | None = None
maxWaitS: int | None = None
@router.put("/api/mcp/settings", responses=_r(schemas.McpSettings))
def mcp_settings(request: Request, body: SettingsPatch, _: OwnerDep):
patch = body.model_dump(exclude_none=True)
if "groups" in patch:
bad = set(patch["groups"]) - set(mtools.tools.GROUPS)
if bad:
raise HTTPException(400, f"unknown group(s): {', '.join(sorted(bad))}")
if "maxWaitS" in patch and not 5 <= patch["maxWaitS"] <= 600:
raise HTTPException(400, "maxWaitS: 5–600")
out = _store(request).set_settings(patch)
request.app.state.ai.hub.publish({"type": "mcp"})
return out
class GrantPatch(BaseModel):
scope: str | None = None
name: str | None = None
# Bind an owner's connection to one of his workers ("" unbinds): its
# calls then see that worker's profile and run there only (workers/bound.py).
worker: str | None = None
@router.patch("/api/mcp/connections/{gid}", responses=_r(schemas.McpConnection))
def mcp_connection_patch(request: Request, gid: str, body: GrantPatch, _: OwnerDep):
patch = body.model_dump(exclude_none=True)
if "scope" in patch and patch["scope"] not in SCOPES:
raise HTTPException(400, "scope: read or full")
if "name" in patch:
patch["name"] = patch["name"].strip()[:80] or "An AI app"
store = _store(request)
deps = request.app.state.ai
if "worker" in patch:
cur = store.grant(gid)
if not cur:
raise HTTPException(404, "no such connection")
patch["worker"] = patch["worker"].strip()
if patch["worker"]:
if cur.get("user") != OWNER_ID:
raise HTTPException(400, "only the owner's connections are bound to a worker")
if not worker_bound.bindable(deps.worker_store.get(patch["worker"])):
raise HTTPException(400, "not one of the owner's workers")
_record(request, "mcp_bound", who=OWNER_ID,
detail=f"{cur.get('name')} → {patch['worker'] or 'every profile'}")
g = store.update_grant(gid, patch)
if not g:
raise HTTPException(404, "no such connection")
deps.hub.publish({"type": "mcp"})
return _grant_view(g, deps.users, deps.worker_store)
@router.delete("/api/mcp/connections/{gid}", responses=_r(schemas.OkResponse))
def mcp_connection_revoke(request: Request, gid: str, _: OwnerDep):
store = _store(request)
g = store.grant(gid)
if not g or not store.revoke(gid):
raise HTTPException(404, "no such connection")
_record(request, "mcp_revoked", who=g.get("user"), detail=f"{g.get('name')} revoked")
request.app.state.ai.hub.publish({"type": "mcp"})
return {"ok": True}
# ── a guest's own (their Settings → AI apps) ─────────────────────────────────
@router.get("/api/me/ai-apps", responses=_r(schemas.MyAiApps))
def my_ai_apps(request: Request, caller: CallerDep):
"""The endpoint to paste into an app and their own connections. ``allowed``
false: the owner hasn't switched AI apps on for them."""
allowed = caller.is_owner or caller.mcp
rows = _store(request).grants(user=caller.id) if allowed else []
return {"endpoint": RESOURCE, "allowed": allowed,
"connections": [_grant_view(g) for g in rows]}
@router.delete("/api/me/ai-apps/{gid}", responses=_r(schemas.OkResponse))
def my_ai_app_revoke(request: Request, gid: str, caller: CallerDep):
store = _store(request)
g = store.grant(gid)
if not g or g.get("user") != caller.id or not store.revoke(gid):
raise HTTPException(404, "no such connection")
_record(request, "mcp_revoked", who=caller.id, detail=f"{g.get('name')} disconnected")
request.app.state.ai.hub.publish({"type": "mcp"})
return {"ok": True}