Repository navigation
Replies: 2 comments 2 replies
|
Actually, I’m running into a similar issue, but in my case it’s not about creating a new header — it’s about overriding the value of the Authorization header. I tried implementing this via middleware, but it doesn’t seem to work as expected. I haven’t been able to find any clear examples in the docs either. That said, I did come across this discussion which might be helpful for your use case as well: #1362 For reference, here’s the middleware implementation I tried while proxying requests to a downstream mcp server: from fastmcp.server.middleware import Middleware, MiddlewareContext
from starlette.datastructures import MutableHeaders
class AuthMiddleware(Middleware):
async def _override_auth_header(self, context: MiddlewareContext, auth_token: str | None):
"""
Override the Authorization header in the request.
Args:
context: The middleware context containing the request
auth_token: The token to set, or None to remove the header
Returns:
Modified context with updated headers
"""
request = context.fastmcp_context.request_context.request
new_headers = MutableHeaders(request._headers)
if auth_token:
new_headers["authorization"] = auth_token
else:
del new_headers["authorization"]
request._headers = new_headers
context.fastmcp_context.request_context.request.scope.update(headers=request.headers.raw)
return context
async def on_call_tool(self, context: MiddlewareContext, call_next):
"""
Intercept tool calls to modify auth headers.
"""
# Override auth header based on tool being called
# Example: Different tools might need different auth mechanisms
if "service_name" in context.message.name:
context = await self._override_auth_header(context, auth_token="Bearer <token>")
return await call_next(context) |
|
For A pure ASGI wrapper preserves streaming: class NoBuffering:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
async def send_with_header(message):
if message["type"] == "http.response.start":
headers = list(message.get("headers", []))
headers.append((b"x-accel-buffering", b"no"))
message = {**message, "headers": headers}
await send(message)
await self.app(scope, receive, send_with_header)
mcp_app = mcp.http_app()
app = NoBuffering(mcp_app)Run Do not use this technique to overwrite the inbound Also check the whole path: |
Uh oh!
There was an error while loading. Please reload this page.
Hi,
In the docs I can see get_http_headers() and this is good for reading of http headers.
But I was wondering how to add custom headers?
For example I need to add:
As I found it that this is needed if MCP's are behind nginx or ALB.
My idea was to do this in Middleware. But no examples are provided.
Any ideas?
All reactions