# FastAPI MCP Server - Complete Guide
## 🎯 What is This?
The FastAPI MCP Server is a Model Context Protocol server that provides AI assistants (like Claude) with powerful tools to introspect, analyze, and work with FastAPI applications. It's like giving AI X-ray vision into your FastAPI codebase!
## ✨ Key Features
### 🔍 **Route Discovery**
- List all API endpoints
- Filter by HTTP method, path pattern, or tags
- Search routes by content
- Get detailed parameter information
### 📊 **Schema Analysis**
- Extract complete OpenAPI specifications
- View Pydantic model schemas
- Inspect field validations and types
- Get model relationships
### 🔗 **Dependency Analysis**
- Map dependency injection hierarchy
- Find all routes using specific dependencies
- Understand authentication flows
- Analyze middleware usage
### 💻 **Source Code Access**
- View route handler source code
- Inspect function signatures
- See docstrings and comments
- Understand implementation details
## 🚀 Installation
### Option 1: From PyPI (Coming Soon)
```bash
pip install fastapi-mcp-server
```
### Option 2: From Source
```bash
git clone <repository>
cd fastapi-mcp-server
pip install -e .
```
## 📖 Configuration
### For Claude Desktop
Edit your `claude_desktop_config.json`:
**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Linux**: `~/.config/Claude/claude_desktop_config.json`
```json
{
"mcpServers": {
"fastapi": {
"command": "python",
"args": [
"-m",
"fastapi_mcp_server.server"
],
"cwd": "/absolute/path/to/your/fastapi/project"
}
}
}
```
### For Other MCP Clients
The server uses stdio for communication. Start it with:
```bash
python -m fastapi_mcp_server.server
```
## 🎮 Usage Examples
### Example 1: Understanding a New API
**You**: "What endpoints does this API have?"
**AI** (using `list_routes`):
- GET /users - List all users
- GET /users/{user_id} - Get user by ID
- POST /users - Create new user
- PUT /users/{user_id} - Update user
- DELETE /users/{user_id} - Delete user (requires admin)
### Example 2: Finding Authenticated Endpoints
**You**: "Which routes require authentication?"
**AI** (using `analyze_dependencies` + `search_routes`):
Routes using `get_current_user` dependency:
- PUT /users/{user_id}
- GET /users/{user_id}/items
- POST /items
Routes requiring admin access:
- DELETE /users/{user_id}
### Example 3: Understanding Data Models
**You**: "What fields does the User model have?"
**AI** (using `get_model_schema`):
```json
{
"name": "User",
"fields": {
"id": {"type": "int", "required": true},
"email": {"type": "str", "required": true},
"username": {"type": "str", "required": true, "min_length": 3},
"full_name": {"type": "str", "required": false},
"is_active": {"type": "bool", "default": true}
}
}
```
### Example 4: Generating Client Code
**You**: "Generate a TypeScript client for the /users endpoint"
**AI** (using `get_route_details` + `get_model_schema`):
```typescript
interface User {
id: number;
email: string;
username: string;
full_name?: string;
is_active: boolean;
}
async function getUser(userId: number): Promise<User> {
const response = await fetch(`/users/${userId}`);
return response.json();
}
```
### Example 5: Debugging Route Configuration
**You**: "Why is my /users/{user_id} endpoint not validating the ID properly?"
**AI** (using `get_route_details` + `get_route_source`):
Looking at the route definition:
- Parameter: `user_id` (path parameter)
- Type: `int`
- Validation: `ge=1` (greater than or equal to 1)
The validation requires `user_id >= 1`. If you want to allow 0, remove the `ge=1` constraint.
## 🛠️ Available Tools
### 1. load_fastapi_app
**Purpose**: Load a FastAPI application from a module path
**Input**:
```json
{
"app_path": "main:app"
}
```
**Example Use Cases**:
- Initialize the MCP server
- Switch between different FastAPI apps
- Work with apps in submodules
### 2. list_routes
**Purpose**: List all API routes with optional filtering
**Input**:
```json
{
"method_filter": "GET",
"path_filter": "/users",
"tag_filter": "authentication"
}
```
**Example Use Cases**:
- Get overview of API structure
- Find all GET endpoints
- List routes in a specific category
### 3. get_route_details
**Purpose**: Get comprehensive information about a specific route
**Input**:
```json
{
"path": "/users/{user_id}",
"method": "GET"
}
```
**Output Includes**:
- HTTP methods
- Path parameters, query params, headers
- Request body schema
- Response model
- Status codes
- Dependencies
- Tags and metadata
**Example Use Cases**:
- Understand parameter requirements
- Generate API documentation
- Create test cases
- Debug validation issues
### 4. get_openapi_schema
**Purpose**: Extract the complete OpenAPI specification
**Input**:
```json
{
"include_only": ["/users", "/users/{user_id}"]
}
```
**Example Use Cases**:
- Generate API documentation
- Create SDK/client libraries
- Share API specifications
- Validate API design
### 5. list_models
**Purpose**: List all Pydantic models used in the application
**Example Use Cases**:
- Understand data structures
- Find all DTOs
- Map model relationships
- Generate type definitions
### 6. get_model_schema
**Purpose**: Get detailed schema for a specific Pydantic model
**Input**:
```json
{
"model_name": "User"
}
```
**Output Includes**:
- Field names and types
- Validation rules
- Default values
- Descriptions
- JSON schema
**Example Use Cases**:
- Understand data requirements
- Generate forms
- Create database migrations
- Validate data structures
### 7. search_routes
**Purpose**: Search for routes by query and criteria
**Input**:
```json
{
"query": "authentication",
"has_auth": true
}
```
**Example Use Cases**:
- Find routes by functionality
- Locate specific endpoints
- Discover related routes
- Audit security
### 8. analyze_dependencies
**Purpose**: Analyze dependency injection usage across routes
**Output**:
- List of all dependencies
- Routes using each dependency
- Dependency relationships
**Example Use Cases**:
- Understand authentication flow
- Map shared logic
- Refactor dependencies
- Audit authorization
### 9. get_route_source
**Purpose**: View the source code of a route handler
**Input**:
```json
{
"path": "/users",
"method": "POST"
}
```
**Example Use Cases**:
- Understand implementation
- Debug issues
- Learn coding patterns
- Review business logic
## 💡 Best Practices
### 1. Start with load_fastapi_app
Always begin by loading your FastAPI app:
```json
{"app_path": "main:app"}
```
### 2. Use Filters for Large APIs
When working with large APIs, use filters:
```json
{
"method_filter": "POST",
"tag_filter": "users"
}
```
### 3. Combine Tools for Better Insights
- Use `list_routes` → `get_route_details` for comprehensive understanding
- Use `list_models` → `get_model_schema` for data structure analysis
- Use `search_routes` → `get_route_source` for implementation details
### 4. Leverage OpenAPI Schema
The OpenAPI schema is perfect for:
- Generating documentation
- Creating client libraries
- API testing
- Contract validation
## 🎯 Common Workflows
### Workflow 1: New Developer Onboarding
1. `load_fastapi_app` - Load the application
2. `list_routes` - Get overview of all endpoints
3. `analyze_dependencies` - Understand auth and shared logic
4. `list_models` - Learn data structures
### Workflow 2: API Documentation
1. `get_openapi_schema` - Get complete specification
2. `list_routes` - Group by tags
3. `get_route_details` - For each important endpoint
4. `get_model_schema` - For all data models
### Workflow 3: Debugging
1. `search_routes` - Find the problematic endpoint
2. `get_route_details` - Check configuration
3. `get_route_source` - View implementation
4. `analyze_dependencies` - Check dependencies
### Workflow 4: Security Audit
1. `list_routes` - Get all endpoints
2. `analyze_dependencies` - Map auth dependencies
3. `search_routes` - Filter by `has_auth: false`
4. Review unprotected endpoints
## 🔧 Troubleshooting
### App Won't Load
**Error**: "No module named 'your_app'"
**Solution**: Make sure `cwd` in config points to your project directory
### Can't Find Models
**Error**: "Model not found"
**Solution**: Models must be used in routes (request body or response model)
### Source Code Unavailable
**Error**: "Could not get source"
**Solution**: Source code not available for built-in functions or C extensions
## 🚀 Advanced Tips
### Tip 1: Work with Multiple Apps
You can switch between apps by calling `load_fastapi_app` multiple times
### Tip 2: Custom App Locations
Your app can be in any module:
```json
{"app_path": "mypackage.api.application:api_app"}
```
### Tip 3: Filter OpenAPI Schema
Generate documentation for specific endpoints:
```json
{
"include_only": ["/public/endpoint1", "/public/endpoint2"]
}
```
## 📊 Example Output
### Route Details Example
```json
{
"path": "/users/{user_id}",
"methods": ["GET"],
"name": "get_user",
"summary": "Get a user by ID",
"parameters": [
{
"name": "user_id",
"type": "path",
"annotation": "int",
"required": true
}
],
"response_model": {
"type": "User",
"schema": {...}
},
"status_code": 200
}
```
## 🤝 Contributing
This MCP server can be extended with additional tools:
- Database introspection
- Test generation
- Performance analysis
- Security scanning
## 📝 License
MIT License - Feel free to use in your projects!
## 🌟 Why This Matters
FastAPI MCP Server bridges the gap between AI assistants and your FastAPI applications, enabling:
- **Faster Onboarding**: New developers understand APIs instantly
- **Better Documentation**: AI generates accurate, up-to-date docs
- **Smarter Debugging**: AI helps diagnose issues quickly
- **Improved Development**: AI suggests best practices and patterns
---
**Built for the FastAPI Community** 🚀