AliQambari/mcp-compose
If you are the rightful owner of mcp-compose and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
The Modular MCP Composition Architecture is a production-ready server framework designed to unify multiple MCP servers into a single endpoint, enhancing performance, reliability, and developer experience.
๐ Modular MCP Composition Architecture
A production-ready MCP server composition - compose multiple MCP servers into one unified endpoint
๐ Quick Start โข ๐ Documentation โข ๐ฏ Features โข ๐ง Configuration
๐ฏ Features
๐ Performance | ๐ก๏ธ Reliability | ๐ง Developer Experience |
---|---|---|
Redis Caching | Connection Pooling | Type Safety |
Async Operations | Error Handling | Clean Architecture |
Sub-ms Response | Graceful Failures | Comprehensive Logging |
โก Lightning Fast
- Redis Caching: 100x faster responses after first query
- Connection Pooling: Efficient database connection management
- Async/Await: Non-blocking operations for maximum throughput
๐๏ธ Production Ready
- Modular Architecture: Clean separation of concerns
- Type Safety: Comprehensive type hints prevent runtime errors
- Error Handling: Structured exception hierarchy with user-friendly messages
- Observability: Detailed logging with cache hit/miss tracking
๐ Modular Composition Architecture
- Server Composition: Combine multiple MCP servers into one endpoint
- Pluggable Services: Database, Math, and custom service modules
- Dynamic Loading: Enable/disable servers via configuration
- Tag-based Filtering: Fine-grained control over tool availability
- Extensible Framework: Add new MCP servers without touching core code
๐ Quick Start
1๏ธโฃ Installation
# 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๏ธโฃ Configuration
Create your .env
file:
# 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 the Server
# Start Redis server
redis-server
# Start the composed MCP server
python main.py
4๏ธโฃ Test with Client
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())
๐ Performance Comparison
Operation | Without Cache | With Redis Cache | Improvement |
---|---|---|---|
First Call | ~500ms | ~500ms | - |
Subsequent Calls | ~500ms | ~5ms | 100x faster ๐ |
Database Load | High | Minimal | 95% reduction |
๐๏ธ Architecture Overview
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
๐จ Design Patterns Used
- ๐ Composition Pattern: Multiple MCP servers composed into unified interface
- ๐ญ Factory Pattern: Database client creation without exposing instantiation logic
- ๐ Repository Pattern: Abstract database operations through consistent interfaces
- ๐ Dependency Injection: Services receive dependencies through constructors
- ๐ฏ Single Responsibility: Each server/service has one clear purpose
- ๐ Strategy Pattern: Different implementations with same interface
- ๐๏ธ Builder Pattern: Dynamic server composition based on configuration
๐ง Configuration
๐ Project Structure
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
โ๏ธ Environment Variables
Variable | Default | Description |
---|---|---|
POSTGRES_HOST | localhost | PostgreSQL server host |
POSTGRES_PORT | 5432 | PostgreSQL server port |
POSTGRES_USER | postgres | PostgreSQL username |
POSTGRES_PASSWORD | - | PostgreSQL password |
MYSQL_HOST | localhost | MySQL server host |
MYSQL_PORT | 3306 | MySQL server port |
REDIS_HOST | localhost | Redis server host |
REDIS_PORT | 6379 | Redis server port |
LOG_LEVEL | INFO | Logging level (DEBUG, INFO, WARNING, ERROR) |
SAVE_FILES | false | Enable/disable file output |
ENABLED_SERVERS | database,math | Comma-separated list of servers to enable |
SERVER_INCLUDE_TAGS | - | Only include tools with these tags |
SERVER_EXCLUDE_TAGS | admin | Exclude tools with these tags |
๐ ๏ธ Available Tools
๐ Database Tools
list_tables
List all tables in a database with caching support.
Parameters:
db_type
(string): Database type - "mysql" or "postgres"db_name
(string): Name of the database
Example:
result = await client.call_tool("list_tables", {
"db_type": "postgres",
"db_name": "my_database"
})
๐งฎ Math Tools
add
Add two numbers with caching support.
Parameters:
a
(float): First numberb
(float): Second number
Example:
result = await client.call_tool("add", {
"a": 5.5,
"b": 3.2
})
๐ Monitoring & Logging
๐ Cache Monitoring
The server provides detailed logging for cache operations:
# 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
๐ Performance Metrics
Monitor your server performance:
- Cache Hit Rate: Track how often cache is used vs database queries
- Response Times: Monitor query execution times
- Connection Pool: Database connection utilization
- Error Rates: Track and alert on failures
๐ Extending the Architecture
๐ Adding New MCP Servers
- Create your server in
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
- Add to
servers/__init__.py
:
from .my_server import create_my_server
__all__ = [..., "create_my_server"]
- Update
main.py
:
if "my_service" in enabled_servers:
await main_server.import_server(create_my_server())
๐ ๏ธ Configuration-Driven Composition
# Enable only specific servers
ENABLED_SERVERS=database,math,my_service
# Filter by tags
SERVER_INCLUDE_TAGS=production
SERVER_EXCLUDE_TAGS=admin,debug
check EXTENDING.md for detailed examples
๐ฏ Adding Caching to Any Method
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 Support
๐ฆ 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
postgres: image: postgres:15 environment: POSTGRES_DB: mydb POSTGRES_USER: user POSTGRES_PASSWORD: password
redis: image: redis:7-alpine ports: - "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
๐งช Testing
Use the included test client to verify functionality:
# Test the composed server with all tools
python test_client.py
# Test specific server composition
ENABLED_SERVERS=math python test_client.py
๐ค Contributing
We welcome contributions! Here's how to get started:
๐ Contribution Guidelines
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
๐ Acknowledgments
- FastMCP - For the excellent MCP framework
- aiomysql & asyncpg - For async database drivers
- aiocache - For Redis caching made simple
- Redis - For blazing-fast caching