Handling Dynamically Added Routes
In some advanced scenarios, you might add FastAPI routes to your application after you have already initialized the FastApiMCP
instance. By default, these new routes will not be discovered and exposed as MCP tools.
To address this, FastApiMCP
provides a setup_server()
method that you can call to refresh the server and re-scan the FastAPI application for all available routes.
Refreshing the Server
Here is an example demonstrating how to use setup_server()
:
# examples/05_reregister_tools_example.py
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
app = FastAPI()
@app.get("/items/", operation_id="list_items")
async def list_items():
return [{"id": 1, "name": "Initial Item"}]
# 1. Initialize FastApiMCP and mount it.
# At this point, it only knows about the '/items/' route.
mcp = FastApiMCP(app)
mcp.mount_http()
# 2. Dynamically add a new endpoint after initialization.
# This endpoint will NOT be available as an MCP tool yet.
@app.get("/new/endpoint/", operation_id="new_endpoint")
async def new_endpoint():
return {"message": "This is a new endpoint!"}
# 3. Call setup_server() to refresh the tool list.
# This re-inspects `app.routes` and rebuilds the MCP tools.
mcp.setup_server()
# Now, the 'new_endpoint' tool will be available to MCP clients.
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
When to Use setup_server()
- When your application's routes are generated programmatically at runtime.
- In plugin-based architectures where plugins can register their own FastAPI routes.
- During testing, if you need to add routes on the fly.
Calling setup_server()
is an idempotent operation that completely rebuilds the tool list and handler mappings based on the current state of the FastAPI
app's routes.