Chuk MCP功能服务器
  
一种高性能、可配置的MCP(模型上下文协议)服务器基础设施,用于构建具有纯功能的领域特定功能服务器。
非常适合将数学计算、数据转换和无状态操作作为MCP工具公开,同时支持STDIO和HTTP传输。
🚀 特性
🏗️ 基础设施
- 双重运输:开箱即用的STDIO和HTTP支持
- 配置管理:YAML、JSON、环境变量和CLI参数
- 功能过滤:灵活的allowlist/denylist系统
- 错误处理:具有超时和恢复功能的强大错误处理
- 演出:纯函数的亚毫秒延迟(2700+操作/秒)
🔧 开发者体验
- 纯功能焦点:针对无状态、确定性功能进行了优化
- 易于扩展:特定于域的服务器的简单基类
- 丰富的CLI:带帮助的全面命令行界面
- 调试工具:内置调试和测试实用程序
- 类型安全:完整的类型提示和验证
📊 生产就绪
- 健康监测:内置健康检查和指标
- 资源管理:内存和CPU监控
- 并行支持:处理多个同时进行的请求
- CORS支持:已为web应用程序做好准备
- 日志记录:具有可配置级别的结构化日志记录
📦 安装
pip install chuk-mcp-function-server可选依赖关系
# 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]🏃 快速开始
1.创建您的服务器
#!/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.运行服务器
# 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.yaml3.测试您的服务器
# 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📚 例子
我们提供完整的 天气计算服务器 示例演示:
- ✅ 10个纯天气功能:温度转换、热指数、风寒、露点、日出/日落时间、紫外线计算等
- ✅ 真正的科学公式:NWS热指数、马格纳斯公式、泰滕斯公式、气压修正
- ✅ 两种运输方式:带有完整演示的STDIO和HTTP客户端
- ✅ 性能基准:实现2700多次操作/秒
运行示例
# 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🔧 配置
命令行选项
python my_server.py \
--transport http \
--port 8000 \
--host 0.0.0.0 \
--verbose \
--functions add multiply \
--timeout 30配置文件(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环境变量
export MCP_SERVER_TRANSPORT=http
export MCP_SERVER_PORT=8000
export MCP_SERVER_LOG_LEVEL=DEBUG
export MCP_SERVER_FUNCTION_allowlist=add,multiply🏛️ 建筑
┌─────────────────────────────────────┐
│ Your Server │
│ (extends BaseMCPServer) │
├─────────────────────────────────────┤
│ Chuk MCP Function Server │
│ ┌─────────────┬─────────────────┐ │
│ │ Config │ Function │ │
│ │ Management │ Filtering │ │
│ └─────────────┴─────────────────┘ │
│ ┌─────────────┬─────────────────┐ │
│ │ STDIO │ HTTP │ │
│ │ Transport │ Transport │ │
│ └─────────────┴─────────────────┘ │
├─────────────────────────────────────┤
│ MCP Protocol Layer │
└─────────────────────────────────────┘关键组件
- BaseMCP服务器:您的服务器扩展了此类
- 服务器配置:全面的配置管理
- 函数过滤器:控制暴露的功能
- 传输层:STDIO和HTTP支持
- 命令行界面:命令行界面和参数解析
🎯 核心概念
纯函数
此框架针对以下方面进行了优化 纯函数 -功能如下:
- ✅ 确定性的:相同的输入总是产生相同的输出
- ✅ 无副作用:无数据库调用、文件I/O或网络请求
- ✅ 无状态:每个函数调用都是独立的
- ✅ 快速:无I/O瓶颈意味着亚毫秒级性能
# ✅ 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工具注册
使用JSON模式将您的函数注册为MCP工具:
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)功能过滤
控制暴露的功能:
# 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📊 演出
天气计算示例的基准结果:
🏆 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 非常适合需要快速数学计算的高性能应用。
🛠️ 发展
项目结构
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运行测试
# 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/调试工具
# 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
在HTTP模式下运行时,服务器提供额外的REST端点:
端点
GET /-服务器信息GET /health-健康检查POST /mcp-MCP协议端点
服务器信息响应
{
"server": "my-calculator-server",
"version": "1.0.0",
"description": "Mathematical calculations MCP server",
"transport": "http"
}健康检查响应
{
"status": "healthy",
"timestamp": 1706356800.123,
"server": "my-calculator-server"
}MCP协议
将JSON-RPC消息发送到 /mcp:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "add",
"arguments": {"a": 5, "b": 3}
}
}🔒 安全考虑
- 功能过滤:使用allowlist/denylist来控制暴露的函数
- 输入验证:所有工具模式都经过验证
- 超时保护:可配置的计算超时可防止挂起
- 资源限制:内存和CPU监控有限制
- CORS配置:可配置用于web应用程序
- 无任意代码:只能调用已注册的函数
🤝 贡献
我们欢迎捐款!请查看我们的 贡献指南 了解详情。
贡献领域
- 🧮 更多示例:特定于域的服务器示例
- 🔧 工具:其他CLI实用程序和调试工具
- 📊 演出:优化和基准测试改进
- 📚 文档:教程和指南
- 🧪 测试:测试覆盖率和集成测试
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
🙏 致谢
- MCP协议:基于模型上下文协议规范构建
- 快速 API:由FastAPI支持的HTTP传输
- 派丹蒂克:使用Pydantic模型进行配置和验证
- 天气科学:示例使用NOAA/NWS的真实气象公式
📞 支持
- 📖 文档: 全部文件
- 🐛 问题:
- 💬 讨论:
- 📧 电子邮件: support@chuk-mcp-function-server.com
______________________________________________________________________
内置于❤️ 对于MCP社区
*使纯函数易于作为高性能MCP工具公开。*
