Last active
April 16, 2025 01:32
-
-
Save eug/93bf43337dfb7f3a5b835378e187a399 to your computer and use it in GitHub Desktop.
FastMCP+ FastAPI Integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from fastapi import FastAPI | |
| from starlette.routing import Mount, Route | |
| from mcp.server import FastMCP | |
| from mcp.server.sse import SseServerTransport | |
| mcp = FastMCP("MCP") | |
| sse = SseServerTransport("/messages/") | |
| async def handle_sse(request): | |
| async with sse.connect_sse( | |
| request.scope, request.receive, request._send | |
| ) as streams: | |
| await mcp._mcp_server.run( | |
| streams[0], | |
| streams[1], | |
| mcp._mcp_server.create_initialization_options(), | |
| ) | |
| app = FastAPI( | |
| title="FastAPI + FastMCP Server", | |
| description="", | |
| version="0.1.0", | |
| routes=[ | |
| Route("/sse", endpoint=handle_sse), | |
| Mount("/messages/", app=sse.handle_post_message), | |
| ] | |
| ) | |
| @app.get("/demo") | |
| async def api_call(id: str): | |
| return f"API returned id={id}" | |
| @mcp.tool() | |
| async def mcp_call(id: str) -> str: | |
| """Simple MCP tool""" | |
| return await api_call(id) | |
| # Run FastAPI and MCP server with the command: `fastapi run demo.py --port 3001` | |
| # The API docs is available at `http://localhost:3001/docs` | |
| # The MCP SSE endpoint is available at `http://localhost:3001/sse` | |
| # In other terminal, you can inspect the MCP with the command `mcp dev demo.py`, then visit `http://localhost:5173/#tools` | |
| # Run **only** the MCP server via STDIO with the command: `uv run --with mcp mcp run demo.py` | |
| # Run FastAPI and MCP server via STDIO with the command: `uv run --with fastapi fastapi run demo.py --port 3001` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment