diff --git a/backend/app/core/mcp_auth.py b/backend/app/core/mcp_auth.py index ff01f72..2422421 100644 --- a/backend/app/core/mcp_auth.py +++ b/backend/app/core/mcp_auth.py @@ -1,3 +1,4 @@ +import hmac import json from starlette.types import ASGIApp, Receive, Scope, Send from app.core.config import settings @@ -11,7 +12,8 @@ class MCPAuthMiddleware: if scope["type"] == "http" and scope.get("path", "").startswith("/mcp"): headers = dict(scope.get("headers", [])) auth = headers.get(b"authorization", b"").decode() - if auth != f"Bearer {settings.mcp_api_key}": + 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", @@ -19,6 +21,7 @@ class MCPAuthMiddleware: "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})