mcp-server-template

emersonmccuin-pixel/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 henry@mcphub.com.

This template provides a structured approach to developing a FastMCP server using the MCP protocol, ensuring compliance with HAAS-AI development methodology.

Template MCP Server - Production Ready Foundation

A secure, production-ready FastMCP server template with comprehensive validation, testing infrastructure, and AI-first design patterns following HAAS-AI development methodology.

๐Ÿšจ Critical Requirements

ALWAYS USE MCP PROTOCOL - NEVER BASIC HTTP API

  • โœ… Use FastMCP with Streamable-HTTP transport
  • โŒ Never create basic HTTP servers that return JSON
  • โœ… Proper MCP endpoints at /mcp
  • โœ… Add tools one at a time incrementally
  • โœ… Security-first architecture with validation
  • โœ… AI-friendly response structures

Quick Start

1. Setup Environment

# Create virtual environment
python -m venv venv

# Windows
venv\Scripts\activate

# Linux/Mac  
source venv/bin/activate

# Install core dependencies
pip install -r requirements.txt

# Install development tools (recommended)
pip install -r requirements-dev.txt

# Copy and configure environment
copy .env.example .env  # Windows
# cp .env.example .env  # Linux/Mac
# Edit .env with your specific settings

2. Customize Server

  1. Replace "Your-MCP-Server-Name" in server.py
  2. Update server description and version
  3. Modify the server info resource

3. Run Server

# Windows - Use the convenient batch script
start_server.bat

# Or manually:
fastmcp run server.py --transport http --host 0.0.0.0 --port 3000

# Linux/Mac
./start_server.sh

# Direct execution (STDIO transport)
python server.py

4. Test & Validate

# Windows - Run comprehensive test suite
run_tests.bat

# Manual testing:
# Test MCP protocol (should reject basic HTTP)
curl http://localhost:3000/mcp
# Should return: "Not Acceptable: Client must accept text/event-stream"

# Test with MCP Inspector
npx @modelcontextprotocol/inspector@latest
# Use http://localhost:3000/mcp as endpoint

# Run pytest
pytest tests/ -v --cov=server

# Run security tests  
pytest tests/test_security.py -v

Development Methodology

Adding Tools (One at a Time)

  1. Create Input Model:
from pydantic import BaseModel, Field

class YourToolInput(BaseModel):
    parameter: str = Field(..., description="Parameter description")
    limit: int = Field(default=100, ge=1, le=1000)
  1. Add Tool Function:
@mcp.tool
def your_tool_name(input_data: YourToolInput) -> Dict[str, Any]:
    """Clear description of what this tool does."""
    try:
        # Implementation here
        result = process_your_data(input_data.parameter)
        return {
            "success": True,
            "result": result,
            "metadata": {"processed_at": datetime.now().isoformat()}
        }
    except Exception as e:
        logger.error(f"Tool failed: {e}")
        return {"success": False, "error": str(e)}
  1. Test Tool:

    • Use MCP Inspector to test the tool
    • Verify input validation works
    • Test error handling
    • Confirm output format
  2. Update Server Info:

    • Increment tools_count in get_server_info()
    • Update description if needed
  3. Repeat for Next Tool

n8n Integration

Your n8n workflow should use:

{
  "transport": "streamable-http",
  "url": "http://your-server-ip:3000/mcp",
  "protocol": "mcp"
}

Features & Sample Tools

๐Ÿ”’ Security Features

  • Input Validation: Comprehensive Pydantic models with safety checks
  • SQL Injection Protection: Pattern-based unsafe input detection
  • Logging Sanitization: Automatic redaction of sensitive data
  • Request Tracing: Correlation IDs for debugging and monitoring
  • Error Sanitization: Safe error messages without sensitive data exposure

๐Ÿค– Sample AI-First Tools

