Replies: 1 comment 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) |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?
Beta Was this translation helpful? Give feedback.
All reactions