MCP-Server-Template

sandeep-13-dev/MCP-Server-Template

3.2

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.

Tools
  1. my_custom_tool

    Processes input parameters and returns a result.

  2. 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.

License: MIT Python 3.11+ Docker FastMCP

šŸ“‹ 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 management
  • src/tools/ - MCP tool implementations with async support
  • src/resources/ - Resource providers and templates
  • src/prompts/ - Prompt templates and generators
  • src/config/ - Configuration management and environment variables
Development Tools
  • scripts/test.py - Comprehensive testing framework
  • scripts/build.sh/.cmd - Cross-platform build automation
  • docker/ - Complete containerization setup
  • tests/ - Unit and integration test suites

Adding New Tools

  1. Create a new file in src/tools/
  2. Implement your tool using the @mcp.tool decorator
  3. Add imports to src/tools/__init__.py
  4. 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 --chown=mcp:mcp . /app
WORKDIR /app

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python scripts/healthcheck.py

EXPOSE 8000
CMD ["python", "src/server.py"]

Environment Variables

Configure your deployment with these environment variables:

VariableDescriptionDefault
MCP_SERVER_NAMEServer display name"MCP Server Template"
MCP_HOSTBind address"0.0.0.0"
MCP_PORTServer port"8000"
MCP_TRANSPORTTransport type (http/sse/stdio)"http"
LOG_LEVELLogging level"INFO"
ENABLE_HEALTH_CHECKEnable health endpoint"true"
API_KEYOptional API key for authenticationNone

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

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

šŸ“„ License

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

šŸ™ Acknowledgments


Built with ā¤ļø for the MCP community