The template includes three sample tools demonstrating best practices:

  1. validate_text_content - Text safety validation with security checks

    # Example usage in AI conversation:
    # "Validate this SQL query for safety: SELECT * FROM users"
    
  2. process_business_data - Intelligent data processing with business context

    # Example usage in AI conversation:
    # "Get active deals from last quarter with business insights"
    
  3. generate_business_insights - AI-powered business intelligence generation

    # Example usage in AI conversation:
    # "Analyze sales performance trends and provide recommendations"
    

๐Ÿ“‹ Response Structure Standard

All tools follow the StandardMCPResponse pattern:

{
  "success": true,
  "results": { /* tool-specific data */ },
  "suggestions": ["Next action 1", "Next action 2"],
  "business_context": { /* domain insights */ },
  "alternatives": ["Alternative approach if issues"],
  "metadata": { /* technical details */ }
}

File Structure

template-mcp-server/
โ”œโ”€โ”€ server.py              # Main FastMCP server with sample tools
โ”œโ”€โ”€ requirements.txt        # Core Python dependencies  
โ”œโ”€โ”€ requirements-dev.txt    # Development and testing tools
โ”œโ”€โ”€ .env.example           # Comprehensive environment template
โ”œโ”€โ”€ pyproject.toml         # Code quality configuration
โ”œโ”€โ”€ pytest.ini            # Testing configuration
โ”œโ”€โ”€ README.md              # This documentation
โ”œโ”€โ”€ start_server.bat       # Windows startup script
โ”œโ”€โ”€ start_server.sh        # Linux/Mac startup script  
โ”œโ”€โ”€ run_tests.bat          # Windows testing script
โ””โ”€โ”€ tests/                 # Test suite
    โ”œโ”€โ”€ test_server.py     # Core server tests
    โ””โ”€โ”€ test_security.py   # Security validation tests

Best Practices

โœ… DO:

  • Use FastMCP with proper MCP protocol
  • Add tools incrementally (one at a time)
  • Use Pydantic for input validation
  • Include comprehensive error handling
  • Test each tool with MCP Inspector
  • Use proper logging
  • Document each tool clearly

โŒ DON'T:

  • Create basic HTTP APIs instead of MCP
  • Add multiple tools simultaneously
  • Skip input validation
  • Ignore error handling
  • Skip testing individual tools
  • Use generic error messages

Troubleshooting

Common Issues:

  • "Not Acceptable" error: This is correct! MCP protocol rejects basic HTTP
  • Tools not appearing: Check tool registration and server restart
  • Import errors: Ensure virtual environment is activated
  • Connection refused: Check if server is running on correct port

Debug Commands:

# Check server is running
ps aux | grep server.py

# Check port is listening
ss -tlnp | grep :3000

# View server logs
tail -f /tmp/your-server.log

Template Checklist

When creating a new MCP server from this template:

๐Ÿ“‹ Initial Setup

  • Copy template to new project directory
  • Replace server name in server.py and .env
  • Update server description and version
  • Customize .env file with your specific settings
  • Install dependencies: pip install -r requirements.txt
  • Install dev tools: pip install -r requirements-dev.txt

๐Ÿงช Validation

  • Run test suite: run_tests.bat (Windows) or pytest
  • Test basic server startup: python server.py
  • Verify MCP protocol response: curl http://localhost:3000/mcp
  • Test with MCP Inspector: npx @modelcontextprotocol/inspector@latest
  • Validate security features work: pytest tests/test_security.py

๐Ÿ”ง Development

  • Remove sample tools and add your first real tool
  • Test each tool individually with MCP Inspector
  • Write tests for your custom tools
  • Update server info resource with accurate tool count
  • Document your tools in docstrings and README

๐Ÿš€ Production Ready

  • Run full test suite and ensure all tests pass
  • Validate security configurations
  • Test n8n integration (if applicable)
  • Review and update environment variables for production
  • Set up monitoring and logging as needed

Support

For questions about FastMCP and MCP protocol:

This template ensures you always start with proper MCP protocol and incremental development methodology.