import hmac import json from starlette.types import ASGIApp, Receive, Scope, Send from app.core.config import settings class MCPAuthMiddleware: def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] == "http" and scope.get("path", "").startswith("/mcp"): headers = dict(scope.get("headers", [])) auth = headers.get(b"authorization", b"").decode() expected = f"Bearer {settings.mcp_api_key}" if not settings.mcp_api_key or not hmac.compare_digest(auth, expected): body = json.dumps({"detail": "Unauthorized"}).encode() await send({ "type": "http.response.start", "status": 401, "headers": [ (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode()), (b"www-authenticate", b"Bearer"), ], }) await send({"type": "http.response.body", "body": body}) return await self.app(scope, receive, send)