使用说明
🚀 模块化MCP(微控制器平台/多通道处理等,具体含义根据上下文确定)组合架构
一个可投入生产的MCP服务器组合——将多个MCP服务器组合成一个统一的端点
🎯 功能
🚀 演出 🛡️ 可靠性 | 🔧(螺丝刀/维修工具) 开发者体验 | |:---:|:---:|:---:| | Redis 缓存 | 连接池 | 类型安全 | | 异步操作 | 错误处理 | 清晰架构 | | 子毫秒级响应 | 平滑故障处理 | 全面日志记录 |
⚡(闪电符号,常用于表示快速、能量或电力等意象) 飞快如闪电
- Redis 缓存首次查询后,响应速度提升100倍
- 连接池高效的数据库连接管理
- **异步/等待(Async/Await)**非阻塞操作以实现最大吞吐量
🏗️ 这个符号可以翻译为“建筑工地”或“正在施工”。 已准备好投入生产
- 模块化架构关注点的清晰分离
- 类型安全全面的类型提示可防止运行时错误
- 错误处理具有用户友好信息的结构化异常层次结构
- 可观测性详细的日志记录,包括缓存命中/未命中追踪
🔌 电源插头/插座 模块化组合架构
- 服务器组合将多个MCP服务器合并为一个终端节点
- 可插拔服务数据库、数学和自定义服务模块
- 动态加载通过配置启用/禁用服务器
- 基于标签的过滤对工具可用性的精细控制
- 可扩展框架添加新的MCP服务器而无需修改核心代码
🚀 快速入门
1️⃣ 安装
# Clone the repository
git clone <your-repo-url>
cd mcp_composition_server
# Install dependencies
pip install -e .
# Install Redis (if not already installed)
# Windows: Download from https://redis.io/download
# Linux: sudo apt install redis-server
# macOS: brew install redis
2️⃣ 配置
创建你的 .env 文件:
# PostgreSQL Configuration
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
# MySQL Configuration
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=your_password
# Redis Cache Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
# Application Settings
LOG_LEVEL=INFO
SAVE_FILES=false
3️⃣ 启动服务器
# Start Redis server
redis-server
# Start the composed MCP server
python main.py
4️⃣ 与客户端进行测试
from fastmcp import Client
async def test_database():
client = Client("http://localhost:8000/mcp")
async with client:
# List tables in PostgreSQL database
result = await client.call_tool("list_tables", {
"db_type": "postgres",
"db_name": "your_database"
})
print(result.content[0].text)
import asyncio
asyncio.run(test_database())
📊 性能对比
| 操作 | 无缓存 | 使用Redis缓存 | 改进 |
|---|---|---|---|
| 首次呼叫 | ~500毫秒 | ~500毫秒 | - |
| 后续调用 | 约500毫秒 | ~5毫秒 | 速度快100倍 🚀 |
| 数据库负载 | 高 | 最小 | 95%的减少 |
🏗️ 架构概述
graph TB
Client[MCP Client] --> Composer[MCP Composition Server]
Composer --> DB[Database Server]
Composer --> Math[Math Server]
Composer --> Custom[Custom Server N...]
DB --> Cache{Redis Cache}
Math --> Cache
Cache -->|Hit| Return[Cached Response]
Cache -->|Miss| Process[Process Request]
Process --> MySQL[(MySQL)]
Process --> Postgres[(PostgreSQL)]
Process --> Store[Store in Cache]
Store --> Return
🎨(彩笔/美术) 所使用的设计模式
- 🔗 组合模式多个MCP服务器集成到统一接口中
- 🏭 工厂模式创建数据库客户端而不暴露实例化逻辑
- **📚 仓储模式(Repository Pattern)**通过统一的接口抽象数据库操作
- 💉 依赖注入服务通过构造函数接收依赖项
- 🎯 单一职责每个服务器/服务都有一个明确的目的
- 🔄 策略模式具有相同接口的不同实现
- 🏗️ 构建器模式基于配置的动态服务器组合
🔧 配置
📁 文件夹 项目结构
mcp-composition-server/
├── 📁 database/ # Database layer
│ ├── __init__.py # Package exports
│ ├── base.py # Abstract interfaces
│ ├── mysql_client.py # MySQL implementation
│ ├── postgres_client.py # PostgreSQL implementation
│ └── factory.py # Database factory
├── 📁 services/ # Business logic layer
│ ├── __init__.py # Package exports
│ ├── table_service.py # Table operations
│ └── math_service.py # Math operations
├── 📁 servers/ # Server modules
│ ├── __init__.py # Package exports
│ ├── database_server.py # Database MCP server
│ └── math_server.py # Math MCP server
├── 📁 utils/ # Utility modules
│ ├── __init__.py # Package exports
│ ├── logger.py # Logging utilities
│ ├── file_utils.py # File operations
│ └── cache_decorator.py # Redis caching with aiocache
├── 📁 outputs/ # Output files (optional)
├── config.py # Configuration management
├── main.py # Composed MCP server
├── test_client.py # Test client example
├── pyproject.toml # Project configuration & dependencies
├── .env # Environment variables
└── README.md # This documentation
⚙️ 这个符号在中文中通常没有直接对应的翻译,它是一个齿轮形状的图标,常用于表示机械、设置、调整或技术相关的概念。在没有具体上下文的情况下,可以简单地将其描述为“齿轮图标”或根据具体语境翻译为“机械装置”、“设置选项”等。 环境变量
| 变量 | 默认值 | 描述 |
|---|---|---|
POSTGRES_HOST |
localhost | PostgreSQL 服务器主机 |
POSTGRES_PORT |
5432 | PostgreSQL 服务器端口 |
POSTGRES_USER |
postgres | PostgreSQL 用户名 |
POSTGRES_PASSWORD |
- | PostgreSQL 密码 |
MYSQL_HOST |
localhost | MySQL 服务器主机 |
MYSQL_PORT |
3306 | MySQL服务器端口 |
REDIS_HOST |
localhost | Redis 服务器主机 |
REDIS_PORT |
6379 | Redis服务器端口 |
LOG_LEVEL |
INFO | 日志级别(DEBUG、INFO、WARNING、ERROR) |
SAVE_FILES |
false | 启用/禁用文件输出 |
ENABLED_SERVERS |
数据库,数学 | 启用的服务器列表,以逗号分隔 |
SERVER_INCLUDE_TAGS |
- | 仅包含带有这些标签的工具 |
SERVER_EXCLUDE_TAGS |
管理员 | 排除带有这些标签的工具 |
🛠️ 可用工具
📋(清单/列表) 数据库工具
列出表(或“显示表列表”)
列出数据库中所有支持缓存的表。
参数:
db_type(字符串):数据库类型 - "mysql" 或 "postgres"db_name(字符串):数据库的名称
示例:
result = await client.call_tool("list_tables", {
"db_type": "postgres",
"db_name": "my_database"
})
计算器(或类似的计算工具) 数学工具
添加
支持缓存的两个数相加。
参数:
a(float): 第一个数字b(float): 第二个数字
示例:
result = await client.call_tool("add", {
"a": 5.5,
"b": 3.2
})
📈 监控与日志记录
🔍 看起来像一个放大镜的符号,常用于表示搜索、查看细节或调查的意思。在中文里,可以简单翻译为“🔍(放大镜)”。如果要结合具体语境,比如表示“仔细查看”或“深入调查”,则可以翻译为相应的中文表达。 缓存监控
服务器为缓存操作提供了详细的日志记录:
# Cache Miss (First Call)
💾 CACHE MISS: list_tables:postgres:mydb - fetching from database
🔍 Fetching tables from postgres database: mydb
✅ Database query completed: 25 tables from mydb
✅ CACHED: list_tables:postgres:mydb (TTL: 300s)
# Cache Hit (Subsequent Calls)
🎯 CACHE HIT: list_tables:postgres:mydb
📊 表格/数据图表 性能指标
监控您的服务器性能:
- 缓存命中率跟踪缓存使用频率与数据库查询频率的对比
- 响应时间监控查询执行时间
- 连接池数据库连接利用率
- 错误率追踪并警报故障
🚀 扩展架构
🔌 电源插头/插座 添加新的MCP服务器
- 在(某平台/服务中)创建您的服务器
servers/my_server.py:
from fastmcp import FastMCP
def create_my_server() -> FastMCP:
server = FastMCP("my-service")
@server.tool()
async def my_tool(param: str) -> str:
return f"Processed: {param}"
return server
- 添加到
servers/__init__.py:
from .my_server import create_my_server
__all__ = [..., "create_my_server"]
- 更新
main.py:
if "my_service" in enabled_servers:
await main_server.import_server(create_my_server())
🛠️(工具/修理) 配置驱动的组合
# Enable only specific servers
ENABLED_SERVERS=database,math,my_service
# Filter by tags
SERVER_INCLUDE_TAGS=production
SERVER_EXCLUDE_TAGS=admin,debug
请查看 EXTENDING.md 获取详细示例
🎯 目标(或“靶心”) 为任意方法添加缓存
from utils.cache_decorator import cached
class MyService:
@cached(ttl=600) # 10 minutes cache
async def expensive_operation(self, param: str) -> Result:
# Automatically cached!
pass
🐳 Docker 支持
📦 箱子/包裹 Docker Compose
version: '3.8'
services:
mcp-composition-server:
build: .
ports:
- "8000:8000"
environment:
- POSTGRES_HOST=postgres
- REDIS_HOST=redis
- ENABLED_SERVERS=database,math
depends_on:
- postgres
- redis
postgres:
image: postgres:15
environment:
POSTGRES_DB: mydb
POSTGRES_USER: user
POSTGRES_PASSWORD: password
redis:
image: redis:7-alpine
ports:
- "6379:6379"
- postgres
- redis
PostgreSQL(简称postgres): 镜像:postgres:15 环境: POSTGRES_DB: mydb(翻译为中文即)数据库名:mydb POSTGRES_USER: 用户 POSTGRES_PASSWORD: 密码
redis(保持原样,因为“redis”是一个专有名词,通常不直接翻译,特指一种内存中的数据结构存储系统) 镜像:redis:7-alpine 端口: - "6379:6379"
### 🚀 **Quick Docker Start**
```bash
# Build and start all services
docker-compose up -d
# View logs
docker-compose logs -f mcp-composition-server
# Stop services
docker-compose down
🧪 测试
使用随附的测试客户端来验证功能:
# Test the composed server with all tools
python test_client.py
# Test specific server composition
ENABLED_SERVERS=math python test_client.py
🤝 贡献
我们欢迎投稿!以下是投稿指南:
📝 贡献指南
- Fork(叉子/分叉) 存储库
- 创造 一个特性分支(
git checkout -b feature/amazing-feature) - 提交 你的更改(
git commit -m 'Add amazing feature') - 推动 到分公司(
git push origin feature/amazing-feature) - 开放 一个拉取请求(或合并请求)
🙏 致谢
- FastMCP - 对于卓越的MCP框架
- aiomysql 和 asyncpg - 用于异步数据库驱动程序
- aiocache(可译为“AI缓存”或根据上下文具体含义翻译,但“aiocache”本身是一个专有名词或特定项目名称,直接翻译可能无法完全传达其原意,因此保留原样) - 简化Redis缓存操作
- Redis - 用于超高速缓存
