hightower9/mysql-mcp-server
If you are the rightful owner of mysql-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
A production-grade Model Context Protocol (MCP) server for MySQL database interactions, enabling AI assistants to safely and efficiently interact with MySQL databases.
MySQL MCP Server
A production-grade Model Context Protocol (MCP) server for MySQL database interactions. This server enables AI assistants like Claude to safely and efficiently interact with MySQL databases through the MCP protocol.
Features
✨ Production Ready
- Connection pooling with configurable settings
- Comprehensive error handling and logging
- SQL injection prevention and query validation
- Configurable security controls (read-only, write, DDL)
🔒 Security First
- Query validation and sanitization
- Parameterized queries
- Configurable operation restrictions
- Maximum result set limits
- Query timeout enforcement
🛠️ MCP Capabilities
- Tools: Execute queries, list tables, describe schemas, search tables, database statistics
- Resources: Access database schemas, table structures, and data previews
- Prompts: Guided table analysis, query generation, optimization, and migration planning
Installation
Prerequisites
- Python 3.10 or higher
- MySQL 5.7 or higher (or MariaDB 10.2+)
- pip or uv package manager
Setup
- Clone the repository:
git clone <repository-url>
cd mysql-mcp-server
- Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install dependencies:
pip install -e .
# Or for development:
pip install -e ".[dev]"
- Configure environment variables:
cp .env.example .env
# Edit .env with your MySQL credentials
Configuration
Edit the .env file with your settings:
# Required
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=your_username
MYSQL_PASSWORD=your_password
MYSQL_DATABASE=your_database
# Optional Security Settings
ENABLE_READ_ONLY=false
ENABLE_WRITE_OPERATIONS=true
ENABLE_DDL_OPERATIONS=false
MAX_QUERY_RESULTS=1000
QUERY_TIMEOUT=30
Security Configuration
ENABLE_READ_ONLY: Restrict to SELECT queries onlyENABLE_WRITE_OPERATIONS: Allow INSERT, UPDATE, DELETE operationsENABLE_DDL_OPERATIONS: Allow CREATE, ALTER, DROP, TRUNCATE operationsMAX_QUERY_RESULTS: Maximum rows returned per queryQUERY_TIMEOUT: Maximum query execution time in seconds
Usage
Starting the Server
# Using the installed command
mysql-mcp-server
# Or directly with uv
uv run python -m server.main
# Or directly with Python
python -m server.main
Using with Claude Desktop
Add to your Claude Desktop configuration file:
MacOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"mysql": {
"command": "uv",
"args": ["run", "python", "-m", "server.main"],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "your_username",
"MYSQL_PASSWORD": "your_password",
"MYSQL_DATABASE": "your_database"
}
}
}
}
Available Tools
1. execute_query
Execute SQL queries on the database:
# SELECT query
execute_query("SELECT * FROM users WHERE age > 25 LIMIT 10")
# INSERT query
execute_query("INSERT INTO users (name, email) VALUES ('John', 'john@example.com')")
# UPDATE query
execute_query("UPDATE users SET status = 'active' WHERE id = 1")
2. list_tables
Get all tables in the database:
list_tables()
# Returns: {"success": true, "tables": ["users", "orders", "products"], "count": 3}
3. describe_table
Get detailed schema for a table:
describe_table("users")
# Returns full schema including columns, types, constraints, indexes
4. get_table_info
Get summary information about a table:
get_table_info("products")
# Returns: row count, column count, column names, primary key info
5. search_tables
Search for tables by name:
search_tables("user")
# Returns tables containing "user" in the name
6. get_database_stats
Get overall database statistics:
get_database_stats()
# Returns: table count, largest tables, configuration settings
Available Resources
Schema Resource
mysql://schema
Returns the complete database schema.
Table Schema Resource
mysql://tables/{table_name}
Returns schema for a specific table.
Table Preview Resource
mysql://tables/{table_name}/preview
Returns first 10 rows of a table.
Available Prompts
analyze_table
Generate analysis of a table structure and data.
generate_query
Create SQL queries from natural language descriptions.
optimize_query
Get optimization suggestions for SQL queries.
database_migration
Plan database schema migrations.
Project Structure
mysql-mcp-server/
├── server/
│ ├── __init__.py # Package initialization
│ ├── main.py # FastAPI application entry point
│ ├── config/
│ │ ├── __init__.py # Config package init
│ │ ├── settings.py # Configuration management
│ │ └── database.py # Database operations
│ ├── core/
│ │ ├── __init__.py # Core package init
│ │ ├── prompts.py # MCP prompt definitions
│ │ ├── resources.py # MCP resource definitions
│ │ └── tools.py # MCP tool definitions
│ └── utils/
│ ├── __init__.py # Utils package init
│ └── security.py # Security validation
├── .env.example # Example environment variables
├── .gitignore # Git ignore rules
├── pyproject.toml # Project metadata and dependencies
└── README.md # Project README
Security Best Practices
- Never commit
.envfile - Contains sensitive credentials - Use read-only mode for analysis tasks
- Disable DDL operations unless explicitly needed
- Set appropriate query timeouts to prevent long-running queries
- Limit max results to prevent memory issues
- Regular security audits of query logs
Troubleshooting
Connection Issues
Error: Failed to connect to database
- Verify MySQL is running
- Check host, port, username, password in .env
- Ensure database exists
- Check firewall settings
Permission Errors
Error: Access denied for user
- Grant appropriate MySQL privileges:
GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.* TO 'username'@'host';
FLUSH PRIVILEGES;
Query Validation Errors
Error: Dangerous keyword detected
- The security validator blocks potentially harmful operations
- Review
security.pyfor allowed operations - Adjust
ENABLE_DDL_OPERATIONSif needed
Performance Optimization
- Connection Pooling: Adjust
POOL_SIZEbased on load - Query Limits: Set
MAX_QUERY_RESULTSappropriately - Indexes: Ensure proper indexes on frequently queried columns
- Pool Recycling: Adjust
POOL_RECYCLEfor long-running servers
License
MIT License
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Support
For issues and questions:
- Create an issue on GitHub
- Check existing issues for solutions
- Review MCP documentation at https://modelcontextprotocol.io
Changelog
Version 1.0.0
- Initial production release
- Complete MCP implementation
- Security validation
- Connection pooling
- Comprehensive documentation