The platform for continuously improving AI agents.
"""API-key and OAuth authentication for account-aware MCP access."""
from __future__ import annotations
from io import BytesIO
from asgiref.sync import sync_to_async
from django.conf import settings
from django.core.handlers.asgi import ASGIRequest
from rest_framework import exceptions
from starlette.datastructures import URL
from starlette.responses import JSONResponse
from starlette.types import Receive, Scope, Send
from overbae.api.authentication import APITokenBackend
from overbae.core import telemetry
from overbae.models import APIToken, Project
from overbae.services.mcp.context import MCPContext, bind_context
from overbae.services.mcp.errors import MCPError, error_payload
from overbae.services.mcp.oauth import authenticate_access
MCP_PATH = "/api/mcp/"
# Starlette would redirect the other form. MCP clients do not follow that redirect.
MCP_PATHS = (MCP_PATH, MCP_PATH.rstrip("/"))
def _request_for_scope(scope: Scope) -> ASGIRequest:
return ASGIRequest(scope, BytesIO())
def _auth_error(detail: str) -> MCPError:
detail = detail.lower()
if "inactive" in detail:
return MCPError("authentication_failed", "The API key is inactive.")
if "expired" in detail:
return MCPError("authentication_failed", "The API key has expired.")
if "user" in detail:
return MCPError("authentication_failed", "The API key owner is inactive.")
return MCPError("authentication_failed", "The API key is invalid.")
def _client_headers(request) -> dict[str, str]:
return {
"user_agent": request.headers.get("User-Agent", "")[:200],
"protocol_version": request.headers.get("MCP-Protocol-Version", "")[:32],
}
def _authenticate_sync(scope: Scope) -> MCPContext:
request = _request_for_scope(scope)
authorization = request.headers.get("Authorization", "").split(None, 1)
if (
not request.headers.get("X-Api-Key")
and len(authorization) == 2
and authorization[0].lower() == "bearer"
and authorization[1].startswith("om_oauth_")
):
token = authenticate_access(authorization[1]) if settings.MCP_SERVER_URL else None
if token is None:
raise MCPError("authentication_failed", "The OAuth access token is invalid or expired.")
return MCPContext(
user=token.grant.user,
token=token,
project=None,
client_ip=(scope.get("client") or (None, None))[0],
inference_base_url=str(
URL(scope=scope).replace(scheme=request.scheme, path="/api/v1", query="")
),
**_client_headers(request),
)
try:
result = APITokenBackend().resolve(request)
except exceptions.AuthenticationFailed as exc:
raise _auth_error(str(exc.detail)) from None
if result is None:
raise MCPError("authentication_required", "Connect with OAuth or an Overmind API key.")
user, token = result
if not isinstance(token, APIToken):
raise MCPError("authentication_failed", "An MCP API key is required.")
client_ip = (scope.get("client") or (None, None))[0]
token_scope = token.scope if isinstance(token.scope, dict) else {}
resource_ids = token_scope.get("resourceIds")
scope_kind = token_scope.get("scope")
if scope_kind not in {"account", "project"} or (scope_kind == "account" and token.project_id):
raise MCPError("project_required", "The API key has an invalid resource scope.")
if scope_kind == "project" and (
not isinstance(resource_ids, list)
or len(resource_ids) != 1
or token.project_id is None
or str(resource_ids[0]) != str(token.project_id)
):
raise MCPError("project_required", "The MCP API key must be pinned to one project.")
permissions = token_scope.get("permission")
if (
not isinstance(permissions, list)
or not permissions
or any(permission not in {"read", "write"} for permission in permissions)
):
raise MCPError("permission_denied", "The MCP API key has no MCP permissions.")
project = None
if scope_kind == "project":
project = (
Project.objects.filter(
pk=resource_ids[0],
is_active=True,
memberships__user_id=user.pk,
)
.distinct()
.first()
)
if scope_kind == "project" and project is None:
raise MCPError("project_required", "The MCP API key is not valid for a project.")
return MCPContext(
user=user,
token=token,
project=project,
client_ip=client_ip,
inference_base_url=str(
URL(scope=scope).replace(scheme=request.scheme, path="/api/v1", query="")
),
**_client_headers(request),
)
authenticate_scope = sync_to_async(_authenticate_sync, thread_sensitive=True)
class MCPAuthMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope.get("type") != "http" or scope.get("path") not in MCP_PATHS:
await self.app(scope, receive, send)
return
try:
context = await authenticate_scope(scope)
except MCPError as error:
headers = {}
if settings.MCP_SERVER_URL:
origin = settings.MCP_SERVER_URL.removesuffix("/api/mcp/")
headers["WWW-Authenticate"] = (
f'Bearer resource_metadata="{origin}/.well-known/oauth-protected-resource/api/mcp/"'
)
response = JSONResponse(
{"error": error_payload(error)},
status_code=401 if error.data.code.startswith("authentication") else 403,
headers=headers,
)
await response(scope, receive, send)
return
with telemetry.scope(), bind_context(context):
telemetry.annotate(
user_id=context.user.pk,
project_id=context.project.pk if context.project else None,
auth_kind=type(context.token).__name__,
)
await self.app(scope, receive, send)