ermolushka/simple-mcp
If you are the rightful owner of simple-mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
This document provides a comprehensive overview of a Model Context Protocol (MCP) server template built using FastAPI, designed for extensibility and production-readiness.
MCP FastAPI Template
A production-ready, extensible template for building Model Context Protocol (MCP) servers using FastAPI. This template provides a solid foundation with security best practices, comprehensive testing, and Docker deployment support.
๐ Features
- FastAPI Integration: Modern, fast web framework with automatic API documentation
- MCP Protocol Support: Full implementation of Model Context Protocol specifications
- Security First: JWT authentication, role-based access control, rate limiting, input validation, security headers, and CORS protection
- Extensible Architecture: Easy-to-extend tool system with example implementations
- Comprehensive Testing: Unit and integration tests with pytest
- Docker Ready: Production and development Docker configurations
- Monitoring: Prometheus metrics and health checks
- Development Tools: Pre-commit hooks, formatting, and type checking
- Documentation: Interactive API docs with Swagger UI and ReDoc
๐ Requirements
- Python 3.11+
- uv (for dependency management)
- Docker and Docker Compose (for containerized deployment)
๐ Installation
Quick Setup
# Clone the repository
git clone https://github.com/yourusername/mcp-fastapi-template.git
cd mcp-fastapi-template
# Run the setup script
./scripts/setup.sh
Manual Setup
-
Install uv (if not already installed):
curl -LsSf https://astral.sh/uv/install.sh | sh # or: pip install uv
-
Install dependencies:
uv sync
-
Set up pre-commit hooks:
uv run pre-commit install
-
Create environment file:
cp .env.example .env # Edit .env with your configuration
-
Run tests to verify setup:
uv run pytest
๐ Usage
Development Mode
Start the development server with hot reloading:
make run-dev
# or
uv run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
Production Mode
make run
# or
uv run python -m app.main
Docker Deployment
Development
make docker-compose-dev
# or
docker-compose -f docker-compose.dev.yml up --build
Production
make docker-compose-up
# or
docker-compose up --build
With Monitoring Stack
make docker-compose-monitoring
# or
docker-compose --profile monitoring up --build
๐ API Documentation
Once the server is running, you can access:
- Interactive API Docs (Swagger UI): http://localhost:8000/docs
- Alternative API Docs (ReDoc): http://localhost:8000/redoc
- Health Check: http://localhost:8000/health
- Metrics (if enabled): http://localhost:8000/metrics
- Authentication: http://localhost:8000/api/v1/auth/
- MCP Endpoints: http://localhost:8000/api/v1/mcp/
๐ง Configuration
The application is configured using environment variables. Copy .env.example
to .env
and modify as needed:
# Application Configuration
APP_NAME="MCP FastAPI Template"
DEBUG=false
LOG_LEVEL=INFO
# Server Configuration
HOST=0.0.0.0
PORT=8000
# Security Configuration
SECRET_KEY=your-secret-key-change-this-in-production
ALLOWED_HOSTS=["localhost", "127.0.0.1"]
CORS_ORIGINS=["http://localhost:3000"]
# Authentication Configuration
ENABLE_AUTHENTICATION=true
ACCESS_TOKEN_EXPIRE_MINUTES=30
ALLOW_ANONYMOUS_HEALTH_CHECKS=true
ALLOW_ANONYMOUS_METRICS=false
# MCP Configuration
MCP_SERVER_NAME="mcp-fastapi-template"
MCP_CAPABILITIES_TOOLS=true
MCP_CAPABILITIES_RESOURCES=true
MCP_CAPABILITIES_PROMPTS=true
# Rate Limiting
RATE_LIMIT_REQUESTS_PER_MINUTE=100
# Monitoring
ENABLE_METRICS=true
๐ Built-in Tools
The template includes several example MCP tools:
Basic Tools
- echo: Echo back messages
- get_current_time: Get current UTC time
Mathematical Tools
- calculator: Basic mathematical operations (add, subtract, multiply, divide, power, sqrt, factorial)
- statistics: Statistical calculations (mean, median, mode, standard deviation, etc.)
Text Processing Tools
- text_processor: Text manipulation (uppercase, lowercase, word count, hash, base64, etc.)
- text_validator: Text validation (email, URL, phone number, IP address, etc.)
System Tools
- system_info: System information (platform, CPU, memory, disk usage, etc.)
- environment: Environment variable access (non-sensitive only)
๐งช Testing
Automated Tests
Run the test suite:
# Run all tests
make test
# Run with coverage
make test-coverage
# Run specific test categories
uv run pytest tests/unit/
uv run pytest tests/integration/
Manual Testing
1. Start the Development Server
make run-dev
# or
uv run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
2. Basic Health Checks
# Root endpoint - shows server info and available endpoints
curl -s http://localhost:8000/ | jq .
# Health check
curl -s http://localhost:8000/health | jq .
# MCP-specific health check
curl -s http://localhost:8000/api/v1/mcp/health | jq .
3. Authentication (if enabled)
# Login to get access token
curl -s -X POST http://localhost:8000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin123"}' | jq .
# Store token for subsequent requests
export TOKEN="your-jwt-token-here"
# Get current user information
curl -s -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/api/v1/auth/me | jq .
4. List Available MCP Components
# List all available tools (authentication required if enabled)
curl -s -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/api/v1/mcp/tools | jq .
# List all available resources
curl -s -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/api/v1/mcp/resources | jq .
# List all available prompts
curl -s -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/api/v1/mcp/prompts | jq .
5. Test Tool Calls
# Test echo tool
curl -s -X POST http://localhost:8000/api/v1/mcp/tools/echo/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"message": "Hello from MCP server!"}' | jq .
# Test get_current_time tool
curl -s -X POST http://localhost:8000/api/v1/mcp/tools/get_current_time/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{}' | jq .
6. Test Resources & Prompts
# Get server info resource
curl -s -H "Authorization: Bearer $TOKEN" \
http://localhost:8000/api/v1/mcp/resources/server_info | jq .
# Generate greeting prompt
curl -s -X POST http://localhost:8000/api/v1/mcp/prompts/greeting/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"name": "Alice"}' | jq .
7. Test MCP Protocol Directly
# MCP initialize request
curl -s -X POST http://localhost:8000/api/v1/mcp/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"method": "initialize", "id": "test-1"}' | jq .
# MCP tools list request
curl -s -X POST http://localhost:8000/api/v1/mcp/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"method": "tools/list", "id": "test-2"}' | jq .
# MCP tool call request
curl -s -X POST http://localhost:8000/api/v1/mcp/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"method": "tools/call", "params": {"name": "echo", "arguments": {"message": "Hello MCP!"}}, "id": "test-3"}' | jq .
7. Interactive API Documentation
Visit these URLs in your browser while the server is running:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
These provide interactive documentation where you can test all endpoints directly in your browser.
8. Metrics & Monitoring
# View Prometheus metrics
curl -s http://localhost:8000/metrics
# Health check with detailed uptime
curl -s http://localhost:8000/api/v1/mcp/health | jq .
๐ Code Quality
The project includes comprehensive code quality tools:
# Run all quality checks
make qa
# Individual checks
make format # Black + isort formatting
make security # Bandit security analysis
make pre-commit # Run all pre-commit hooks
๐ Project Structure
mcp-fastapi-template/
โโโ app/
โ โโโ api/v1/ # API routes
โ โโโ core/ # Core configuration and utilities
โ โโโ models/ # Data models (if using database)
โ โโโ schemas/ # Pydantic schemas
โ โโโ services/ # Business logic
โ โโโ tools/ # MCP tools implementation
โ โโโ utils/ # Utility functions
โ โโโ main.py # FastAPI application
โโโ tests/
โ โโโ unit/ # Unit tests
โ โโโ integration/ # Integration tests
โโโ scripts/ # Utility scripts
โโโ monitoring/ # Monitoring configuration
โโโ docker-compose.yml # Production Docker setup
โโโ docker-compose.dev.yml # Development Docker setup
โโโ Dockerfile # Production Docker image
โโโ Dockerfile.dev # Development Docker image
โโโ pyproject.toml # Project configuration
๐ Extending the Template
Adding New Tools
- Create a new tool class extending
BaseMCPTool
:
from app.tools.base import BaseMCPTool
from app.schemas.mcp import MCPToolResult
class MyCustomTool(BaseMCPTool):
def __init__(self):
super().__init__(
name="my_custom_tool",
description="Description of what this tool does",
input_schema={
"type": "object",
"properties": {
"param": {"type": "string", "description": "Parameter description"}
},
"required": ["param"]
}
)
async def execute(self, arguments: dict) -> MCPToolResult:
validated_args = self.validate_arguments(arguments)
# Your tool logic here
return MCPToolResult(content=["Result"], is_error=False)
- Register the tool in
app/tools/registry.py
:
from app.tools.my_module import MyCustomTool
# In the ToolRegistry._register_default_tools method:
self.register_tool(MyCustomTool())
Adding New API Endpoints
- Create a new router in
app/api/v1/
:
from fastapi import APIRouter
router = APIRouter(prefix="/my-endpoint", tags=["my-endpoint"])
@router.get("/")
async def my_endpoint():
return {"message": "Hello from my endpoint"}
- Include the router in
app/main.py
:
from app.api.v1.my_endpoint import router as my_router
app.include_router(my_router, prefix="/api/v1")
๐ณ Docker Configuration
Environment Variables for Docker
The Docker setup supports the same environment variables as the local setup. For production, create a .env
file or use Docker secrets.
Custom Docker Images
To create custom images:
# Build production image
docker build -t my-mcp-server .
# Build development image
docker build -f Dockerfile.dev -t my-mcp-server:dev .
๐ Monitoring
The template includes:
- Health Checks: Built-in health endpoints
- Metrics: Prometheus-compatible metrics endpoint
- Logging: Structured logging with configurable levels
- Request Tracking: Request ID tracking and timing
Optional monitoring stack with Docker Compose:
- Prometheus: Metrics collection
- Grafana: Metrics visualization
๐ฏ Why uv?
This template uses uv as the package manager, which provides:
- Speed: 10-100x faster than pip and pip-tools
- Reliability: Reproducible installs with lockfile
- Simplicity: Single tool for dependency resolution and virtual environment management
- Compatibility: Drop-in replacement for pip with full pyproject.toml support
๐ Authentication & Authorization
This template includes a complete authentication and authorization system:
Quick Start with Authentication
# 1. Set your JWT secret key
export SECRET_KEY="your-super-secret-jwt-key-here"
# 2. Start the server
uv run python -m app.main
# 3. Login with default admin user
curl -X POST http://localhost:8000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin123"}'
# 4. Use the returned token in API calls
curl -H "Authorization: Bearer YOUR_TOKEN" \
http://localhost:8000/api/v1/mcp/tools
Default Users
- Admin:
admin
/admin123
(full access) - User:
user
/user123
(limited access)
Features
- JWT Token Authentication with configurable expiration
- Role-Based Access Control (Guest, User, Moderator, Admin)
- Granular Permissions for MCP operations
- Protected Endpoints with automatic token validation
- User Management (register, login, logout, refresh)
Configuration
# Enable/disable authentication
ENABLE_AUTHENTICATION=true
# JWT settings
SECRET_KEY=your-jwt-secret-key
ACCESS_TOKEN_EXPIRE_MINUTES=30
# Anonymous access
ALLOW_ANONYMOUS_HEALTH_CHECKS=true
ALLOW_ANONYMOUS_METRICS=false
For complete documentation, see .
Testing Authentication
# Run the interactive demo
uv run python examples/auth_examples.py
๐ Security Features
- JWT Authentication: Secure token-based authentication
- Role-Based Access Control: User, Moderator, Admin roles with granular permissions
- Rate Limiting: Configurable request rate limiting
- Input Validation: Comprehensive input sanitization
- Security Headers: Standard security headers (CSP, HSTS, etc.)
- CORS Protection: Configurable CORS origins
- Secrets Management: Environment-based configuration
- Non-root Docker: Containers run as non-root users
๐ค Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Make your changes
- Run the quality checks:
make qa
- Commit your changes:
git commit -m 'Add amazing feature'
- Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
๐ License
This project is licensed under the MIT License - see the file for details.
๐ Support
- Create an Issue for bug reports or feature requests
- Check the Documentation for detailed guides
- Join the discussion in Discussions
๐ Acknowledgments
- FastAPI for the excellent web framework
- Model Context Protocol for the protocol specification
- Pydantic for data validation
- uv for fast and reliable dependency management
๐บ Roadmap
- Database integration examples (SQLAlchemy, MongoDB)
- Authentication and authorization - JWT + RBAC implementation โ
- WebSocket support for real-time MCP communication
- Additional tool examples (file operations, API integrations)
- Kubernetes deployment configurations
- CI/CD pipeline examples (GitHub Actions, GitLab CI)
Happy coding! ๐