Generic configurable MCP server infrastructure
Project description
Chuk MCP Function Server
A high-performance, configurable MCP (Model Context Protocol) server infrastructure for building domain-specific function servers with pure functions.
Perfect for exposing mathematical calculations, data transformations, and stateless operations as MCP tools with both STDIO and HTTP transport support.
๐ Features
๐๏ธ Infrastructure
- Dual Transport: STDIO and HTTP support out of the box
- Configuration Management: YAML, JSON, environment variables, and CLI args
- Function Filtering: Flexible allowlist/denylist system
- Error Handling: Robust error handling with timeouts and recovery
- Performance: Sub-millisecond latency for pure functions (2,700+ ops/sec)
๐ง Developer Experience
- Pure Function Focus: Optimized for stateless, deterministic functions
- Easy Extension: Simple base classes for domain-specific servers
- Rich CLI: Comprehensive command-line interface with help
- Debugging Tools: Built-in debug and testing utilities
- Type Safety: Full type hints and validation
๐ Production Ready
- Health Monitoring: Built-in health checks and metrics
- Resource Management: Memory and CPU monitoring
- Concurrent Support: Handle multiple simultaneous requests
- CORS Support: Ready for web applications
- Logging: Structured logging with configurable levels
๐ฆ Installation
pip install chuk-mcp-function-server
Optional Dependencies
# For HTTP transport
pip install chuk-mcp-function-server[http]
# For development tools
pip install chuk-mcp-function-server[dev]
# Install everything
pip install chuk-mcp-function-server[full]
๐ Quick Start
1. Create Your Server
#!/usr/bin/env python3
from chuk_mcp_function_server import BaseMCPServer, ServerConfig, main
class MyCalculatorServer(BaseMCPServer):
def __init__(self, config: ServerConfig):
config.server_name = "my-calculator-server"
config.server_description = "Mathematical calculations MCP server"
super().__init__(config)
def _register_tools(self):
"""Register your pure functions as MCP tools."""
self.register_tool(
name="add",
handler=self._add,
schema={
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number"},
"b": {"type": "number", "description": "Second number"}
},
"required": ["a", "b"]
},
description="Add two numbers"
)
async def _add(self, a: float, b: float) -> str:
"""Pure function: add two numbers."""
result = a + b
return f"Result: {a} + {b} = {result}"
if __name__ == "__main__":
main(server_class=MyCalculatorServer)
2. Run Your Server
# STDIO mode (default)
python my_server.py
# HTTP mode
python my_server.py --transport http --port 8000
# With configuration file
python my_server.py --config server-config.yaml
3. Test Your Server
# Create a simple client
import asyncio
import json
async def test_calculator():
# Start your server process and send JSON-RPC messages
# See examples/ directory for complete client implementations
pass
๐ Examples
We provide a complete Weather Calculations Server example that demonstrates:
- โ 10 Pure Weather Functions: Temperature conversions, heat index, wind chill, dew point, sunrise/sunset times, UV calculations, and more
- โ Real Scientific Formulas: NWS heat index, Magnus formula, Tetens formula, barometric corrections
- โ Both Transports: STDIO and HTTP clients with full demonstrations
- โ Performance Benchmarks: Achieving 2,700+ operations/second
Run the Example
# Clone the repository to get examples
git clone https://github.com/your-org/chuk-mcp-function-server.git
cd chuk-mcp-function-server
# Test STDIO transport
uv run examples/weather_calculations_stdio_client.py
# Test HTTP transport
uv run examples/weather_calculations_http_client.py
# Run performance benchmarks
uv run examples/weather_calculations_benchmark.py
๐ง Configuration
Command Line Options
python my_server.py \
--transport http \
--port 8000 \
--host 0.0.0.0 \
--verbose \
--functions add multiply \
--timeout 30
Configuration File (YAML)
# server-config.yaml
transport: http
port: 8000
host: "0.0.0.0"
enable_tools: true
enable_resources: true
enable_prompts: false
log_level: "INFO"
# Function filtering
function_allowlist:
- add
- multiply
- divide
# Performance settings
cache_strategy: smart
computation_timeout: 30.0
max_concurrent_calls: 10
Environment Variables
export MCP_SERVER_TRANSPORT=http
export MCP_SERVER_PORT=8000
export MCP_SERVER_LOG_LEVEL=DEBUG
export MCP_SERVER_FUNCTION_allowlist=add,multiply
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Your Server โ
โ (extends BaseMCPServer) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Chuk MCP Function Server โ
โ โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ โ
โ โ Config โ Function โ โ
โ โ Management โ Filtering โ โ
โ โโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ โ
โ โ STDIO โ HTTP โ โ
โ โ Transport โ Transport โ โ
โ โโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ MCP Protocol Layer โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Key Components
- BaseMCPServer: Your server extends this class
- ServerConfig: Comprehensive configuration management
- FunctionFilter: Control which functions are exposed
- Transport Layer: STDIO and HTTP support
- CLI: Command-line interface and argument parsing
๐ฏ Core Concepts
Pure Functions
This framework is optimized for pure functions - functions that:
- โ Deterministic: Same inputs always produce same outputs
- โ No Side Effects: No database calls, file I/O, or network requests
- โ Stateless: Each function call is independent
- โ Fast: No I/O bottlenecks mean sub-millisecond performance
# โ
Perfect for this framework
async def celsius_to_fahrenheit(self, celsius: float) -> str:
fahrenheit = (celsius * 9/5) + 32
return json.dumps({"celsius": celsius, "fahrenheit": fahrenheit})
# โ Not ideal (has side effects)
async def get_weather_from_api(self, city: str) -> str:
response = await httpx.get(f"http://api.weather.com/{city}")
return response.text
Tool Registration
Register your functions as MCP tools with JSON schemas:
def _register_tools(self):
tools = [
{
"name": "calculate_bmi",
"handler": self._calculate_bmi,
"description": "Calculate Body Mass Index",
"schema": {
"type": "object",
"properties": {
"weight_kg": {"type": "number", "description": "Weight in kilograms"},
"height_m": {"type": "number", "description": "Height in meters"}
},
"required": ["weight_kg", "height_m"]
}
}
]
for tool in tools:
self.register_tool(**tool)
Function Filtering
Control which functions are exposed:
# Configuration
function_allowlist = ["add", "multiply"] # Only these functions
function_denylist = ["dangerous_function"] # Exclude these
domain_allowlist = ["math", "conversion"] # Only these domains
category_allowlist = ["safe"] # Only these categories
๐ Performance
Benchmark results from the weather calculations example:
๐ BENCHMARK RESULTS
================================================================================
Test Name Transport Ops/sec Avg (ms) P95 (ms) Memory (MB)
--------------------------------------------------------------------------------
STDIO Single-Threaded stdio 2702.7 0.4 0.8 40.6
HTTP Single-Threaded http 1499.5 0.7 0.8 50.3
HTTP Concurrent (x5) http 539.3 1.4 1.7 49.6
HTTP Mixed Operations http 1541.9 0.6 0.8 49.7
Perfect for high-performance applications requiring fast mathematical computations.
๐ ๏ธ Development
Project Structure
chuk-mcp-function-server/
โโโ src/chuk_mcp_function_server/
โ โโโ __init__.py # Main exports
โ โโโ base_server.py # BaseMCPServer class
โ โโโ config.py # Configuration management
โ โโโ function_filter.py # Function filtering system
โ โโโ cli.py # Command-line interface
โ โโโ _version.py # Version management
โโโ examples/
โ โโโ weather_calculations_server.py # Complete example server
โ โโโ weather_calculations_stdio_client.py # STDIO client
โ โโโ weather_calculations_http_client.py # HTTP client
โ โโโ weather_calculations_benchmark.py # Performance tests
โโโ tests/ # Test suite
โโโ docs/ # Documentation
Running Tests
# Install development dependencies
pip install chuk-mcp-function-server[dev]
# Run tests
pytest
# Run with coverage
pytest --cov=chuk_mcp_function_server
# Run type checking
mypy src/
# Format code
black src/ examples/
isort src/ examples/
Debug Tools
# Check setup and dependencies
python examples/debug_setup.py
# Test imports and file structure
python examples/test_import.py
# Check server functionality
python examples/weather_calculations_server.py --help
๐ HTTP API
When running in HTTP mode, the server provides additional REST endpoints:
Endpoints
GET /- Server informationGET /health- Health checkPOST /mcp- MCP protocol endpoint
Server Info Response
{
"server": "my-calculator-server",
"version": "1.0.0",
"description": "Mathematical calculations MCP server",
"transport": "http"
}
Health Check Response
{
"status": "healthy",
"timestamp": 1706356800.123,
"server": "my-calculator-server"
}
MCP Protocol
Send JSON-RPC messages to /mcp:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "add",
"arguments": {"a": 5, "b": 3}
}
}
๐ Security Considerations
- Function Filtering: Use allowlist/denylist to control exposed functions
- Input Validation: All tool schemas are validated
- Timeout Protection: Configurable computation timeouts prevent hanging
- Resource Limits: Memory and CPU monitoring with limits
- CORS Configuration: Configurable for web applications
- No Arbitrary Code: Only registered functions can be called
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
Areas for Contribution
- ๐งฎ More Examples: Domain-specific server examples
- ๐ง Tools: Additional CLI utilities and debugging tools
- ๐ Performance: Optimization and benchmarking improvements
- ๐ Documentation: Tutorials and guides
- ๐งช Testing: Test coverage and integration tests
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- MCP Protocol: Built on the Model Context Protocol specification
- FastAPI: HTTP transport powered by FastAPI
- Pydantic: Configuration and validation using Pydantic models
- Weather Science: Example uses real meteorological formulas from NOAA/NWS
๐ Support
- ๐ Documentation: Full documentation
- ๐ Issues: GitHub Issues
- ๐ฌ Discussions: GitHub Discussions
- ๐ง Email: support@chuk-mcp-function-server.com
Built with โค๏ธ for the MCP community
Making it easy to expose pure functions as high-performance MCP tools.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file chuk_mcp_function_server-0.1.1.tar.gz.
File metadata
- Download URL: chuk_mcp_function_server-0.1.1.tar.gz
- Upload date:
- Size: 43.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9af1dddc24c554353cfe5e712dd219aa7dca539e8f7381ca9ca5e739ddb7949c
|
|
| MD5 |
a54f5589348ac846328db156c0b0546d
|
|
| BLAKE2b-256 |
5d3457efe35b716b2c601b39088fe549083d2a9b1cf56acee45e1540c29c86ce
|
File details
Details for the file chuk_mcp_function_server-0.1.1-py3-none-any.whl.
File metadata
- Download URL: chuk_mcp_function_server-0.1.1-py3-none-any.whl
- Upload date:
- Size: 25.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9d40250b2b95580829d2d2d094b8616b3b94e7c3a7399d6f065670f2f13c02ce
|
|
| MD5 |
4daab39b853cbb01470a87cfc142daf6
|
|
| BLAKE2b-256 |
bfab37e5bcbba75bdf54af4c9879ca711edc634f83cf9695c376eb052a57ba0a
|