MCP_Server_Template

Matt3rOfFact/MCP_Server_Template

3.1

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 dayong@mcphub.com.

This template provides a comprehensive setup for building Model Context Protocol (MCP) servers using the FastMCP 2.0 framework.

Tools
6
Resources
0
Prompts
0

MCP Server Template

A production-ready template for building MCP (Model Context Protocol) servers using FastMCP 2.0.

Features

  • =� FastMCP 2.0 - Modern Python framework for MCP servers
  • =' Example Tools - Calculator, file operations, web scraper, data processor
  • =� Resources - Configuration, status monitoring, logs access
  • = Authentication - Bearer token and OAuth support
  • =� Middleware - Logging, rate limiting, CORS, request tracking
  • =3 Docker Ready - Multi-stage build with compose configuration
  •  Testing - Comprehensive test suite with pytest
  • =� Type Safety - Full type hints and mypy support
  • <� Production Ready - Environment-based configuration, health checks, monitoring

Quick Start

Prerequisites

  • Python 3.12 or newer
  • UV package manager (pip install uv)

Installation

  1. Clone the repository:
git clone https://github.com/yourusername/mcp-server-template.git
cd mcp-server-template
  1. Install dependencies with UV:
uv sync
  1. Copy environment variables:
cp .env.example .env
# Edit .env with your configuration
  1. Run the server:

For HTTP mode:

uv run python -m mcp_server_template.main

The server will start on http://localhost:8000.

For MCP Inspector (stdio mode):

uv run mcp-server-stdio

Using with MCP Inspector

MCP Inspector is a debugging tool for MCP servers. Here's how to use it with this template:

Option 1: Direct Command

# Install MCP Inspector
npx @modelcontextprotocol/inspector

# Run with your server
npx @modelcontextprotocol/inspector uv run mcp-server-stdio

Option 2: Using Configuration File

  1. Use the provided mcp_config.json:
npx @modelcontextprotocol/inspector mcp_config.json
  1. Or create your own configuration in your MCP client:
{
  "mcpServers": {
    "mcp-server-template": {
      "command": "uv",
      "args": ["run", "mcp-server-stdio"],
      "cwd": "/path/to/mcp-server-template"
    }
  }
}

Available Tools in Inspector:

  • calculate: Perform mathematical operations
  • read_file: Read file contents
  • write_file: Write content to files
  • list_directory: Browse directory contents
  • scrape_url: Extract content from web pages
  • process_data: Transform and analyze data

Available Resources in Inspector:

  • config://settings: View server configuration
  • status://server: Check server health and metrics
  • logs://recent: Access recent log entries

Available Prompts in Inspector:

  • coding_assistant: Programming help prompt
  • data_analyst: Data analysis prompt

Project Structure

mcp-server-template/
�� src/
   �� mcp_server_template/
       �� __init__.py
       �� main.py              # Server entry point
       �� config.py            # Configuration management
       �� tools/               # MCP tools
          �� calculator.py
          �� file_operations.py
          �� web_scraper.py
          �� data_processor.py
       �� resources/           # MCP resources
          �� config_resource.py
          �� status_resource.py
          �� logs_resource.py
       �� middleware/          # Middleware components
           �� auth.py
           �� logging.py
           �� rate_limiting.py
�� tests/                       # Test suite
�� examples/                    # Usage examples
�� docs/                        # Documentation
�� fastmcp.json                # FastMCP configuration
�� pyproject.toml              # Project dependencies
�� Dockerfile                  # Container configuration
�� docker-compose.yml          # Docker compose setup
�� CLAUDE.md                   # AI assistant instructions
�� .cursorrules                # Cursor IDE rules

Available Tools

Calculator

Perform mathematical calculations:

{
  "tool": "calculate",
  "params": {
    "operation": "add",
    "a": 5,
    "b": 3
  }
}

File Operations

Read, write, and list files:

{
  "tool": "read_file",
  "params": {
    "path": "/path/to/file.txt"
  }
}

Web Scraper

Extract content from URLs:

{
  "tool": "scrape_url",
  "params": {
    "url": "https://example.com",
    "selector": ".content"
  }
}

Data Processor

