Add user-bound external MCP server and OAuth access

This commit is contained in:
anor
2026-11-27 17:12:15 +10:00
parent 9a8c2de750
commit 70ad8743d2
25 changed files with 1520 additions and 20 deletions
+184 -4
View File
@@ -998,6 +998,11 @@ def _целое(request: Request, имя: str, по_умолчанию: int) ->
def _get_user(request: Request) -> str:
if request.scope.get("mcp_internal") is True:
from mcp_context import current_tool_context
context = current_tool_context()
if context is not None:
return context.username
auth = request.headers.get("authorization", "")
token = auth.removeprefix("Bearer ").strip()
if not token:
@@ -2080,7 +2085,7 @@ async def chat(request: Request):
# есть сам прогон, обрыв связи убивает работу. Включено — прогон уходит в фоновую задачу,
# а браузеру отдаётся зеркало её журнала: закрытая вкладка больше не выбрасывает минуты
# работы, за которые человек уже заплатил.
if db.get_app_setting("agent_jobs", "off") == "on":
if db.get_app_setting("agent_jobs", "off") == "on" or request.scope.get("mcp_internal") is True:
поток = _stream_as_job(message, user, tab_id)
else:
поток = _stream_and_save(message, user, tab_id)
@@ -3216,6 +3221,11 @@ def _reviews_enabled() -> bool:
def _review_owner(request: Request) -> str:
"""Программная дверь: пропуск устройства. С входом на сайте — 403 (не 401): дверь
не та, и человеку это надо сказать прямо."""
if request.scope.get("mcp_internal") is True:
from mcp_context import current_tool_context
context = current_tool_context()
if context is not None and "reviews:run" in context.scopes:
return context.username
import device_auth
try:
return device_auth.require_device(request)["username"]
@@ -3348,9 +3358,12 @@ async def reviews_create(request: Request):
f"попробуйте через {verdict.retry_seconds} с.",
"axis": verdict.axis, "retry_seconds": verdict.retry_seconds},
code="quota_exceeded")
import device_auth
device = await asyncio.to_thread(device_auth.require_device, request)
tab_id = await asyncio.to_thread(_review_tab, user, device.get("tab_id"))
if request.scope.get("mcp_internal") is True:
tab_id = await asyncio.to_thread(_review_tab, user, request.headers.get("x-tab-id"))
else:
import device_auth
device = await asyncio.to_thread(device_auth.require_device, request)
tab_id = await asyncio.to_thread(_review_tab, user, device.get("tab_id"))
est = await asyncio.to_thread(_review_estimate, user, len(items))
got = await asyncio.to_thread(db.create_review, user, tab_id, body.get("title") or "",
items, est["est_rub"], budget,
@@ -5379,6 +5392,173 @@ for _dep_url in ("/batch", "/batch2", "/batch3", "/ssr", "/wizard",
"/generate", "/reference", "/check"):
app.add_api_route(_dep_url, _deprecated_moved, methods=["GET"], include_in_schema=False)
# External user-bound MCP. The mount is last, so the established web and ARM
# routes keep their precedence. Its ASGI session manager has its own lifespan.
from contextlib import asynccontextmanager
from external_mcp import create_mcp_app, resolve_context
from mcp_identity import InfosmetaOAuthProvider
from mcp_context import bind_tool_context
_mcp_issuer = os.environ.get("PUBLIC_BASE_URL", "https://infosmeta.ru").rstrip("/")
_mcp_provider = InfosmetaOAuthProvider(_mcp_issuer, _mcp_issuer + "/mcp")
@app.get("/oauth/consent", response_class=HTMLResponse)
async def mcp_consent_page(request: Request):
if not await _mcp_provider.pending(request.query_params.get("ticket", "")):
raise HTTPException(404, "Запрос подключения истёк")
return HTMLResponse(Path("static/mcp-consent.html").read_text(encoding="utf-8"),
headers={"Cache-Control": "no-store"})
@app.get("/mcp/clients", response_class=HTMLResponse)
async def mcp_clients_page():
return HTMLResponse(Path("static/mcp-clients.html").read_text(encoding="utf-8"),
headers={"Cache-Control": "no-store"})
@app.get("/mcp/confirm-action", response_class=HTMLResponse)
async def mcp_action_page(request: Request):
if not await _mcp_provider.action_info(request.query_params.get("ticket", "")):
raise HTTPException(404, "Запрос подтверждения истёк")
return HTMLResponse(Path("static/mcp-confirm-action.html").read_text(encoding="utf-8"),
headers={"Cache-Control": "no-store"})
@app.get("/api/mcp/action")
async def mcp_action_info(request: Request):
info = await _mcp_provider.action_info(request.query_params.get("ticket", ""))
if not info:
raise HTTPException(404, "Запрос подтверждения истёк")
return {"tab_id": info["tab_id"], "kind": info["kind"]}
@app.post("/api/mcp/action")
async def mcp_action_approve(request: Request):
user = _get_user(request)
body = await _тело(request)
if not isinstance(body.get("ticket"), str):
raise HTTPException(400, "Нужен ticket")
try:
await _mcp_provider.approve_action(body["ticket"], user)
except ValueError:
raise HTTPException(404, "Запрос подтверждения истёк")
return {"ok": True}
@app.get("/api/mcp/consent")
async def mcp_consent_info(request: Request):
pending = await _mcp_provider.pending(request.query_params.get("ticket", ""))
if not pending:
raise HTTPException(404, "Запрос подключения истёк")
return pending
@app.post("/oauth/consent")
async def mcp_consent_decision(request: Request):
user = _get_user(request)
body = await _тело(request)
if not isinstance(body.get("ticket"), str) or type(body.get("approved")) is not bool:
raise HTTPException(400, "Неверное решение о подключении")
pending = await _mcp_provider.pending(body["ticket"])
try:
redirect = await _mcp_provider.confirm(body["ticket"], user, approved=body["approved"])
except ValueError:
raise HTTPException(400, "Запрос подключения истёк")
try:
await asyncio.to_thread(log_action, user, "mcp_consent", "POST", "/oauth/consent",
f"client={pending['client_id'] if pending else '?'};approved={body['approved']}",
_client_ip(request) or None, 200)
except Exception:
logger.exception("MCP consent audit failed")
return JSONResponse({"redirect": redirect}, headers={"Cache-Control": "no-store"})
@app.get("/api/mcp/clients")
async def mcp_connected_clients(request: Request):
return await _mcp_provider.list_clients_for_user(_get_user(request))
@app.delete("/api/mcp/clients/{client_id}")
async def mcp_disconnect_client(client_id: str, request: Request):
user = _get_user(request)
await _mcp_provider.revoke_client_for_user(user, client_id)
try:
await asyncio.to_thread(log_action, user, "mcp_revoke", "DELETE", "/api/mcp/clients",
f"client={client_id}", _client_ip(request) or None, 200)
except Exception:
logger.exception("MCP revoke audit failed")
return {"ok": True}
async def _mcp_file_context(request: Request, needed_scope: str):
raw = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
token = await _mcp_provider.load_access_token(raw) if raw else None
if token is None:
raise HTTPException(401, "MCP token required")
if needed_scope not in token.scopes:
raise HTTPException(403, "Insufficient MCP scope")
try:
return await resolve_context(token, request.query_params.get("tab_id"))
except (ValueError, PermissionError):
raise HTTPException(403, "This tab is unavailable")
@app.post("/mcp/files")
async def mcp_upload_file(request: Request):
context = await _mcp_file_context(request, "files:write")
try:
length = int(request.headers.get("content-length") or 0)
except ValueError:
raise HTTPException(400, "Invalid Content-Length")
if length > MAX_UPLOAD_SIZE + 1024 * 1024:
raise HTTPException(413, "File is too large")
form = await request.form(max_files=1, max_fields=1)
file = form.get("file")
from starlette.datastructures import UploadFile as _StarletteUploadFile
if not isinstance(file, _StarletteUploadFile):
raise HTTPException(400, "Expected multipart field 'file'")
from mcp_adapters import _request as mcp_internal_request
with bind_tool_context(context):
return await upload(mcp_internal_request(context, path="/api/upload", method="POST"), file)
@app.get("/mcp/files/{filename}")
async def mcp_download_file(filename: str, request: Request):
context = await _mcp_file_context(request, "files:read")
from mcp_adapters import _request as mcp_internal_request
with bind_tool_context(context):
response = await download_file(filename, mcp_internal_request(context, path="/api/files/" + filename))
response.headers["Cache-Control"] = "no-store"
return response
@app.get("/mcp/reviews/{review_id}/report")
async def mcp_review_report(review_id: int, request: Request):
context = await _mcp_file_context(request, "reviews:run")
from mcp_adapters import _request as mcp_internal_request
with bind_tool_context(context):
response = await reviews_report(review_id, mcp_internal_request(context, path=f"/api/reviews/{review_id}/report"))
response.headers["Cache-Control"] = "no-store"
return response
_mcp_host = _mcp_issuer.split("://", 1)[1]
_mcp_http_app = create_mcp_app(_mcp_provider, allowed_hosts=[_mcp_host])
_web_lifespan = app.router.lifespan_context
@asynccontextmanager
async def _web_with_mcp_lifespan(app_instance):
async with _web_lifespan(app_instance):
async with _mcp_http_app.router.lifespan_context(_mcp_http_app):
yield
app.router.lifespan_context = _web_with_mcp_lifespan
app.mount("/", _mcp_http_app)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))