MySQL MCP Server
by ayush1184
README.md
# MySQL MCP Server
A comprehensive Model Context Protocol (MCP) server for MySQL databases with Langchain integration. This server provides 40+ tools for database operations, schema management, query optimization, and administration.
**Author:** [Ayush Singh](https://github.com/ayushsingh)
## Features
- **Comprehensive Tool Set**: 40+ tools covering all MySQL operations
- **Langchain Compatible**: Tools can be used with Langchain agents
- **Security First**: Built-in SQL injection prevention and access control
- **Performance Optimized**: Connection pooling, query caching, result streaming
- **Production Ready**: Error handling, logging, monitoring
- **Easy Integration**: Simple configuration for Claude Desktop, Claude Code, Cursor
- **Extensible**: Modular design for easy extension
## Installation
### Prerequisites
- Python 3.10 or higher
- MySQL 5.7 or higher (MySQL 8.0+ recommended)
- MySQL user with appropriate permissions
### Option 1: Docker (recommended for production)
Pull the image from Docker Hub and run with your `.env`:
```bash
docker pull ayush1184docker/mysql-mcp-server:latest
docker run --rm -i --env-file /path/to/your/.env ayush1184docker/mysql-mcp-server:latest
```
See [DOCKER.md](DOCKER.md) for build, push, and Cursor integration details.
### Option 2: Install from source
```bash
pip install -r requirements.txt
```
Or using pip:
```bash
pip install mcp aiomysql pymysql sqlalchemy langchain langchain-community pydantic python-dotenv
```
## Configuration
### Environment Variables
Create a `.env` file in the project root or set environment variables:
```bash
# MySQL Connection Settings
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=your_password
MYSQL_DATABASE=your_database
# Optional: Path to .env file (for per-project configurations)
# MYSQL_ENV_FILE=/path/to/custom/.env
# Connection Pool Settings
MYSQL_POOL_SIZE=10
MYSQL_MAX_CONNECTIONS=100
MYSQL_QUERY_TIMEOUT=30
# SSL/TLS Settings
MYSQL_SSL_ENABLED=false
MYSQL_SSL_CA=
MYSQL_SSL_CERT=
MYSQL_SSL_KEY=
# Security Settings
MYSQL_READ_ONLY=false
MYSQL_ALLOW_DDL=false
MYSQL_ALLOW_DELETE=false
MYSQL_RATE_LIMIT=100
# Logging Settings
MYSQL_LOG_QUERIES=false
MYSQL_LOG_LEVEL=INFO
```
### Configuration Reference
| Variable | Description | Default |
|----------|-------------|---------|
| `MYSQL_ENV_FILE` | Path to `.env` file (for per-project configs) | (none, loads from CWD) |
| `MYSQL_HOST` | MySQL server host | `127.0.0.1` |
| `MYSQL_PORT` | MySQL server port | `3306` |
| `MYSQL_USER` | MySQL username | `root` |
| `MYSQL_PASSWORD` | MySQL password | (empty) |
| `MYSQL_DATABASE` | Default database name | (none) |
| `MYSQL_CONNECTION_STRING` | Full connection string (alternative) | (none) |
| `MYSQL_POOL_SIZE` | Connection pool size | `10` |
| `MYSQL_MAX_CONNECTIONS` | Maximum connections | `100` |
| `MYSQL_QUERY_TIMEOUT` | Query timeout in seconds | `30` |
| `MYSQL_SSL_ENABLED` | Enable SSL/TLS | `false` |
| `MYSQL_READ_ONLY` | Read-only mode | `false` |
| `MYSQL_ALLOW_DDL` | Allow DDL operations | `false` |
| `MYSQL_ALLOW_DELETE` | Allow DELETE operations | `false` |
| `MYSQL_RATE_LIMIT` | Queries per minute | `100` |
| `MYSQL_LOG_QUERIES` | Log all queries | `false` |
| `MYSQL_LOG_LEVEL` | Logging level | `INFO` |
## Usage
### Running the Server
```bash
python -m src.server
```
Or using the entry point:
```bash
mysql-mcp-server
```
### Claude Desktop Configuration
Add to your `claude_desktop_config.json` (usually located at `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
```json
{
"mcpServers": {
"mysql": {
"command": "python",
"args": ["-m", "src.server"],
"env": {
"MYSQL_HOST": "127.0.0.1",
"MYSQL_PORT": "3306",
"MYSQL_USER": "root",
"MYSQL_PASSWORD": "your_password",
"MYSQL_DATABASE": "your_database"
}
}
}
}
```
### Claude Code Configuration
Add to your Claude Code MCP configuration:
```json
{
"mcpServers": {
"mysql": {
"command": "python",
"args": ["-m", "src.server"],
"env": {
"MYSQL_HOST": "127.0.0.1",
"MYSQL_PORT": "3306",
"MYSQL_USER": "root",
"MYSQL_PASSWORD": "your_password",
"MYSQL_DATABASE": "your_database"
}
}
}
}
```
### Cursor Configuration
Add to your Cursor MCP configuration:
```json
{
"mcpServers": {
"mysql": {
"command": "python",
"args": ["-m", "src.server"],
"env": {
"MYSQL_HOST": "127.0.0.1",
"MYSQL_PORT": "3306",
"MYSQL_USER": "root",
"MYSQL_PASSWORD": "your_password",
"MYSQL_DATABASE": "your_database"
}
}
}
}
```
#### Per-Project Database Configuration
For per-project database configurations, use project-scoped `.cursor/mcp.json` files. See the [Quick Start Guide](QUICKSTART.md#per-project-database-configuration) for details.
## Available Tools
### CRUD Operations
- `mysql_insert` - Insert a single row into a table
- `mysql_select` - Select data from a table with filtering and sorting
- `mysql_update` - Update rows in a table
- `mysql_delete` - Delete rows from a table
- `mysql_upsert` - Insert or update a row (upsert operation)
### DDL Operations
- `mysql_create_table` - Create a new table
- `mysql_alter_table` - Alter table structure
- `mysql_drop_table` - Drop a table
- `mysql_create_index` - Create an index
- `mysql_drop_index` - Drop an index
- `mysql_create_database` - Create a database
- `mysql_drop_database` - Drop a database
- `mysql_create_view` - Create a view
- `mysql_create_procedure` - Create a stored procedure
- `mysql_create_function` - Create a stored function
- `mysql_create_trigger` - Create a trigger
### Query Tools
- `mysql_execute_query` - Execute an arbitrary SQL query
- `mysql_explain_query` - Explain query execution plan
- `mysql_analyze_query` - Analyze query performance
- `mysql_validate_query` - Validate SQL query syntax and permissions
### Schema Tools
- `mysql_list_databases` - List all databases
- `mysql_list_tables` - List tables in a database
- `mysql_describe_table` - Get detailed table structure
- `mysql_get_table_schema` - Get complete table schema
- `mysql_list_columns` - List columns in a table
- `mysql_list_indexes` - List indexes on a table
- `mysql_list_foreign_keys` - List foreign key relationships
- `mysql_get_table_stats` - Get table statistics
### Administration Tools
- `mysql_show_processes` - Show running processes or kill a process
- `mysql_show_variables` - Show MySQL server variables
- `mysql_show_status` - Show MySQL server status
- `mysql_flush_tables` - Flush tables
- `mysql_optimize_table` - Optimize a table
- `mysql_analyze_table` - Analyze a table
- `mysql_repair_table` - Repair a corrupted table
- `mysql_backup_table` - Backup table data
- `mysql_restore_table` - Restore table data from backup
### Optimization Tools
- `mysql_suggest_indexes` - Suggest indexes for queries
- `mysql_analyze_slow_queries` - Analyze slow query log
- `mysql_get_query_stats` - Get query statistics
## Langchain Integration
### Using with Langchain Agents
```python
from langchain.agents import initialize_agent, AgentType
from langchain.llms import OpenAI
from src.langchain.adapters import create_langchain_tools
# Initialize LLM
llm = OpenAI(temperature=0)
# Get MySQL tools from MCP server
mysql_tools = create_langchain_tools()
# Create agent with MySQL tools
agent = initialize_agent(
tools=mysql_tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
)
# Use the agent
response = agent.run("List all tables in the database")
```
### Using with Langchain SQL Agent
```python
from langchain.llms import OpenAI
from src.langchain.sql_agent import create_mysql_agent
# Initialize LLM
llm = OpenAI(temperature=0)
# Create MySQL SQL agent
agent = create_mysql_agent(
llm=llm,
database="your_database",
verbose=True,
)
# Use the agent
response = agent.run("How many users are in the database?")
```
## Security Features
### SQL Injection Prevention
All queries use parameterized statements to prevent SQL injection attacks. The server validates queries before execution and checks for dangerous patterns.
### Permission System
- **Read-only mode**: Prevents all write operations when enabled
- **DDL restrictions**: Control creation/modification of database structures
- **DELETE restrictions**: Control deletion operations
- **Rate limiting**: Limit queries per minute
### Query Validation
- Syntax validation
- Permission checking
- SQL injection detection
- Complexity analysis
## Examples
See the `examples/` directory for:
- Claude Desktop configuration
- Claude Code configuration
- Cursor configuration
- Langchain integration examples
## Troubleshooting
### Connection Issues
1. Verify MySQL server is running and accessible
2. Check credentials and permissions
3. Ensure SSL/TLS configuration is correct if enabled
4. Try connecting with a MySQL client to confirm access
### Permission Errors
1. Review rate limiting configuration
2. Check query whitelist/blacklist settings
3. Verify SSL/TLS settings
4. Ensure the user has appropriate MySQL permissions
### Performance Issues
1. Adjust connection pool size
2. Configure query timeout values
3. Enable query caching if needed
4. Check query complexity settings
5. Monitor server resource usage
## Publishing to Docker Hub
To build and push the image as **Ayush Singh** (or your Docker Hub username):
```bash
docker build -t ayush1184docker/mysql-mcp-server:1.0.0 .
docker tag ayush1184docker/mysql-mcp-server:1.0.0 ayush1184docker/mysql-mcp-server:latest
docker login
docker push ayush1184docker/mysql-mcp-server:latest
docker push ayush1184docker/mysql-mcp-server:1.0.0
```
See [DOCKER.md](DOCKER.md) for full details.
## Development
### Project Structure
```
mysql-mcp-server/
├── src/
│ ├── database/ # Database connection and query execution
│ ├── tools/ # MCP tool implementations
│ ├── langchain/ # Langchain integration
│ ├── security/ # Security validators and permissions
│ └── utils/ # Configuration and logging
├── tests/ # Test suite
├── examples/ # Configuration examples
└── README.md # This file
```
### Running Tests
```bash
pytest tests/
```
### Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
MIT License. See [LICENSE](LICENSE) for details.
Copyright (c) 2025 Ayush Singh.
## Acknowledgments
- Built with [FastMCP](https://github.com/modelcontextprotocol/python-sdk)
- Inspired by [benborla/mcp-server-mysql](https://github.com/benborla/mcp-server-mysql)
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo recent community issues