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_count
inget_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.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) 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.