Skip to content

Request body contention when using FastAPI middleware #226

@alexander-alderman-webb

Description

Thank you for this project! It's great to see more MCP tools.

In the Sentry Python SDK we received a bug report where the request body is consumed by FastAPI Request methods before reaching the handler. The fastapi_mcp endpoint therefore does not respond as expected because the stream is empty by the time the request is handled. See getsentry/sentry-python#4764.

Consuming the request body may be the culprit in other bugs related to using a middleware with fastapi_mcp, such as #171, although it's hard to say without more information. There is a much-discussed issue in the Starlette repository where the responses illustrate some use cases for reading the request body in the middleware (Kludex/starlette#495). In our case, we read the request body to attach to Sentry events such as exceptions in the request-handling code.

I noticed that fastapi_mcp wraps the mcp library, which works on the lower-level ASGI interface (scope, receive, send).

async def handle_fastapi_request(self, request: Request) -> Response:
"""
Handle a FastAPI request by delegating to the session manager.
This converts FastAPI's Request/Response to ASGI scope/receive/send
and then converts the result back to a FastAPI Response.
"""

Do you plan to make the library more FastAPI-friendly in the future, especially for scenarios where users register a middleware that reads request bodies. For example, by extending the pattern you have in overriding the following method?

async def handle_fastapi_post_message(self, request: Request) -> Response:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions