Skip to content

FastMCP connected with Fast API results 400 error #1797

@shanalikhan

Description

@shanalikhan

Description

Everything was working fine, until i connected FastMCP with Fast API and started using connecting with my LangGraph application.

I'm getting the error:

Error in post_writer
Traceback (most recent call last):
  File "/Users/shan/Documents/.env/lib/python3.11/site-packages/mcp/client/streamable_http.py", line 413, in post_writer
    await handle_request_async()
  File "/Users/shan/Documents//.env/lib/python3.11/site-packages/mcp/client/streamable_http.py", line 407, in handle_request_async
    await self._handle_post_request(ctx)
  File "/Users/shan/Documents//.env/lib/python3.11/site-packages/mcp/client/streamable_http.py", line 278, in _handle_post_request
    response.raise_for_status()
  File "/Users/shan/Documents//.env/lib/python3.11/site-packages/httpx/_models.py", line 829, in raise_for_status
    raise HTTPStatusError(message, request=request, response=self)
httpx.HTTPStatusError: Client error '400 Bad Request' for url 'http://0.0.0.0:8001/mcp'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400
Error initializing RecipeGraph: 
Session termination failed: 400
Traceback (most recent call last):
  File "/Users/shan/Documents/src/llm_graph.py", line 446, in <module>
    asyncio.run(main())
  File "/Users/shan/.pyenv/versions/3.11.10/lib/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/Users/shan/.pyenv/versions/3.11.10/lib/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/shan/.pyenv/versions/3.11.10/lib/python3.11/asyncio/base_events.py", line 654, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/Users/shan/Documents/src/llm_graph.py", line 409, in main
    graph_system = await RecipeGraph.ainit([],inputs,'123') # type: ignore
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/shan/Documents///src/llm_graph.py", line 115, in ainit
    raise e
  File "/Users/shan/Documents//src/llm_graph.py", line 109, in ainit
    tools = await asyncio.wait_for(load_mcp_tools(client.session), timeout=30)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/shan/.pyenv/versions/3.11.10/lib/python3.11/asyncio/tasks.py", line 489, in wait_for
    return fut.result()
           ^^^^^^^^^^^^
  File "/Users/shan/Documents/.env/lib/python3.11/site-packages/langchain_mcp_adapters/tools.py", line 172, in load_mcp_tools
    tools = await _list_all_tools(session)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/shan/Documents//.env/lib/python3.11/site-packages/langchain_mcp_adapters/tools.py", line 81, in _list_all_tools
    list_tools_page_result = await session.list_tools(cursor=current_cursor)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/shan/Documents//.env/lib/python3.11/site-packages/mcp/client/session.py", line 386, in list_tools
    result = await self.send_request(
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/shan/Documents/.env/lib/python3.11/site-packages/mcp/shared/session.py", line 261, in send_request
    await self._write_stream.send(SessionMessage(message=JSONRPCMessage(jsonrpc_request), metadata=metadata))
  File "/Users/shan/Documents/.env/lib/python3.11/site-packages/anyio/streams/memory.py", line 256, in send
    raise BrokenResourceError from None
anyio.BrokenResourceError

Running Application with

gunicorn src.mcp_server:app -w 4 -k "uvicorn.workers.UvicornWorker" --bind "0.0.0.0:8001"

Example Server

...

mcp = FastMCP("RecipeSubstitute")
mcp_app = mcp.http_app(path='/mcp',transport="streamable-http")
app = FastAPI(title="E-commerce API", lifespan=mcp_app.lifespan)
app.mount("/", mcp_app)
cache = SimpleMemoryCache(ttl=3600)  # Set TTL to 1 hour
...

Example Client

...
            if not config.OPENAI_API_KEY:
                raise ValueError("OPENAI_API_KEY is required in configuration")

            llm = AzureChatOpenAI(
                model=config.OPENAI_MODEL,
                api_key=SecretStr(config.OPENAI_API_KEY or ""),
                azure_endpoint=config.OPENAI_API_BASE,
                api_version=config.OPENAI_API_VERSION,
                streaming=False,
            )
            client = Client(transport=StreamableHttpTransport(sse_read_timeout=60,url=config.MCP_SERVER_URL))
            await asyncio.wait_for(client._connect(), timeout=30)
            tools = await asyncio.wait_for(load_mcp_tools(client.session), timeout=30)
            logger.info(f"Tools loaded: {', '.join(tool.name for tool in tools)}")

            return cls(llm, client, tools, ingredients, recipe_filters, 'RecipeSubstitute', session_id)
        except Exception as e:
            print(f"Error initializing RecipeGraph: {e}")
            raise e
...

Version Information

FastMCP version:                                                                            2.12.2
MCP version:                                                                                1.13.1
Python version:                                                                            3.11.10
Platform:                                                             macOS-15.6.1-arm64-arm-64bit
FastMCP root path: /Users/shan/Documents/callexcell/agent_assist/.env/lib/python3.11/site-packages

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working. Reports of errors, unexpected behavior, or broken functionality.clientRelated to the FastMCP client SDK or client-side functionality.httpRelated to HTTP transport, networking, or web server functionality.serverRelated to FastMCP server implementation or server-side functionality.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions