sandeep-13-dev/MCP-Server-Template
If you are the rightful owner of MCP-Server-Template 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 template provides a comprehensive foundation for building Model Context Protocol (MCP) servers using FastMCP 2.0, with Docker support and automated deployment.
my_custom_tool
Processes input parameters and returns a result.
process_data
Processes data with specified format and returns the result.
š MCP Server Template
A robust, production-ready template for building FastMCP servers with Docker support, automated deployment, and comprehensive tooling.
š Overview
This template provides a complete foundation for building Model Context Protocol (MCP) servers using FastMCP 2.0. It includes Docker containerization, automated builds, health monitoring, and production-ready configurations.
⨠Features
- šļø FastMCP 2.0 Integration - Latest MCP server framework
- š³ Docker Support - Complete containerization with multi-stage builds
- š Multiple Transports - Streamable HTTP, SSE, and STDIO support
- š Health Monitoring - Built-in health checks and logging
- š§ Development Tools - Testing framework and debugging utilities
- š Comprehensive Documentation - Detailed guides and examples
- š Production Ready - Security, performance, and scalability considerations
- š CI/CD Ready - Automated build and deployment scripts
šļø Architecture
MCP-Server-Template/
āāā src/
ā āāā server.py # Main MCP server implementation
ā āāā tools/ # MCP tools directory
ā ā āāā __init__.py
ā ā āāā example_tools.py # Example tool implementations
ā ā āāā base.py # Base tool classes
ā āāā resources/ # MCP resources directory
ā ā āāā __init__.py
ā ā āāā example_resources.py # Example resource implementations
ā āāā prompts/ # MCP prompts directory
ā ā āāā __init__.py
ā ā āāā example_prompts.py # Example prompt implementations
ā āāā config/
ā āāā __init__.py
ā āāā settings.py # Configuration management
āāā docker/
ā āāā Dockerfile # Multi-stage production build
ā āāā docker-compose.yml # Development environment
ā āāā entrypoint.sh # Container initialization
ā āāā .dockerignore # Docker build optimization
āāā scripts/
ā āāā build.sh # Linux/macOS build script
ā āāā build.cmd # Windows build script
ā āāā test.py # Testing utilities
ā āāā deploy.sh # Deployment automation
āāā tests/
ā āāā test_server.py # Server integration tests
ā āāā test_tools.py # Tool unit tests
ā āāā conftest.py # pytest configuration
āāā docs/
ā āāā quickstart.md # Quick start guide
ā āāā development.md # Development guide
ā āāā deployment.md # Deployment guide
ā āāā api-reference.md # API documentation
ā āāā examples/ # Usage examples
āāā pyproject.toml # Python dependencies
āāā uv.lock # Dependency lock file
āāā README.md # This file
š Quick Start
Prerequisites
- Python 3.11+
- Docker & Docker Compose
- UV package manager (recommended)
1. Clone and Setup
# Clone the template
git clone [<your-repo-url> my-mcp-server](https://github.com/sandeep-13-dev/MCP-Server-Template.git)
cd my-mcp-server
# Install dependencies
uv sync
2. Configure Your Server
Edit src/config/settings.py
:
SERVER_NAME = "My Awesome MCP Server"
SERVER_VERSION = "1.0.0"
SERVER_DESCRIPTION = "Description of your MCP server"
3. Add Your Tools
Create tools in src/tools/
:
from fastmcp import FastMCP
from typing import Dict, Any
mcp = FastMCP("My Server")
@mcp.tool
async def my_custom_tool(param: str) -> Dict[str, Any]:
"""Your custom tool implementation"""
return {"result": f"Processed: {param}"}
4. Run Locally
# Development mode
python src/server.py
# Or with UV
uv run src/server.py
5. Build and Deploy with Docker
# Build container
docker-compose build
# Run in production mode
docker-compose up -d
# Check status
docker-compose ps
docker-compose logs -f
š ļø Development
Project Structure
Core Components
src/server.py
- Main FastMCP server with lifecycle managementsrc/tools/
- MCP tool implementations with async supportsrc/resources/
- Resource providers and templatessrc/prompts/
- Prompt templates and generatorssrc/config/
- Configuration management and environment variables
Development Tools
scripts/test.py
- Comprehensive testing frameworkscripts/build.sh/.cmd
- Cross-platform build automationdocker/
- Complete containerization setuptests/
- Unit and integration test suites
Adding New Tools
- Create a new file in
src/tools/
- Implement your tool using the
@mcp.tool
decorator - Add imports to
src/tools/__init__.py
- Write tests in
tests/test_tools.py
Example tool:
# src/tools/my_tools.py
from fastmcp import FastMCP
from typing import Dict, Any, Optional
import asyncio
mcp = FastMCP.get_instance() # Get shared instance
@mcp.tool
async def process_data(
data: str,
format_type: str = "json",
timeout: Optional[int] = 30
) -> Dict[str, Any]:
"""
Process data with specified format.
Args:
data: Input data to process
format_type: Output format (json, xml, csv)
timeout: Processing timeout in seconds
Returns:
Dict containing processed result
"""
try:
# Your processing logic here
await asyncio.sleep(0.1) # Simulate async work
return {
"success": True,
"result": f"Processed {len(data)} characters as {format_type}",
"timestamp": "2024-12-26T10:00:00Z"
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
Configuration Management
Environment variables are managed through src/config/settings.py
:
# src/config/settings.py
import os
from typing import Optional
class Settings:
# Server Configuration
SERVER_NAME: str = os.getenv("MCP_SERVER_NAME", "MCP Server Template")
SERVER_VERSION: str = os.getenv("MCP_SERVER_VERSION", "1.0.0")
SERVER_DESCRIPTION: str = os.getenv("MCP_SERVER_DESCRIPTION", "A template MCP server")
# Network Configuration
HOST: str = os.getenv("MCP_HOST", "0.0.0.0")
PORT: int = int(os.getenv("MCP_PORT", "8000"))
# Feature Flags
ENABLE_HEALTH_CHECK: bool = os.getenv("ENABLE_HEALTH_CHECK", "true").lower() == "true"
ENABLE_METRICS: bool = os.getenv("ENABLE_METRICS", "false").lower() == "true"
# Security
API_KEY: Optional[str] = os.getenv("API_KEY")
CORS_ORIGINS: list = os.getenv("CORS_ORIGINS", "*").split(",")
settings = Settings()
š³ Docker Deployment
Production Build
The template includes a multi-stage Dockerfile optimized for production:
# Optimized for size and security
FROM python:3.11-slim as production
# Non-root user for security
RUN useradd --create-home --shell /bin/bash mcp
USER mcp
# Minimal dependencies
COPY . /app
WORKDIR /app
# Health check
HEALTHCHECK \
CMD python scripts/healthcheck.py
EXPOSE 8000
CMD ["python", "src/server.py"]
Environment Variables
Configure your deployment with these environment variables:
Variable | Description | Default |
---|---|---|
MCP_SERVER_NAME | Server display name | "MCP Server Template" |
MCP_HOST | Bind address | "0.0.0.0" |
MCP_PORT | Server port | "8000" |
MCP_TRANSPORT | Transport type (http/sse/stdio) | "http" |
LOG_LEVEL | Logging level | "INFO" |
ENABLE_HEALTH_CHECK | Enable health endpoint | "true" |
API_KEY | Optional API key for authentication | None |
Build Scripts
Use the provided build scripts for consistent deployments:
# Linux/macOS
./scripts/build.sh --production --push --tag v1.0.0
# Windows
./scripts/build.cmd --production --push --tag v1.0.0
š Testing
Running Tests
# Run all tests
uv run pytest
# Run with coverage
uv run pytest --cov=src --cov-report=html
# Run specific test file
uv run pytest tests/test_tools.py
# Run integration tests
uv run pytest tests/test_server.py
Test Structure
# tests/test_tools.py
import pytest
from fastmcp import Client
from src.server import create_server
@pytest.fixture
async def mcp_client():
"""Create a test MCP client."""
server = create_server()
client = Client(server)
async with client:
yield client
async def test_process_data_tool(mcp_client):
"""Test the process_data tool."""
result = await mcp_client.call_tool("process_data", {
"data": "test data",
"format_type": "json"
})
assert result[0].text is not None
data = json.loads(result[0].text)
assert data["success"] is True
assert "result" in data
š Client Integration
Cursor IDE
Add to your Cursor settings:
{
"mcpServers": {
"my-mcp-server": {
"transport": "http",
"url": "http://localhost:8000/mcp",
"description": "My custom MCP server"
}
}
}
Claude Desktop
Add to your Claude Desktop configuration:
{
"mcpServers": {
"my-mcp-server": {
"command": "npx",
"args": ["mcp-remote", "http://localhost:8000/mcp"]
}
}
}
Custom Python Client
from fastmcp import Client
import asyncio
async def use_mcp_server():
client = Client("http://localhost:8000/mcp")
async with client:
# List available tools
tools = await client.list_tools()
print(f"Available tools: {[t.name for t in tools]}")
# Use a tool
result = await client.call_tool("process_data", {
"data": "Hello, MCP!",
"format_type": "json"
})
print(f"Result: {result[0].text}")
asyncio.run(use_mcp_server())
š§ Customization
Server Lifecycle
The template includes comprehensive lifecycle management:
# src/server.py
from contextlib import asynccontextmanager
from fastmcp import FastMCP
@asynccontextmanager
async def lifespan(app):
"""Manage server lifecycle."""
print("š Server starting...")
# Startup logic
await initialize_resources()
await setup_monitoring()
yield
# Shutdown logic
await cleanup_resources()
print("š Server stopped")
def create_server() -> FastMCP:
"""Create and configure the MCP server."""
mcp = FastMCP(
name=settings.SERVER_NAME,
version=settings.SERVER_VERSION,
description=settings.SERVER_DESCRIPTION
)
# Import all tools, resources, and prompts
from src.tools import *
from src.resources import *
from src.prompts import *
return mcp
Adding Authentication
# src/config/auth.py
from fastapi import HTTPException, Security
from fastapi.security.api_key import APIKeyHeader
from src.config.settings import settings
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
async def verify_api_key(api_key: str = Security(api_key_header)):
"""Verify API key if authentication is enabled."""
if settings.API_KEY and api_key != settings.API_KEY:
raise HTTPException(
status_code=401,
detail="Invalid API key"
)
return api_key
š Production Considerations
Performance
- Async Design: All tools use async/await for optimal performance
- Connection Pooling: Efficient resource management
- Memory Management: Proper cleanup and garbage collection
- Caching: Built-in caching strategies for frequently accessed data
Security
- Non-root Container: Docker containers run as non-privileged user
- API Key Authentication: Optional API key protection
- CORS Configuration: Configurable cross-origin resource sharing
- Input Validation: Comprehensive input sanitization
Monitoring
- Health Checks: Built-in health monitoring endpoints
- Structured Logging: JSON-formatted logs for easy parsing
- Metrics Collection: Optional metrics export
- Error Tracking: Comprehensive error handling and reporting
Scalability
- Stateless Design: Horizontal scaling ready
- Resource Limits: Configurable memory and CPU limits
- Load Balancing: Compatible with standard load balancers
- Database Integration: Ready for external data stores
š Documentation
- - Get up and running in 5 minutes
- - Detailed development workflow
- - Production deployment strategies
- - Complete API documentation
- - Real-world implementation examples
š¤ Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - 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.
š Acknowledgments
- FastMCP - The excellent MCP framework
- Model Context Protocol - The protocol specification
- Docker - Containerization platform
Built with ā¤ļø for the MCP community