# MySQL MCP Server
A Model Context Protocol (MCP) server that enables secure interaction with MySQL/MariaDB/TiDB/AWS OceanBase/RDS/Aurora MySQL databases.
## ๐ Features
- **MCP Protocol Support**: Built on FastMCP framework with standard MCP tools and resources
- **Multi-Database Compatibility**: Support for MySQL, MariaDB, TiDB, OceanBase, AWS RDS, and Aurora MySQL
- **Asynchronous Architecture**: Built with `aiomysql` for high-performance database operations
- **Connection Pooling**: Efficient connection management with configurable pool settings
- **Security Features**: Query type restrictions, automatic LIMIT enforcement, and parameter validation
- **Comprehensive Tools**: SQL execution, table structure queries, and test data generation
## ๐ Prerequisites
- Python >= 3.12
- MySQL/MariaDB/TiDB/OceanBase database instance
- Network access to database server
## ๐ ๏ธ Installation
### 1. Clone the repository
```bash
git clone <repository-url>
cd mysql_mcp_server
```
### 2. Install from PyPI (Recommended)
```bash
pip install mysql-server-mcp
```
### 3. Install from source
```bash
# Clone and install in development mode
git clone <repository-url>
cd mysql_mcp_server
pip install -e .
# Or install dependencies and run directly
pip install -r requirements.txt
```
### 3. Configure database connection
Edit `dbconfig.json` with your database credentials:
```json
{
"dbPoolSize": 5,
"dbMaxOverflow": 10,
"dbPoolTimeout": 30,
"dbList": [
{
"dbInstanceId": "mysql_main",
"dbHost": "localhost",
"dbPort": 3306,
"dbDatabase": "your_database",
"dbUsername": "your_username",
"dbPassword": "your_password",
"dbType": "MySQL",
"dbVersion": "8.0",
"dbActive": true
}
],
"logPath": "/path/to/logs",
"logLevel": "info"
}
```
### 4. Environment Variables (Optional)
```bash
export config_file="/path/to/custom/dbconfig.json"
```
## ๐ Quick Start
### Start the MCP Server
```bash
# Using the installed package
mysql-mcp-server
# Using fastmcp CLI
fastmcp run src/server.py
# Or directly with Python
python src/server.py
```
### Using with MCP Clients
The server provides the following MCP tools and resources:
#### Tools
- `sql_exec`: Execute any SQL statement
- `describe_table`: Get table structure information
- `execute_query_with_limit`: Execute SELECT queries with automatic LIMIT
- `generate_demo_data`: Generate test data for tables
#### Resources
- `database://tables`: Database table metadata
- `database://config`: Database configuration information
## ๐ API Reference
### SQL Execution Tool
```python
await sql_exec("SELECT * FROM users WHERE age > 18")
```
**Parameters:**
- `sql` (str): SQL statement to execute
**Returns:**
- `success` (bool): Execution status
- `result`: Query results or affected rows
- `message` (str): Status description
### Table Structure Tool
```python
await describe_table("users")
```
**Parameters:**
- `table_name` (str): Table name (supports `database.table` format)
**Returns:**
- Table structure information including columns, types, and constraints
### Limited Query Tool
```python
await execute_query_with_limit("SELECT * FROM users", 100)
```
**Parameters:**
- `sql` (str): SELECT query statement
- `limit` (int): Maximum rows to return (1-10000)
**Security Features:**
- Only SELECT queries allowed
- Automatic LIMIT enforcement
- Parameter validation
### Test Data Generation
```python
await generate_demo_data("users", ["name", "email"], 50)
```
**Parameters:**
- `table_name` (str): Target table name
- `columns_name` (List[str]): Column names to populate
- `num` (int): Number of test records to generate
## โ๏ธ Configuration
### Database Configuration
The `dbconfig.json` file supports multiple database instances:
```json
{
"dbPoolSize": 5, // Minimum connection pool size
"dbMaxOverflow": 10, // Maximum overflow connections
"dbPoolTimeout": 30, // Connection timeout in seconds
"dbList": [
{
"dbInstanceId": "unique_id",
"dbHost": "hostname",
"dbPort": 3306,
"dbDatabase": "database_name",
"dbUsername": "username",
"dbPassword": "password",
"dbType": "MySQL",
"dbVersion": "8.0",
"dbActive": true // Only one instance should be active
}
],
"logPath": "/path/to/logs",
"logLevel": "info"
}
```
### Logging Configuration
- **Log Levels**: TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL
- **Log Rotation**: 10 MB per file, 7 days retention
- **Output**: Both stderr (for MCP) and file logging
## ๐ Security Features
### Query Restrictions
- **Read-only Queries**: `execute_query_with_limit` only allows SELECT statements
- **Automatic LIMIT**: Prevents excessive data retrieval (max 10,000 rows)
- **Parameter Validation**: Input validation for all parameters
### Configuration Security
- **Password Hiding**: Sensitive information is masked in responses
- **Instance Isolation**: Only active database configuration is exposed
- **Environment Override**: Secure configuration file path management
## ๐๏ธ Architecture
### Project Structure
```
src/
โโโ server.py # MCP server main entry point
โโโ utils/ # Utility modules
โ โโโ db_config.py # Database configuration management
โ โโโ db_pool.py # Connection pool management
โ โโโ db_operate.py # Database operations
โ โโโ logger_util.py # Logging management
โ โโโ __init__.py # Module initialization
โโโ resources/ # MCP resources
โ โโโ db_resources.py # Database resources
โโโ tools/ # MCP tools
โโโ db_tool.py # Database tools
```
### Key Components
#### Database Connection Pool
- **Singleton Pattern**: Ensures single pool instance
- **Async Management**: Non-blocking connection handling
- **Automatic Cleanup**: Connection release and pool management
#### Configuration Management
- **JSON-based**: Human-readable configuration format
- **Environment Override**: Flexible configuration management
- **Validation**: Required field validation and error handling
#### Logging System
- **Unified Interface**: Single logger instance across modules
- **Configurable Output**: File and console logging
- **Structured Format**: Timestamp, level, module, function, and line information
## ๐งช Testing
### Generate Test Data
```python
# Generate 100 test records for users table
await generate_demo_data("users", ["name", "email", "phone"], 100)
```
### Test Database Connection
```python
# Test basic SQL execution
result = await sql_exec("SELECT 1 as test")
print(result) # {'success': True, 'result': [{'test': 1}]}
```
## ๐ Monitoring
### Database Status
```python
# Get database configuration
config = await get_database_config()
print(f"Database: {config['dbType']} {config['dbVersion']}")
# Get table information
tables = await get_database_tables()
print(f"Total tables: {len(tables)}")
```
### Connection Pool Status
- Pool size and overflow configuration
- Connection timeout settings
- Active connection count
## ๐จ Troubleshooting
### Common Issues
#### Connection Errors
```bash
# Check database connectivity
mysql -h localhost -P 3306 -u username -p database_name
# Verify configuration
python -c "from src.utils.db_config import load_db_config; print(load_db_config())"
```
#### Permission Issues
- Ensure database user has necessary privileges
- Check firewall and network access
- Verify database server is running
#### Configuration Errors
- Validate JSON syntax in `dbconfig.json`
- Check file permissions
- Verify environment variables
### Debug Mode
Set log level to DEBUG in configuration:
```json
{
"logLevel": "debug"
}
```
## ๐ค Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request
### Development Setup
```bash
# Install in development mode with all dependencies
pip install -e ".[dev,test,docs]"
# Run with debug logging
export LOG_LEVEL=debug
python src/server.py
```
### Code Quality Tools
```bash
# Format code
black src/
isort src/
# Lint code
flake8 src/
mypy src/
# Run tests
pytest
# Run tests with coverage
pytest --cov=src --cov-report=html
# Pre-commit hooks
pre-commit install
pre-commit run --all-files
```
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ฅ Authors
- **Frank Jin** - *Initial work* - [j00131120@163.com](mailto:j00131120@163.com)
## ๐ Acknowledgments
- [FastMCP](https://github.com/fastmcp/fastmcp) - MCP framework
- [aiomysql](https://github.com/aio-libs/aiomysql) - Async MySQL driver
- [loguru](https://github.com/Delgan/loguru) - Logging library
## ๐ Support
For support and questions:
- Create an issue in the repository
- Contact: [j00131120@163.com](mailto:j00131120@163.com)
## ๐ Changelog
### v1.0.0
- Initial release
- MCP protocol support
- Multi-database compatibility
- Async connection pooling
- Security features implementation
## ๐ฆ Building and Distribution
### Build the Package
```bash
# Clean and build
python build.py build
# Build and check
python build.py check
# Build and test installation
python build.py test
# Complete build process
python build.py all
```
### Publish to PyPI
```bash
# Build, test, and publish
python build.py publish
# Or manually
python -m build
python -m twine check dist/*
python -m twine upload dist/*
```
### Package Information
- **Package Name**: `mysql-server-mcp`
- **Entry Point**: `mysql-mcp-server`
- **MCP Server Entry Point**: `mysql`
- **Python Version**: >= 3.12
- **License**: MIT
Raw data
{
"_id": null,
"home_page": null,
"name": "mysql-server-mcp",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.12",
"maintainer_email": "Frank Jin <j00131120@163.com>",
"keywords": "mcp, mysql, tidb, oceanbase, model-context-protocol, async, connection-pool",
"author": null,
"author_email": "Frank Jin <j00131120@163.com>",
"download_url": "https://files.pythonhosted.org/packages/ab/8c/6798da3fe3941ec141a2f38ed9fe0250609aa7b3d143ef084c28659682af/mysql_server_mcp-1.0.0.tar.gz",
"platform": null,
"description": "# MySQL MCP Server\n\nA Model Context Protocol (MCP) server that enables secure interaction with MySQL/MariaDB/TiDB/AWS OceanBase/RDS/Aurora MySQL databases.\n\n## \ud83d\ude80 Features\n\n- **MCP Protocol Support**: Built on FastMCP framework with standard MCP tools and resources\n- **Multi-Database Compatibility**: Support for MySQL, MariaDB, TiDB, OceanBase, AWS RDS, and Aurora MySQL\n- **Asynchronous Architecture**: Built with `aiomysql` for high-performance database operations\n- **Connection Pooling**: Efficient connection management with configurable pool settings\n- **Security Features**: Query type restrictions, automatic LIMIT enforcement, and parameter validation\n- **Comprehensive Tools**: SQL execution, table structure queries, and test data generation\n\n## \ud83d\udccb Prerequisites\n\n- Python >= 3.12\n- MySQL/MariaDB/TiDB/OceanBase database instance\n- Network access to database server\n\n## \ud83d\udee0\ufe0f Installation\n\n### 1. Clone the repository\n```bash\ngit clone <repository-url>\ncd mysql_mcp_server\n```\n\n### 2. Install from PyPI (Recommended)\n```bash\npip install mysql-server-mcp\n```\n\n### 3. Install from source\n```bash\n# Clone and install in development mode\ngit clone <repository-url>\ncd mysql_mcp_server\npip install -e .\n\n# Or install dependencies and run directly\npip install -r requirements.txt\n```\n\n### 3. Configure database connection\nEdit `dbconfig.json` with your database credentials:\n\n```json\n{\n \"dbPoolSize\": 5,\n \"dbMaxOverflow\": 10,\n \"dbPoolTimeout\": 30,\n \"dbList\": [\n {\n \"dbInstanceId\": \"mysql_main\",\n \"dbHost\": \"localhost\",\n \"dbPort\": 3306,\n \"dbDatabase\": \"your_database\",\n \"dbUsername\": \"your_username\",\n \"dbPassword\": \"your_password\",\n \"dbType\": \"MySQL\",\n \"dbVersion\": \"8.0\",\n \"dbActive\": true\n }\n ],\n \"logPath\": \"/path/to/logs\",\n \"logLevel\": \"info\"\n}\n```\n\n### 4. Environment Variables (Optional)\n```bash\nexport config_file=\"/path/to/custom/dbconfig.json\"\n```\n\n## \ud83d\ude80 Quick Start\n\n### Start the MCP Server\n```bash\n# Using the installed package\nmysql-mcp-server\n\n# Using fastmcp CLI\nfastmcp run src/server.py\n\n# Or directly with Python\npython src/server.py\n```\n\n### Using with MCP Clients\nThe server provides the following MCP tools and resources:\n\n#### Tools\n- `sql_exec`: Execute any SQL statement\n- `describe_table`: Get table structure information\n- `execute_query_with_limit`: Execute SELECT queries with automatic LIMIT\n- `generate_demo_data`: Generate test data for tables\n\n#### Resources\n- `database://tables`: Database table metadata\n- `database://config`: Database configuration information\n\n## \ud83d\udcda API Reference\n\n### SQL Execution Tool\n```python\nawait sql_exec(\"SELECT * FROM users WHERE age > 18\")\n```\n\n**Parameters:**\n- `sql` (str): SQL statement to execute\n\n**Returns:**\n- `success` (bool): Execution status\n- `result`: Query results or affected rows\n- `message` (str): Status description\n\n### Table Structure Tool\n```python\nawait describe_table(\"users\")\n```\n\n**Parameters:**\n- `table_name` (str): Table name (supports `database.table` format)\n\n**Returns:**\n- Table structure information including columns, types, and constraints\n\n### Limited Query Tool\n```python\nawait execute_query_with_limit(\"SELECT * FROM users\", 100)\n```\n\n**Parameters:**\n- `sql` (str): SELECT query statement\n- `limit` (int): Maximum rows to return (1-10000)\n\n**Security Features:**\n- Only SELECT queries allowed\n- Automatic LIMIT enforcement\n- Parameter validation\n\n### Test Data Generation\n```python\nawait generate_demo_data(\"users\", [\"name\", \"email\"], 50)\n```\n\n**Parameters:**\n- `table_name` (str): Target table name\n- `columns_name` (List[str]): Column names to populate\n- `num` (int): Number of test records to generate\n\n## \u2699\ufe0f Configuration\n\n### Database Configuration\nThe `dbconfig.json` file supports multiple database instances:\n\n```json\n{\n \"dbPoolSize\": 5, // Minimum connection pool size\n \"dbMaxOverflow\": 10, // Maximum overflow connections\n \"dbPoolTimeout\": 30, // Connection timeout in seconds\n \"dbList\": [\n {\n \"dbInstanceId\": \"unique_id\",\n \"dbHost\": \"hostname\",\n \"dbPort\": 3306,\n \"dbDatabase\": \"database_name\",\n \"dbUsername\": \"username\",\n \"dbPassword\": \"password\",\n \"dbType\": \"MySQL\",\n \"dbVersion\": \"8.0\",\n \"dbActive\": true // Only one instance should be active\n }\n ],\n \"logPath\": \"/path/to/logs\",\n \"logLevel\": \"info\"\n}\n```\n\n### Logging Configuration\n- **Log Levels**: TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL\n- **Log Rotation**: 10 MB per file, 7 days retention\n- **Output**: Both stderr (for MCP) and file logging\n\n## \ud83d\udd12 Security Features\n\n### Query Restrictions\n- **Read-only Queries**: `execute_query_with_limit` only allows SELECT statements\n- **Automatic LIMIT**: Prevents excessive data retrieval (max 10,000 rows)\n- **Parameter Validation**: Input validation for all parameters\n\n### Configuration Security\n- **Password Hiding**: Sensitive information is masked in responses\n- **Instance Isolation**: Only active database configuration is exposed\n- **Environment Override**: Secure configuration file path management\n\n## \ud83c\udfd7\ufe0f Architecture\n\n### Project Structure\n```\nsrc/\n\u251c\u2500\u2500 server.py # MCP server main entry point\n\u251c\u2500\u2500 utils/ # Utility modules\n\u2502 \u251c\u2500\u2500 db_config.py # Database configuration management\n\u2502 \u251c\u2500\u2500 db_pool.py # Connection pool management\n\u2502 \u251c\u2500\u2500 db_operate.py # Database operations\n\u2502 \u251c\u2500\u2500 logger_util.py # Logging management\n\u2502 \u2514\u2500\u2500 __init__.py # Module initialization\n\u251c\u2500\u2500 resources/ # MCP resources\n\u2502 \u2514\u2500\u2500 db_resources.py # Database resources\n\u2514\u2500\u2500 tools/ # MCP tools\n \u2514\u2500\u2500 db_tool.py # Database tools\n```\n\n### Key Components\n\n#### Database Connection Pool\n- **Singleton Pattern**: Ensures single pool instance\n- **Async Management**: Non-blocking connection handling\n- **Automatic Cleanup**: Connection release and pool management\n\n#### Configuration Management\n- **JSON-based**: Human-readable configuration format\n- **Environment Override**: Flexible configuration management\n- **Validation**: Required field validation and error handling\n\n#### Logging System\n- **Unified Interface**: Single logger instance across modules\n- **Configurable Output**: File and console logging\n- **Structured Format**: Timestamp, level, module, function, and line information\n\n## \ud83e\uddea Testing\n\n### Generate Test Data\n```python\n# Generate 100 test records for users table\nawait generate_demo_data(\"users\", [\"name\", \"email\", \"phone\"], 100)\n```\n\n### Test Database Connection\n```python\n# Test basic SQL execution\nresult = await sql_exec(\"SELECT 1 as test\")\nprint(result) # {'success': True, 'result': [{'test': 1}]}\n```\n\n## \ud83d\udcca Monitoring\n\n### Database Status\n```python\n# Get database configuration\nconfig = await get_database_config()\nprint(f\"Database: {config['dbType']} {config['dbVersion']}\")\n\n# Get table information\ntables = await get_database_tables()\nprint(f\"Total tables: {len(tables)}\")\n```\n\n### Connection Pool Status\n- Pool size and overflow configuration\n- Connection timeout settings\n- Active connection count\n\n## \ud83d\udea8 Troubleshooting\n\n### Common Issues\n\n#### Connection Errors\n```bash\n# Check database connectivity\nmysql -h localhost -P 3306 -u username -p database_name\n\n# Verify configuration\npython -c \"from src.utils.db_config import load_db_config; print(load_db_config())\"\n```\n\n#### Permission Issues\n- Ensure database user has necessary privileges\n- Check firewall and network access\n- Verify database server is running\n\n#### Configuration Errors\n- Validate JSON syntax in `dbconfig.json`\n- Check file permissions\n- Verify environment variables\n\n### Debug Mode\nSet log level to DEBUG in configuration:\n```json\n{\n \"logLevel\": \"debug\"\n}\n```\n\n## \ud83e\udd1d Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Add tests if applicable\n5. Submit a pull request\n\n### Development Setup\n```bash\n# Install in development mode with all dependencies\npip install -e \".[dev,test,docs]\"\n\n# Run with debug logging\nexport LOG_LEVEL=debug\npython src/server.py\n```\n\n### Code Quality Tools\n```bash\n# Format code\nblack src/\nisort src/\n\n# Lint code\nflake8 src/\nmypy src/\n\n# Run tests\npytest\n\n# Run tests with coverage\npytest --cov=src --cov-report=html\n\n# Pre-commit hooks\npre-commit install\npre-commit run --all-files\n```\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## \ud83d\udc65 Authors\n\n- **Frank Jin** - *Initial work* - [j00131120@163.com](mailto:j00131120@163.com)\n\n## \ud83d\ude4f Acknowledgments\n\n- [FastMCP](https://github.com/fastmcp/fastmcp) - MCP framework\n- [aiomysql](https://github.com/aio-libs/aiomysql) - Async MySQL driver\n- [loguru](https://github.com/Delgan/loguru) - Logging library\n\n## \ud83d\udcde Support\n\nFor support and questions:\n- Create an issue in the repository\n- Contact: [j00131120@163.com](mailto:j00131120@163.com)\n\n## \ud83d\udd04 Changelog\n\n### v1.0.0\n- Initial release\n- MCP protocol support\n- Multi-database compatibility\n- Async connection pooling\n- Security features implementation\n\n## \ud83d\udce6 Building and Distribution\n\n### Build the Package\n```bash\n# Clean and build\npython build.py build\n\n# Build and check\npython build.py check\n\n# Build and test installation\npython build.py test\n\n# Complete build process\npython build.py all\n```\n\n### Publish to PyPI\n```bash\n# Build, test, and publish\npython build.py publish\n\n# Or manually\npython -m build\npython -m twine check dist/*\npython -m twine upload dist/*\n```\n\n### Package Information\n- **Package Name**: `mysql-server-mcp`\n- **Entry Point**: `mysql-mcp-server`\n- **MCP Server Entry Point**: `mysql`\n- **Python Version**: >= 3.12\n- **License**: MIT\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A Model Context Protocol (MCP) server that enables secure interaction with MySQL/MariaDB/TiDB/AWS OceanBase/RDS/Aurora MySQL DataBases.",
"version": "1.0.0",
"project_urls": {
"Bug Tracker": "https://github.com/j00131120/mcp_database_server/issues",
"Changelog": "https://github.com/j00131120/mcp_database_server/blob/main/mysql_mcp_server/README.md",
"Documentation": "https://github.com/j00131120/mcp_database_server/blob/main/mysql_mcp_server/README.md",
"Download": "https://github.com/j00131120/mcp_database_server/tree/main/mysql_mcp_server",
"Homepage": "https://github.com/j00131120/mcp_database_server/tree/main/mysql_mcp_server",
"Repository": "https://github.com/j00131120/mcp_database_server.git",
"Source Code": "https://github.com/j00131120/mcp_database_server/tree/main/mysql_mcp_server"
},
"split_keywords": [
"mcp",
" mysql",
" tidb",
" oceanbase",
" model-context-protocol",
" async",
" connection-pool"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "aa80baaeecb7e89d79639dafa5cfa459b1c88c91e0f248ce1d5d0838285867bb",
"md5": "6a34bfaf5da94efff2a372cb7d35bc83",
"sha256": "b318bb327c429c6db8b7599341555ca5351004d24d1e654f1e078b9706298d02"
},
"downloads": -1,
"filename": "mysql_server_mcp-1.0.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "6a34bfaf5da94efff2a372cb7d35bc83",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.12",
"size": 19000,
"upload_time": "2025-08-16T16:20:05",
"upload_time_iso_8601": "2025-08-16T16:20:05.856462Z",
"url": "https://files.pythonhosted.org/packages/aa/80/baaeecb7e89d79639dafa5cfa459b1c88c91e0f248ce1d5d0838285867bb/mysql_server_mcp-1.0.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "ab8c6798da3fe3941ec141a2f38ed9fe0250609aa7b3d143ef084c28659682af",
"md5": "bed4bfae4efd001f6b8be675cda5af97",
"sha256": "e8d92947e4c80c05336100fdb8fdc113db0c1c364a81c57b605623cca146f960"
},
"downloads": -1,
"filename": "mysql_server_mcp-1.0.0.tar.gz",
"has_sig": false,
"md5_digest": "bed4bfae4efd001f6b8be675cda5af97",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.12",
"size": 16702,
"upload_time": "2025-08-16T16:20:07",
"upload_time_iso_8601": "2025-08-16T16:20:07.548340Z",
"url": "https://files.pythonhosted.org/packages/ab/8c/6798da3fe3941ec141a2f38ed9fe0250609aa7b3d143ef084c28659682af/mysql_server_mcp-1.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-16 16:20:07",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "j00131120",
"github_project": "mcp_database_server",
"github_not_found": true,
"lcname": "mysql-server-mcp"
}