Claude Code FastAPI MCP Server Guide
Connecting a FastAPI backend to Claude Code through MCP (Model Context Protocol) lets Claude directly query your API endpoints, run database operations, and invoke custom business logic during development. This guide shows you how to build a FastAPI MCP server from scratch and wire it into your Claude Code workflow.
The Problem
Developers building FastAPI applications want Claude Code to understand their API structure, test endpoints, and interact with their database layer. Without MCP integration, Claude can only read your source files. With a FastAPI MCP server, Claude gains live access to your running application, making debugging and development significantly faster.
Quick Solution
- Install the MCP SDK alongside FastAPI:
pip install mcp fastapi uvicorn
- Create
mcp_server.pyin your project root:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("fastapi-tools")
@mcp.tool()
def list_routes() -> str:
"""List all registered FastAPI routes."""
from main import app
routes = [f"{r.methods} {r.path}" for r in app.routes]
return "\n".join(routes)
@mcp.tool()
def test_endpoint(method: str, path: str) -> str:
"""Test a FastAPI endpoint locally."""
from httpx import Client
client = Client(base_url="http://localhost:8000")
resp = client.request(method, path)
return f"Status: {resp.status_code}\n{resp.text[:500]}"
- Add to your
.mcp.json:
{
"mcpServers": {
"fastapi-tools": {
"command": "python",
"args": ["mcp_server.py"],
"cwd": "/path/to/your/project"
}
}
}
-
Start your FastAPI app in one terminal, then launch Claude Code in another.
-
Claude can now call
list_routesandtest_endpointas tools.
How It Works
MCP (Model Context Protocol) is the standard way Claude Code connects to external tools. When you define a FastMCP server, it exposes Python functions as tools that Claude can invoke during a conversation. The server runs as a subprocess managed by Claude Code.
Your FastAPI application runs normally on localhost:8000. The MCP server acts as a bridge, using httpx or direct Python imports to call your FastAPI endpoints and return results to Claude. This gives Claude live feedback about response codes, payloads, and errors without you manually copy-pasting curl output.
CLAUDE.md awareness matters here. When your CLAUDE.md documents the API structure and available MCP tools, Claude makes better decisions about when to use each tool and how to interpret responses.
Common Issues
MCP server fails to start. Ensure your Python environment has both mcp and your project dependencies installed. Use the same virtual environment for the MCP server and your FastAPI app. Check with which python in Claude Code’s terminal.
Circular import errors. If mcp_server.py imports from main.py at module level, you may hit circular imports. Use lazy imports inside tool functions as shown in the example above.
Endpoint returns empty response. Make sure your FastAPI app is running before Claude tries to call the MCP tool. The MCP server does not start your FastAPI app automatically.
Example CLAUDE.md Section
# FastAPI Project with MCP
## Stack
- Python 3.12, FastAPI 0.115, SQLAlchemy 2.0
- Database: PostgreSQL via asyncpg
- MCP server: mcp_server.py (auto-started by Claude Code)
## MCP Tools Available
- list_routes: Shows all API endpoints
- test_endpoint: Hits an endpoint and returns status + body
- query_db: Runs a read-only SQL query (SELECT only)
## Rules
- Always run tests with: pytest -x --tb=short
- Use async def for all route handlers
- Pydantic models go in schemas/ directory
- Never modify alembic migration files directly
Best Practices
- Add read-only database tools so Claude can inspect data without risk of mutations. Restrict MCP tools to SELECT queries only.
- Include response schema validation in your MCP tools so Claude gets structured feedback about whether responses match expected Pydantic models.
- Keep MCP tools focused on one action each. Instead of a generic “call any endpoint” tool, create specific tools for common operations.
- Log MCP tool calls to a file so you can audit what Claude accessed during a development session.
Related Reading
Built by theluckystrike. More at zovo.one