A Model Context Protocol (MCP) server that enables secure interaction with MySQL/MariaDB/TiDB/AWS OceanBase/RDS/Aurora MySQL DataBases.
Project description
Multi-Database MCP Client
A Model Context Protocol (MCP) server that enables secure interaction with multiple database types including MySQL, MariaDB, TiDB, OceanBase, and AWS RDS/Aurora MySQL. This server exposes database operations as MCP tools and resources while proxying actual SQL execution to a remote HTTP service.
๐ Features
- Universal SQL Execution: Execute any SQL statement (SELECT, INSERT, UPDATE, DELETE, DDL) through a single tool
- Multi-Database Support: Works with MySQL, MariaDB, TiDB, OceanBase, and compatible cloud databases
- HTTP Proxy Architecture: Decouples MCP interface from database connections via HTTP forwarding
- Schema Introspection: Get table structures and database metadata as MCP resources
- Test Data Generation: Built-in tool for generating development test data
- Flexible Configuration: Support for multiple database instances with runtime switching
- Async I/O: Full asynchronous operation using
aiohttp
andasyncio
- Structured Logging: Comprehensive logging with
loguru
to both stderr and rotating files
๐๏ธ Architecture
The system follows a proxy pattern where the MCP server acts as a client-side interface:
MCP Client โ FastMCP Tools/Resources โ HTTP POST โ Remote DB Server โ Database
Key Components
src/server.py
: MCP server with FastMCP framework, tool/resource definitionssrc/utils/db_operate.py
: HTTP-proxied SQL execution enginesrc/utils/db_config.py
: Singleton configuration loader with multi-instance supportsrc/resources/db_resources.py
: Database metadata and configuration resource builderssrc/tools/db_tool.py
: Test data generation utilitiessrc/utils/http_util.py
: Async HTTP client helperssrc/utils/logger_util.py
: Logging setup and configuration path resolution
๐ Requirements
- Python 3.12+
- A remote database server accessible via the configured
multiDBServer
endpoint
๐ง Installation
# Clone the repository
git clone https://github.com/j00131120/mcp_database_server.git
cd mcp_database_server/multidb_mcp_client
# Create virtual environment
python3.12 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -U pip
pip install -e .
โ๏ธ Configuration
Configuration File
The server reads configuration from dbconfig.json
(default) or a custom path via the config_file
environment variable:
export config_file="/absolute/path/to/your/dbconfig.json"
Example Configuration
{
"dbType-Comment": "Supported types: mysql, xesql, ubisql, rasesql, oceanbase, tidb",
"dbList": [
{
"dbInstanceId": "primary_oceanbase",
"dbHost": "localhost",
"dbPort": 2281,
"dbDatabase": "production_db",
"dbUsername": "app_user",
"dbPassword": "secure_password",
"dbType": "OceanBase",
"dbVersion": "V4.0.0",
"dbActive": true
},
{
"dbInstanceId": "backup_mysql",
"dbHost": "backup.example.com",
"dbPort": 3306,
"dbDatabase": "backup_db",
"dbUsername": "backup_user",
"dbPassword": "backup_password",
"dbType": "MySQL",
"dbVersion": "8.0",
"dbActive": false
}
],
"multiDBServer": "http://127.0.0.1:8080/mcp/executeQuery",
"logPath": "/var/log/mcp-client",
"logLevel": "INFO"
}
Configuration Properties
dbList
: Array of database instance configurationsdbActive
: Exactly one instance must betrue
(the active database)dbType
: Supported values include MySQL, OceanBase, TiDB, etc.
multiDBServer
: HTTP endpoint that accepts SQL execution requestslogPath
: Directory for log files (auto-creates if missing)logLevel
: One of TRACE, DEBUG, INFO, WARNING, ERROR, CRITICAL
Remote Server Contract
The multiDBServer
endpoint must accept POST requests with this payload:
{
"sql": "SELECT * FROM users WHERE id = ?",
"params": [123],
"databaseInstance": {
"dbInstanceId": "primary_oceanbase",
"dbHost": "localhost",
"dbPort": 2281,
"dbDatabase": "production_db",
"dbUsername": "app_user",
"dbPassword": "secure_password",
"dbType": "OceanBase",
"dbActive": true
}
}
And return responses like:
{
"result": [
{"id": 123, "name": "John Doe", "email": "john@example.com"}
]
}
๐ Running the Server
Command Line
After installation, use the provided CLI command:
multidb-mcp-client
This starts the MCP server over stdio for consumption by MCP-compatible clients.
FastMCP CLI (Alternative)
# List available MCP servers
fastmcp servers list
# Run via entry point (defined in pyproject.toml)
fastmcp run mysql
Environment Variables
config_file
: Override default config file path- Standard logging environment variables supported by
loguru
๐ ๏ธ MCP Tools
sql_exec(sql: str)
Execute any SQL statement with automatic transaction handling.
Parameters:
sql
(string): SQL statement to execute
Returns:
{
"success": true,
"result": [...], // Query results or affected row count
"message": "SQL executed successfully"
}
Usage Examples:
# Query data
await sql_exec("SELECT * FROM users WHERE age > 18")
# Insert data
await sql_exec("INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')")
# Update records
await sql_exec("UPDATE users SET email = 'newemail@example.com' WHERE id = 1")
# DDL operations
await sql_exec("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(100))")
describe_table(table_name: str)
Get detailed table structure information.
Parameters:
table_name
(string): Name of the table (supportsdatabase.table
format)
Returns:
Same format as sql_exec
, with result
containing column metadata.
Usage Examples:
await describe_table("users")
await describe_table("inventory.products")
generate_demo_data(table_name: str, columns_name: List[str], num: int)
Generate test data for development and testing.
Parameters:
table_name
(string): Target table namecolumns_name
(array): List of column names to populatenum
(integer): Number of test records to generate
Usage Examples:
# Generate 100 test users
await generate_demo_data("users", ["name", "email", "phone"], 100)
# Generate 50 test products
await generate_demo_data("products", ["product_name", "category", "description"], 50)
๐ MCP Resources
database://tables
Provides comprehensive metadata for all database tables.
Returns:
{
"uri": "database://tables",
"mimeType": "application/json",
"text": "[{\"name\": \"users\", \"columns\": [...], \"record_count\": 1250}, ...]"
}
Use Cases:
- Schema exploration and documentation
- Database monitoring and statistics
- Query planning and optimization
database://config
Provides current database configuration (with sensitive data masked).
Returns:
{
"uri": "database://config",
"mimeType": "application/json",
"text": "{\"dbInstanceId\": \"primary_oceanbase\", \"dbHost\": \"localhost\", \"dbPassword\": \"***hidden***\", ...}"
}
๐ Logging
The system provides comprehensive logging:
- Console Output: Logs to stderr for MCP client visibility
- File Logging: Rotating log files (10MB max, 7-day retention)
- Structured Format: Timestamp, level, function, line number, and message
- Configurable Levels: TRACE through CRITICAL
Log files are stored in:
- Configured
logPath
directory - Default:
<project_root>/logs/mcp_server.log
๐ Security Considerations
Current Security Features
- Password Masking: Sensitive data hidden in resource responses
- HTTP Client: Supports custom headers for authentication
- Configuration Isolation: Only active database config exposed
Security Recommendations
- Credential Management: Store database passwords in environment variables or secure vaults
- Network Security: Use HTTPS for
multiDBServer
endpoint with proper authentication - Access Control: Restrict
sql_exec
tool usage to trusted environments - File Permissions: Secure
dbconfig.json
with appropriate file system permissions - Network Isolation: Deploy
multiDBServer
in a secured network segment
Production Deployment
# Use environment variables for sensitive data
export DB_PASSWORD="your_secure_password"
export MULTIDB_SERVER_URL="https://secure-db-proxy.internal.com/api/v1/execute"
# Restrict config file permissions
chmod 600 dbconfig.json
# Run with non-root user
useradd -r mcp-client
sudo -u mcp-client multidb-mcp-client
๐งช Development
Project Structure
multidb_mcp_client/
โโโ src/
โ โโโ server.py # MCP server and tool definitions
โ โโโ resources/
โ โ โโโ db_resources.py # Resource data builders
โ โโโ tools/
โ โ โโโ db_tool.py # Tool implementations
โ โโโ utils/
โ โโโ db_config.py # Configuration management
โ โโโ db_operate.py # SQL execution via HTTP
โ โโโ http_util.py # HTTP client utilities
โ โโโ logger_util.py # Logging configuration
โโโ dbconfig.json # Database configuration
โโโ pyproject.toml # Project metadata and dependencies
โโโ logs/ # Log output directory
Code Style
- Explicit naming: Clear, descriptive function and variable names
- Early returns: Reduce nesting with guard clauses
- Type annotations: Public APIs include type hints
- Error handling: Comprehensive exception handling with logging
- Async/await: Proper async patterns throughout
Key Dependencies
fastmcp
: MCP framework and protocol implementationaiohttp
: Async HTTP client for database proxy callsloguru
: Structured logging with rotation and formattingmcp[cli]
: MCP command-line tools
๐ License
MIT License - see the LICENSE file for details.
๐ Links
- Homepage: https://github.com/j00131120/mcp_database_server/tree/main/multidb_mcp_client
- Documentation: https://github.com/j00131120/mcp_database_server/blob/main/multidb_mcp_client/README.md
- Source Code: https://github.com/j00131120/mcp_database_server.git
- Issue Tracker: https://github.com/j00131120/mcp_database_server/issues
- Changelog: https://github.com/j00131120/mcp_database_server/blob/main/multidb_mcp_client/CHANGELOG.md
๐ค Contributing
- 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
๐ Support
For questions, issues, or contributions:
- Author: Frank Jin (j00131120@163.com)
- GitHub Issues: Use the issue tracker for bug reports and feature requests
- Documentation: Check the repository wiki for additional documentation
Note: This MCP server requires a compatible remote database service running at the configured multiDBServer
endpoint. Ensure your remote service implements the expected HTTP API contract before running the client.
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
File details
Details for the file multidb_mcp_client-0.1.0.tar.gz
.
File metadata
- Download URL: multidb_mcp_client-0.1.0.tar.gz
- Upload date:
- Size: 14.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 |
e10c98bc4b4ec54cc5b7c1e0982292d82e8986a31b0b4a332b58cec2f270aa02
|
|
MD5 |
c935d695fd4e9862f055a6b081773e69
|
|
BLAKE2b-256 |
5d2a6833ebca8c4564a326233df356c7e8ab384e52b756f50530270e9eb4f680
|
File details
Details for the file multidb_mcp_client-0.1.0-py3-none-any.whl
.
File metadata
- Download URL: multidb_mcp_client-0.1.0-py3-none-any.whl
- Upload date:
- Size: 17.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 |
e5091679d94dbae456b542604a62e0a15ea7fa3550d7cb8252b57cb31b0f4933
|
|
MD5 |
e8ca76f8a8692283e8922d202bceac34
|
|
BLAKE2b-256 |
f728f7d9a6445d51fc5a67140eff98afd22d1a64da6c592891402fbc73eb12e9
|