From cc8fc5ba3f4e8353b71904aa588fab12d6a862a6 Mon Sep 17 00:00:00 2001 From: Gilles Soulier Date: Mon, 25 May 2026 22:47:24 +0200 Subject: [PATCH] feat(mcp): middleware ASGI Bearer token pour /mcp* --- backend/app/core/mcp_auth.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 backend/app/core/mcp_auth.py diff --git a/backend/app/core/mcp_auth.py b/backend/app/core/mcp_auth.py new file mode 100644 index 0000000..ff01f72 --- /dev/null +++ b/backend/app/core/mcp_auth.py @@ -0,0 +1,26 @@ +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() + if auth != f"Bearer {settings.mcp_api_key}": + 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()), + ], + }) + await send({"type": "http.response.body", "body": body}) + return + await self.app(scope, receive, send)