MariaDB/MySQL MCP Server
Provides tools to work with a MariaDB database: execute SQL queries, list all tables with row counts, describe a table's column definitions and constraints, and preview sample rows from a table, plus resources exposing database/table overviews.
Provides tools to work with a MySQL database: execute SQL queries, list all tables with row counts, describe a table's column definitions and constraints, and preview sample rows from a table, plus resources exposing database/table overviews.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
MariaDB/MySQL MCP Server
A Model Context Protocol (MCP) server that provides seamless integration with MariaDB and MySQL databases. This server enables AI assistants and other MCP clients to interact with your database through a standardized interface.
โจ Features
๐ Secure Database Connections: Support for SSL/TLS encryption and connection pooling
๐ง Comprehensive Database Tools: Execute queries, browse tables, and inspect database structure
๐ Smart Data Sampling: Preview table contents with configurable limits
๐ Multiple Database Support: Works with both MariaDB and MySQL
โก Async Performance: Built with asyncio for high performance
๐ Error Handling: Robust error handling with detailed feedback
๐ Extensive Logging: Configurable logging for debugging and monitoring
๐ก๏ธ Security Best Practices: Environment-based configuration and SQL injection protection
Related MCP server: MariaDB MCP Server
๐ Quick Start
Prerequisites
Python 3.8 or higher
MariaDB or MySQL server
Required Python packages (see
requirements.txt)
Installation
Clone the repository:
git clone https://github.com/xaviram/mysql-mariadb-mcp-server.git cd mysql-mariadb-mcp-serverInstall dependencies:
pip install -r requirements.txtConfigure your database connection:
cp mcp.example.json mcp.json # Edit mcp.json with your database credentialsTest the server:
python mysql_mcp_server.py
โ๏ธ Configuration
Environment Variables
Configure the server using environment variables or the mcp.json file:
Variable | Default | Description |
|
| Database server hostname |
|
| Database server port |
|
| Database username |
| (empty) | Database password |
|
| Default database name |
|
| Character set |
|
| Connection timeout (seconds) |
|
| Maximum connection pool size |
|
| Enable SSL connection |
Configuration File
Create a mcp.json file:
{
"DB_HOST": "localhost",
"DB_PORT": "3306",
"DB_USER": "your_username",
"DB_PASSWORD": "your_password",
"DB_NAME": "your_database",
"DB_CHARSET": "utf8mb4",
"CONNECTION_TIMEOUT": "10",
"MAX_CONNECTIONS": "5",
"USE_SSL": "false"
}๏ฟฝ๏ธ Available Tools
execute_sql
Execute SQL queries on the database.
Parameters:
query(string): SQL query to execute
Example:
SELECT * FROM users WHERE active = 1 LIMIT 10;show_tables
List all tables in the current database.
Returns: List of table names with row counts and descriptions.
describe_table
Show the structure of a specific table.
Parameters:
table_name(string): Name of the table to describe
Returns: Column definitions with types, constraints, and properties.
table_data_sample
Preview data from a table.
Parameters:
table_name(string): Name of the tablelimit(integer, optional): Number of rows to return (default: 10)
Returns: Sample rows from the specified table.
๐ Resources
The server provides the following resources:
mysql://{database}/tables: Overview of all tables in the databasemysql://{database}/table/{table_name}: Detailed information about a specific table
๐ง Usage with MCP Clients
Claude Desktop
Add to your Claude Desktop configuration:
{
"servers": {
"mysql": {
"command": "python",
"args": ["path/to/mysql_mcp_server.py"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "3306",
"DB_USER": "your_username",
"DB_PASSWORD": "your_password",
"DB_NAME": "your_database"
}
}
}
}Continue VS Code Extension
Add to your Continue configuration:
{
"contextProviders": [
{
"name": "mcp",
"params": {
"command": "python",
"args": ["mysql_mcp_server.py"],
"env": {
"DB_HOST": "localhost",
"DB_USER": "your_username",
"DB_PASSWORD": "your_password",
"DB_NAME": "your_database"
}
}
}
]
}๐งช Testing
Run the comprehensive test suite:
python test_mcp_server.pyThe test script will:
Verify database connectivity
Test all available tools
Validate resource access
Check error handling
Provide troubleshooting guidance
๐ก๏ธ Security Considerations
Best Practices
Use Environment Variables: Never hardcode database credentials
Limit Database Permissions: Create a dedicated database user with minimal required permissions
Enable SSL/TLS: Use encrypted connections in production
Network Security: Restrict database access to trusted networks
Query Validation: The server includes protection against SQL injection
Recommended Database User Permissions
-- Create a dedicated user for the MCP server
CREATE USER 'mcp_user'@'%' IDENTIFIED BY 'secure_password';
-- Grant only necessary permissions
GRANT SELECT, SHOW VIEW ON your_database.* TO 'mcp_user'@'%';
GRANT SELECT ON information_schema.* TO 'mcp_user'@'%';
-- For administrative tasks (optional)
GRANT CREATE, DROP, ALTER ON your_database.* TO 'mcp_user'@'%';
FLUSH PRIVILEGES;๏ฟฝ Troubleshooting
Common Issues
Connection Refused
Verify database server is running
Check host and port configuration
Ensure firewall allows connections
Authentication Failed
Verify username and password
Check user permissions
Ensure user can connect from the client host
SSL Connection Issues
Verify SSL is enabled on the database server
Check SSL certificate configuration
Try disabling SSL for testing
Import Errors
Install required dependencies:
pip install -r requirements.txtVerify Python version compatibility
Debug Mode
Enable detailed logging by setting environment variable:
export LOG_LEVEL=DEBUG
python mysql_mcp_server.py๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
Fork the repository
Create your feature branch (
git checkout -b feature/amazing-feature)Commit your changes (
git commit -m 'Add some amazing feature')Push to the branch (
git push origin feature/amazing-feature)Open a Pull Request
๏ฟฝ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
Model Context Protocol team for the excellent MCP framework
All contributors who help improve this project
๐ Support
๐ Bug Reports: Issues
๐ก Feature Requests: Discussions
๐ Documentation: Wiki
Made with โค๏ธ for the MCP community
Option B: Copy and edit config file
cp config.example.py config.py
### 3. Run the Server
```bash
python mysql_mcp_server.py4. Connect with MCP Client
Configure your MCP client with the provided mcp_config.example.json template.
๐ฆ Installation
Prerequisites
Python 3.8 or higher
MariaDB 10.3+ or MySQL 5.7+
MCP-compatible client (like Claude Desktop, Continue, or similar)
Install Dependencies
# Basic installation
pip install -r requirements.txt
# Development installation (includes testing tools)
pip install -r requirements-dev.txtVerify Installation
# Test database connection
python -c "
import mysql.connector, os
conn = mysql.connector.connect(
host=os.getenv('DB_HOST', 'localhost'),
port=int(os.getenv('DB_PORT', '3306')),
user=os.getenv('DB_USER', 'root'),
password=os.getenv('DB_PASSWORD', ''),
database=os.getenv('DB_NAME', 'mysql')
)
print('โ
Database connection successful!')
conn.close()
"โ๏ธ Configuration
Configuration Methods (Priority Order)
Environment Variables (Highest)
config.py file (Medium)
Default values (Lowest)
Environment Variables
Variable | Description | Default | Example |
| Database server hostname |
|
|
| Database server port |
|
|
| Database username |
|
|
| Database password | `` (empty) |
|
| Database name |
|
|
Configuration File
Create a config.py file from the example:
# config.py
DB_CONFIG = {
'host': 'localhost',
'port': 3306,
'user': 'your_user',
'password': 'your_password',
'database': 'your_database',
'autocommit': True
}
MCP_CONFIG = {
'server_name': 'mysql-mcp-server',
'server_version': '1.0.0',
'description': 'MCP Server for MySQL/MariaDB'
}MCP Client Configuration
Example configuration for MCP clients:
{
"servers": {
"mysql": {
"command": "python",
"args": ["mysql_mcp_server.py"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "3306",
"DB_USER": "your_user",
"DB_PASSWORD": "your_password",
"DB_NAME": "your_database"
}
}
}
}๐ ๏ธ Available Tools
1. execute_sql
Execute any SQL query on the database.
Parameters:
query(string, required): The SQL query to execute
Example:
{
"name": "execute_sql",
"arguments": {
"query": "SELECT * FROM users WHERE active = 1 LIMIT 5"
}
}2. show_tables
List all tables in the database.
Parameters: None
Usage: "Show me all tables in the database"
3. describe_table
Show the structure of a specific table.
Parameters:
table_name(string, required): Name of the table to describe
Example:
{
"name": "describe_table",
"arguments": {
"table_name": "users"
}
}4. table_data_sample
Get a sample of data from a table.
Parameters:
table_name(string, required): Name of the tablelimit(integer, optional): Number of rows to return (default: 10)
Example:
{
"name": "table_data_sample",
"arguments": {
"table_name": "products",
"limit": 5
}
}๐ MCP Resources
The server provides structured resources accessible via MCP URIs:
1. mysql://{database}/tables
Returns a JSON list of all tables with metadata:
{
"database": "myapp_db",
"tables": ["users", "products", "orders"],
"total_tables": 3
}2. mysql://{database}/schema
Returns complete schema information:
{
"database": "myapp_db",
"tables": {
"users": [
{
"Field": "id",
"Type": "int(11)",
"Null": "NO",
"Key": "PRI",
"Default": null,
"Extra": "auto_increment"
}
]
}
}๐ก Examples
Natural Language Queries
With an MCP client, you can ask:
"Show me all tables in the database"
"What's the structure of the users table?"
"Get me 5 sample records from the products table"
"How many active users do we have?"
"Show me recent orders from the last 7 days"
Direct SQL Execution
-- Basic queries
SELECT COUNT(*) FROM users WHERE status = 'active';
SELECT * FROM products WHERE price > 100 ORDER BY price DESC LIMIT 10;
-- Data analysis
SELECT
DATE(created_at) as date,
COUNT(*) as orders_count,
SUM(total_amount) as revenue
FROM orders
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY DATE(created_at)
ORDER BY date DESC;
-- Schema exploration
SHOW TABLES;
DESCRIBE users;
SHOW CREATE TABLE products;๐ง Development
Project Structure
mysql-mariadb-mcp-server/
โโโ mysql_mcp_server.py # Main server implementation
โโโ config.example.py # Configuration template
โโโ mcp_config.example.json # MCP client config template
โโโ requirements.txt # Python dependencies
โโโ requirements-dev.txt # Development dependencies
โโโ test_mcp_server.py # Test script
โโโ .gitignore # Git ignore patterns
โโโ LICENSE # MIT license
โโโ README.md # This fileRunning Tests
# Test the MCP server functionality
python test_mcp_server.py
# Test database connection only
python -c "from mysql_mcp_server import DatabaseConnection; db = DatabaseConnection(); print('โ
Success' if db.connect() else 'โ Failed')"Code Quality
# Install development dependencies
pip install -r requirements-dev.txt
# Format code
black mysql_mcp_server.py
# Lint code
flake8 mysql_mcp_server.py
# Type checking
mypy mysql_mcp_server.py --ignore-missing-imports๐ Troubleshooting
Connection Issues
Error: Can't connect to MySQL server
โ Verify database server is running
โ Check host and port settings
โ Confirm firewall allows connections
Error: Access denied for user
โ Verify username and password
โ Check user privileges:
GRANT SELECT, INSERT, UPDATE, DELETE ON database.* TO 'user'@'host'; FLUSH PRIVILEGES;
Error: Unknown database
โ Ensure database exists:
CREATE DATABASE your_database;โ Verify database name spelling
Module Issues
ImportError: No module named 'mysql.connector'
pip install mysql-connector-pythonImportError: No module named 'mcp'
pip install mcpServer Issues
Server exits immediately
โ Check logs for error messages
โ Verify database connection parameters
โ Ensure Python version 3.8+
Performance Issues
Slow query responses
โ Add database indexes for frequently queried columns
โ Use LIMIT clauses for large result sets
โ Monitor database server performance
๐ค Contributing
Contributions are welcome! Please follow these steps:
Fork the repository
Create a feature branch:
git checkout -b feature/amazing-featureMake your changes with proper tests
Follow code style: Run
blackandflake8Test thoroughly: Ensure all tests pass
Commit changes:
git commit -m 'Add amazing feature'Push to branch:
git push origin feature/amazing-featureOpen a Pull Request
Development Guidelines
Follow PEP 8 style guidelines
Add docstrings to new functions
Include tests for new features
Update documentation as needed
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Support
Issues: GitHub Issues
Discussions: GitHub Discussions
Documentation: Check this README and code comments
โญ Acknowledgments
Model Context Protocol (MCP) team for the excellent framework
MySQL and MariaDB communities for robust database systems
Python community for amazing libraries and tools
Made with โค๏ธ for the MCP community
โญ Star this project if you find it helpful!
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
This server cannot be deployed
Maintenance
Related MCP Connectors
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Guard AI agents' PostgreSQL/MySQL access via MCP: SQL audit, auth, masking, write approval
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Draxlr's remote MCP server connects AI assistants to your SQL databases and dashboards. Explore schemas, run read-only queries, manage saved queries and dashboards, and export results, all with row-level security so each user sees only their own data.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceProvides MySQL database integration for AI assistants and other MCP clients, allowing them to list tables, read table data, and execute SQL queries.-
- AlicenseBqualityDmaintenanceEnables AI assistants to securely interact with MariaDB and MySQL databases using granular per-connection read/write permissions and transaction support. It allows users to manage multiple database connections, explore schemas, and execute controlled SQL queries through a standardized interface.625 npm5MIT
- FlicenseNot gradedqualityDmaintenanceProvides MySQL database query capabilities through MCP protocol, enabling AI assistants to retrieve table metadata, execute SQL queries, and manage database interactions via Resources, Prompts, and Tools.-
- AlicenseNot gradedqualityDmaintenanceEnables AI models to interact with MySQL databases through MCP protocol, supporting queries, table schema inspection, and data manipulation operations.MIT