Transform and analyze data:

{
  "tool": "process_data",
  "params": {
    "data": [1, 2, 3, 4, 5],
    "operation": "statistics"
  }
}

Available Resources

  • config://settings - Current server configuration
  • status://server - Server health and metrics
  • logs://recent - Recent log entries

Configuration

Environment Variables

Create a .env file with:

# Environment
ENVIRONMENT=development  # development, staging, production

# Authentication
MCP_AUTH_TOKEN=your-secret-token

# OAuth (optional)
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

# Database (optional)
DATABASE_URL=postgresql://user:password@localhost/dbname

# External APIs (optional)
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key

FastMCP Configuration

Edit fastmcp.json to configure:

  • Server settings
  • Authentication methods
  • Middleware options
  • Resource caching
  • Deployment environments

Development

Running Tests

# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=mcp_server_template --cov-report=html

# Run specific test file
uv run pytest tests/unit/test_calculator.py

Code Quality

# Format code
uv run black src tests

# Lint code
uv run ruff check src tests

# Type checking
uv run mypy src

Adding New Tools

  1. Create a new file in src/mcp_server_template/tools/
  2. Implement the tool class with async methods
  3. Register in main.py using @app.tool()
  4. Add tests in tests/unit/tools/

Example:

# src/mcp_server_template/tools/my_tool.py
class MyTool:
    async def process(self, input: str) -> dict:
        return {"result": f"Processed: {input}"}

# main.py
@app.tool()
async def my_tool(input: str) -> dict:
    return await my_tool_instance.process(input)

Docker Deployment

Build and Run

# Build image
docker build -t mcp-server .

# Run container
docker run -p 8000:8000 --env-file .env mcp-server

# Or use docker-compose
docker-compose up -d

Docker Compose Profiles

# Run with PostgreSQL database
docker-compose --profile with-database up

# Run with Redis cache
docker-compose --profile with-cache up

# Run with Nginx proxy
docker-compose --profile with-proxy up

Production Deployment

Environment Configuration

Set ENVIRONMENT=production to enable:

  • Multi-worker processing
  • File-based logging
  • Optimized performance settings
  • Security hardening

Health Checks

The server provides a /health endpoint for monitoring:

curl http://localhost:8000/health

Monitoring

Access server metrics via the status resource:

{
  "resource": "status://server"
}

Scaling

Adjust worker count in production:

# pyproject.toml or environment
SERVER_WORKERS=4  # Number of worker processes

Security

Authentication

Enable bearer token authentication:

MCP_AUTH_TOKEN=your-secure-token

Requests must include:

Authorization: Bearer your-secure-token

Rate Limiting

Configure in fastmcp.json:

{
  "middleware": {
    "rate_limiting": {
      "enabled": true,
      "requests_per_minute": 60
    }
  }
}

Best Practices

  1. Always use environment variables for secrets
  2. Enable authentication in production
  3. Implement rate limiting
  4. Use HTTPS with proper certificates
  5. Regularly update dependencies
  6. Monitor logs and metrics
  7. Implement proper error handling

AI Assistant Integration

Claude.ai

The project includes CLAUDE.md with specific instructions for Claude to:

  • Challenge assumptions
  • Provide counterpoints
  • Test reasoning
  • Offer alternatives
  • Prioritize correctness

Cursor IDE

The .cursorrules file configures Cursor to:

  • Use UV for package management
  • Follow project conventions
  • Maintain code quality
  • Challenge implementation decisions

Troubleshooting

Common Issues

  1. Import errors

    uv sync  # Reinstall dependencies
    
  2. Port already in use

    # Change port in .env or command line
    uv run uvicorn mcp_server_template.main:app --port 8001
    
  3. Authentication failures

    • Check MCP_AUTH_TOKEN is set correctly
    • Verify Authorization header format
  4. Rate limiting

    • Adjust requests_per_minute in configuration
    • Check X-RateLimit-* response headers

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

MIT License - see LICENSE file for details

Resources

Support

For issues, questions, or suggestions:

  • Open an issue on GitHub
  • Check existing documentation
  • Review the CLAUDE.md file for development guidance

Built with d using FastMCP 2.0