Quick Start Guide
This guide will walk you through creating and running your first MCP server using FastAPI-MCP.
If you haven't installed the library yet, please see the Installation page.
1. Create a Basic MCP Server
Create a Python file (e.g., main.py
) and add the following code. This example uses a simple FastAPI application with a few item-related endpoints and exposes them via MCP.
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from fastapi_mcp import FastApiMCP
# --- 1. Define your FastAPI App and Endpoints ---
app = FastAPI(
title="My Items API",
description="A simple API to manage items."
)
class Item(BaseModel):
id: int
name: str
price: float
items_db = {
1: Item(id=1, name="Hammer", price=9.99),
2: Item(id=2, name="Screwdriver", price=5.50),
}
@app.get("/items/", response_model=List[Item], operation_id="list_items")
def list_items():
"""List all available items."""
return list(items_db.values())
@app.get("/items/{item_id}", response_model=Item, operation_id="get_item")
def get_item(item_id: int):
"""Get a specific item by its ID."""
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
# --- 2. Create and Mount the MCP Server ---
mcp = FastApiMCP(app)
mcp.mount_http() # Mounts at the default /mcp path
# --- 3. Add a Runner (for local execution) ---
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
What this code does:
- It defines a standard FastAPI application with two endpoints:
list_items
andget_item
. - We instantiate
FastApiMCP
, passing our FastAPIapp
instance to it. This automatically inspects the app and converts its endpoints into MCP-compatible tools. mcp.mount_http()
adds a new route to our FastAPI app (by default,/mcp
) that will handle all MCP communications using the recommended Streamable HTTP transport.
2. Run the Server
Save the code as main.py
and run it from your terminal:
python main.py
Your FastAPI server and the integrated MCP server are now running. The MCP endpoint is available at http://localhost:8000/mcp
.
3. Connect an MCP Client
Once the server is running, you can connect to it using any MCP-compatible client, such as Claude Desktop, Cursor, or a command-line tool like mcp-remote
.
For a client that supports direct HTTP connections, you would configure it with the server's URL.
Example Client Configuration (claude_desktop_config.json
):
{
"mcpServers": {
"my_fastapi_server": {
"command": "npx",
"args": [
"mcp-remote",
"http://localhost:8000/mcp"
]
}
}
}
When the client connects, it will automatically discover the list_items
and get_item
tools, ready for an LLM to use.