A production-ready Python template for building Model Context Protocol (MCP) servers. This template provides a complete foundation with schema validation, comprehensive testing, and example implementations using the Weather API.
This template serves as a starting point for building your own unique MCP servers in Python. It includes:
- Complete MCP server setup with
uvpackage manager - JSON Schema-based tool definitions with clear examples
- Comprehensive input/output validation
- Extensive test suite framework
- Error handling and logging
- 2 example weather tools showing different patterns
- Template instructions embedded in every file for easy customization
python-mcp-server/
βββ mcp_server/ # Main package directory (β οΈ RENAME THIS!)
β βββ __init__.py # Package initialization
β βββ __main__.py # Entry point for the MCP server
β βββ server.py # Core MCP server implementation
β βββ handlers.py # Tool function implementations
β βββ tools.json # Tool schemas and definitions
βββ main.py # Compatibility wrapper for testing
βββ test_server.py # Comprehensive test framework
βββ test_cases.json # Test case definitions
βββ pyproject.toml # Project dependencies and metadata
βββ .env.example # Environment variables template
βββ uv.lock # Locked dependencies
βββ README.md # This file
mcp_server/ to your unique name (e.g., weather_server/) and update imports accordingly.
-
Clone or fork this repository:
git clone https://github.com/yourusername/python-mcp-server.git my-mcp-server cd my-mcp-server -
Make your server unique (Critical!):
# Rename the package folder to avoid conflicts mv mcp_server my_server_name # e.g., mv mcp_server weather_server # Follow template instructions (π―) in these files to update imports: # - my_server_name/server.py (line 18) # - main.py (line 11) # - pyproject.toml (lines 41, 65, 67, 71)
-
Install dependencies with uv:
uv sync
-
Customize for your use case:
- Follow template instructions (π―) embedded in every file
- Replace tool implementations in
my_server_name/handlers.py - Update tool schemas in
my_server_name/tools.json - Modify test cases in
test_cases.json - Update project metadata in
pyproject.toml
-
Run tests to verify:
uv run python test_server.py
your_server_name/server.py
The core MCP server that:
- Loads tool schemas from
tools.json - Handles MCP protocol communication
- Routes tool calls to handler functions
- Manages server lifecycle
Key functions:
load_tool_schemas()- Loads tool definitions from JSONhandle_list_tools()- Returns available tools to MCP clientshandle_call_tool()- Executes tool functions with validationrun_server()- Main server loop
your_server_name/handlers.py
Implement your tool functions here. The template includes Weather API handlers as examples:
# Example tool function structure
async def your_tool_function(param1: str, param2: int = None) -> dict:
"""Your tool implementation."""
# Validate inputs
if not param1:
raise ValueError("param1 is required")
# Process request
result = await process_data(param1, param2)
# Return structured response
return {"status": "success", "data": result}
# Register in TOOL_FUNCTIONS mapping
TOOL_FUNCTIONS = {
"your_tool": your_tool_function,
# Add more tools here
}your_server_name/tools.json
Define your tools using JSON Schema:
{
"name": "YourServer",
"tools": [
{
"name": "your_tool",
"description": "Tool description",
"inputSchema": {
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "Parameter description"
}
},
"required": ["param1"]
},
"outputSchema": {
"type": "object",
"properties": {
"status": {"type": "string"},
"data": {"type": "object"}
}
}
}
]
}Comprehensive testing with:
- Schema structure validation
- Input/output validation
- Tool function testing
- Error case handling
- Performance monitoring
Define test scenarios:
{
"test_cases": [
{
"name": "test_name",
"tool": "your_tool",
"arguments": {
"param1": "test_value"
},
"description": "Test description",
"expected_fields": ["status", "data"],
"should_succeed": true
}
]
}Edit mcp_server/tools.json:
- Update the server name
- Define your tool schemas
- Specify input/output validation rules
Edit mcp_server/handlers.py:
- Remove example Weather API functions
- Add your tool implementations
- Update the
TOOL_FUNCTIONSmapping
Edit pyproject.toml:
- Update project name and description
- Add/remove dependencies as needed
- Update the console script name if desired
Edit test_cases.json:
- Remove example Weather API tests
- Add test cases for your tools
- Include both success and failure scenarios
If your server needs configuration:
- Create a
.envfile for local development - Add environment variable handling in
handlers.py - Document required variables in README
Users can install directly from your repository:
uvx --from git+https://github.com/yourusername/your-mcp-server your-server-name- Update
pyproject.tomlwith your package details - Build the package:
uv build - Publish:
uv publish
Configure in Claude Desktop or other MCP clients:
{
"mcpServers": {
"your-server": {
"command": "uvx",
"args": [
"--from",
"git+https://github.com/yourusername/your-mcp-server",
"your-server-name"
],
"env": {
"YOUR_ENV_VAR": "value"
}
}
}
}This template includes a complete Weather API implementation as a reference showing:
- Multiple tool types - Various weather-related queries
- Complex schemas - Nested objects and arrays
- Error handling - Invalid inputs and API errors
- Async operations - HTTP client integration
- Environment configuration - API key management
- Comprehensive testing - 45+ test cases
| Tool | Description |
|---|---|
get_weather |
Weather forecasts (1-3 days) |
get_weather_history |
Historical weather data |
get_weather_airquality |
Air quality information |
get_astronomy_data |
Sunrise, sunset, moon phases |
search_locations |
Location search |
get_timezone |
Timezone information |
get_sport_events |
Sports event weather |
To use the Weather API example:
- Get a free API key from WeatherAPI.com
- Set
WEATHER_API_KEYin your.envfile - Run tests:
uv run python test_server.py
The template includes a comprehensive test framework:
# Run all tests
uv run python test_server.py
# Test output includes:
# - Schema validation
# - Tool function tests
# - Error handling
# - Performance metrics
# - Success/failure summary- Schema Validation - Validates all tool schemas
- Input Validation - Tests parameter constraints
- Output Validation - Verifies response structure
- Error Cases - Tests invalid inputs
- Performance - Measures response times
- Define schemas in
tools.json - Implement handlers in
handlers.py - Write tests in
test_cases.json - Run tests with
test_server.py - Test with MCP client (Claude Desktop, etc.)
- Package and distribute
This template implements the MCP protocol:
- Communication: JSON-RPC 2.0 over stdio
- Tool Discovery: Clients call
list_toolsto discover available tools - Tool Execution: Clients call
call_toolwith tool name and arguments - Validation: Input/output validated against JSON schemas
- Error Handling: Structured error responses
Contributions to improve this template are welcome:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
This template is provided as open source for use in your MCP server projects.
- Customize - Replace the example implementation with your own tools
- Test - Ensure comprehensive test coverage
- Document - Update this README with your specific details
- Deploy - Share your MCP server with the community
This template provides a solid foundation for building MCP servers in Python. The Weather API implementation serves as a comprehensive example of how to structure tools, handle validation, and implement testing.