Description
Enhancement Description
I'm working on a project that uses FastMCP, and I'd like to generate a unique trace_id (UUID) for every incoming request and ensure that it's included in all log messages during that request's lifecycle.
I’m currently starting the server like this:
from fastmcp import FastMCP
mcp = FastMCP(name="MyServer")
mcp.run(
transport="sse",
uvicorn_config={"access_log": False}
)
What I’m trying to do:
-
Generate a UUID per incoming request (HTTP or SSE).
-
Propagate it across the entire request lifecycle, including exception handlers.
-
Print it in every log entry, so I can trace logs for a single request easily.
-
Ideally, inject this into existing loggers via a logging filter or similar.
My questions:
-
Is there a recommended way to attach a middleware to FastMCP apps created via mcp.run() or mcp.sse_app()?
-
Can I retrieve the underlying FastAPI/Starlette app from FastMCP and add custom middleware (e.g., to set a ContextVar)?
-
Would it be reasonable to inject a trace_id using contextvars and a logging.Filter to modify log records?
-
Is there any existing support in FastMCP for per-request logging context?
If others have done something similar, I’d love to see an example!
Thanks in advance
Use Case
No response