Skip to main content

Generic configurable MCP server infrastructure

Project description

Chuk MCP Function Server

Python 3.8+ License: MIT MCP Protocol

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 information
  • GET /health - Health check
  • POST /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


Built with โค๏ธ for the MCP community

Making it easy to expose pure functions as high-performance MCP tools.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chuk_mcp_function_server-0.1.1.tar.gz (43.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chuk_mcp_function_server-0.1.1-py3-none-any.whl (25.0 kB view details)

Uploaded Python 3

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

Hashes for chuk_mcp_function_server-0.1.1.tar.gz
Algorithm Hash digest
SHA256 9af1dddc24c554353cfe5e712dd219aa7dca539e8f7381ca9ca5e739ddb7949c
MD5 a54f5589348ac846328db156c0b0546d
BLAKE2b-256 5d3457efe35b716b2c601b39088fe549083d2a9b1cf56acee45e1540c29c86ce

See more details on using hashes here.

File details

Details for the file chuk_mcp_function_server-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for chuk_mcp_function_server-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9d40250b2b95580829d2d2d094b8616b3b94e7c3a7399d6f065670f2f13c02ce
MD5 4daab39b853cbb01470a87cfc142daf6
BLAKE2b-256 bfab37e5bcbba75bdf54af4c9879ca711edc634f83cf9695c376eb052a57ba0a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page