simple-mcp

ermolushka/simple-mcp

3.2

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.

Tools
8
Resources
0
Prompts
0

MCP FastAPI Template

License: MIT Python 3.11+ FastAPI Docker

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

  1. Install uv (if not already installed):

    curl -LsSf https://astral.sh/uv/install.sh | sh
    # or: pip install uv
    
  2. Install dependencies:

    uv sync
    
  3. Set up pre-commit hooks:

    uv run pre-commit install
    
  4. Create environment file:

    cp .env.example .env
    # Edit .env with your configuration
    
  5. 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:

๐Ÿ”ง 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:

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

  1. 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)
  1. 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

  1. 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"}
  1. 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

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run the quality checks: make qa
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

๐Ÿ“ License

This project is licensed under the MIT License - see the file for details.

๐Ÿ†˜ Support

๐Ÿ™ Acknowledgments

๐Ÿ—บ 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! ๐ŸŽ‰