emersonmccuin-pixel/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 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
- Replace
"Your-MCP-Server-Name"inserver.py - Update server description and version
- 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)
- 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)
- 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)}
-
Test Tool:
- Use MCP Inspector to test the tool
- Verify input validation works
- Test error handling
- Confirm output format
-
Update Server Info:
- Increment
tools_countinget_server_info() - Update description if needed
- Increment
-
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:
-
validate_text_content- Text safety validation with security checks# Example usage in AI conversation: # "Validate this SQL query for safety: SELECT * FROM users" -
process_business_data- Intelligent data processing with business context# Example usage in AI conversation: # "Get active deals from last quarter with business insights" -
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.pyand.env - Update server description and version
- Customize
.envfile 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) orpytest - 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:
- FastMCP Docs: https://gofastmcp.com
- MCP Specification: https://modelcontextprotocol.io
This template ensures you always start with proper MCP protocol and incremental development methodology.