Kri8tivemike/MySQL-MCP-Local-Server
If you are the rightful owner of MySQL-MCP-Local-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 henry@mcphub.com.
MySQL MCP Server v2.0 is a comprehensive server designed for efficient MySQL database management, offering a suite of 37 tools for various operations.
MySQL MCP Server v2.0
A comprehensive Model Context Protocol (MCP) server for MySQL database operations with 37 powerful tools, advanced error handling, logging, and transaction support.
๐ Features
- โ 37 MySQL Tools: Complete database management toolkit
- โ Core Operations: SELECT, INSERT, UPDATE, DELETE queries
- โ Schema Management: Create/drop tables, indexes, alter structures
- โ Advanced Queries: Joins, aggregations, bulk operations, upserts
- โ Database Administration: Backup, restore, optimize, analyze
- โ User & Security: User management and permissions (where supported)
- โ Monitoring & Performance: Query analysis, status monitoring, table sizes
- โ Import/Export: CSV, JSON data exchange, table cloning
- โ Transaction Support: Multi-query transactions with rollback
- โ Connection Management: Pooling, health checks, auto-reconnection
- โ Error Handling: Comprehensive error handling with detailed logging
- โ Testing: Complete test suite covering all 37 tools
๐ Prerequisites
- Node.js 18.0.0 or higher
- MySQL server 5.7+ or 8.0+
- Database credentials configured
๐ ๏ธ Installation
- Install dependencies:
npm install
- Configure your database connection by updating the
.env
file:
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
๐ฏ Usage
Starting the Server
# Production mode
npm start
# Development mode with auto-restart
npm run dev
Running Tests
npm test
๐ง Available Tools (37 Total)
Core Database Operations (4 tools)
1. mysql_query
Execute SELECT queries on the database.
Parameters:
sql
(string, required): The SQL SELECT queryparams
(array, optional): Parameters for prepared statements
Example:
{
"sql": "SELECT * FROM users WHERE age > ? AND department = ?",
"params": [25, "IT"]
}
2. mysql_insert
Insert data into a table.
Parameters:
table
(string, required): Table namedata
(object, required): Key-value pairs of column names and values
Example:
{
"table": "users",
"data": {
"name": "John Doe",
"email": "john@example.com",
"age": 30,
"department": "Engineering"
}
}
3. mysql_update
Update data in a table.
Parameters:
table
(string, required): Table namedata
(object, required): Key-value pairs of columns to updatewhere
(object, required): WHERE conditions
Example:
{
"table": "users",
"data": {
"age": 31,
"department": "Senior Engineering"
},
"where": {
"email": "john@example.com"
}
}
4. mysql_delete
Delete data from a table.
Parameters:
table
(string, required): Table namewhere
(object, required): WHERE conditions
Example:
{
"table": "users",
"where": {
"email": "john@example.com"
}
}
Schema Management Tools (5 tools)
5. mysql_create_table
Create new tables with column definitions.
Parameters:
table_name
(string, required): Name of the table to createcolumns
(array, required): Array of column definitionsoptions
(object, optional): Additional table options
Example:
{
"table_name": "products",
"columns": [
"id INT AUTO_INCREMENT PRIMARY KEY",
"name VARCHAR(255) NOT NULL",
"price DECIMAL(10,2)",
"created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
],
"options": {
"engine": "InnoDB",
"charset": "utf8mb4"
}
}
6. mysql_drop_table
Drop tables safely.
Parameters:
table_name
(string, required): Name of the table to dropif_exists
(boolean, optional): Use IF EXISTS clause
Example:
{
"table_name": "old_products",
"if_exists": true
}
7. mysql_alter_table
Modify table structure (add/drop columns).
Parameters:
table_name
(string, required): Name of the table to alteraction
(string, required): Action to perform (ADD, DROP, MODIFY)column_definition
(string, required): Column definition or name
Example:
{
"table_name": "users",
"action": "ADD",
"column_definition": "phone VARCHAR(20)"
}
8. mysql_create_index
Create database indexes.
Parameters:
table_name
(string, required): Table nameindex_name
(string, required): Index namecolumns
(array, required): Columns to indexunique
(boolean, optional): Create unique index
Example:
{
"table_name": "users",
"index_name": "idx_email",
"columns": ["email"],
"unique": true
}
9. mysql_drop_index
Remove indexes.
Parameters:
table_name
(string, required): Table nameindex_name
(string, required): Index name to drop
Example:
{
"table_name": "users",
"index_name": "idx_email"
}
Advanced Query Tools (5 tools)
10. mysql_aggregate_query
Execute aggregate functions (COUNT, SUM, AVG, etc.).
Parameters:
table
(string, required): Table nameaggregates
(array, required): Aggregate functionswhere
(object, optional): WHERE conditionsgroup_by
(array, optional): GROUP BY columns
Example:
{
"table": "orders",
"aggregates": ["COUNT(*) as total_orders", "SUM(amount) as total_revenue"],
"where": {"status": "completed"},
"group_by": ["customer_id"]
}
11. mysql_join_query
Execute complex JOIN operations.
Parameters:
main_table
(string, required): Primary tablejoins
(array, required): Join definitionsselect
(array, required): Columns to selectwhere
(object, optional): WHERE conditions
Example:
{
"main_table": "users",
"joins": [
{
"type": "INNER",
"table": "orders",
"on": "users.id = orders.user_id"
}
],
"select": ["users.name", "users.email", "orders.total"],
"where": {"orders.status": "completed"}
}
12. mysql_bulk_insert
Insert multiple records efficiently.
Parameters:
table
(string, required): Table namedata
(array, required): Array of objects to insert
Example:
{
"table": "products",
"data": [
{"name": "Product A", "price": 19.99, "category": "Electronics"},
{"name": "Product B", "price": 29.99, "category": "Electronics"},
{"name": "Product C", "price": 39.99, "category": "Books"}
]
}
13. mysql_upsert
INSERT ON DUPLICATE KEY UPDATE operations.
Parameters:
table
(string, required): Table namedata
(object, required): Data to insert/updateupdate_on_duplicate
(object, optional): Columns to update on duplicate
Example:
{
"table": "products",
"data": {"sku": "ABC123", "name": "Product A", "price": 24.99},
"update_on_duplicate": {"price": "VALUES(price)", "updated_at": "NOW()"}
}
14. mysql_search
Full-text search with LIKE/MATCH operations.
Parameters:
table
(string, required): Table namesearch_columns
(array, required): Columns to searchsearch_term
(string, required): Search termmatch_mode
(string, optional): LIKE or MATCH (default: LIKE)
Example:
{
"table": "articles",
"search_columns": ["title", "content"],
"search_term": "database optimization",
"match_mode": "LIKE"
}
Database Administration Tools (6 tools)
15. mysql_show_databases
List all databases on server.
Parameters: None
16. mysql_create_database
Create new databases.
Parameters:
database_name
(string, required): Name of database to createcharset
(string, optional): Character setcollation
(string, optional): Collation
Example:
{
"database_name": "new_project",
"charset": "utf8mb4",
"collation": "utf8mb4_unicode_ci"
}
17. mysql_backup_table
Export table data to SQL.
Parameters:
table_name
(string, required): Table to backupinclude_data
(boolean, optional): Include data (default: true)file_path
(string, optional): Output file path
Example:
{
"table_name": "users",
"include_data": true,
"file_path": "./backups/users_backup.sql"
}
18. mysql_restore_table
Import data from SQL backup.
Parameters:
file_path
(string, required): Path to SQL backup filetable_name
(string, optional): Specific table to restore
Example:
{
"file_path": "./backups/users_backup.sql",
"table_name": "users"
}
19. mysql_optimize_table
Optimize table performance.
Parameters:
table_names
(array, required): Tables to optimize
Example:
{
"table_names": ["users", "orders", "products"]
}
20. mysql_analyze_table
Analyze table statistics.
Parameters:
table_names
(array, required): Tables to analyze
Example:
{
"table_names": ["users", "orders"]
}
User & Security Tools (4 tools)
21. mysql_show_users
List database users.
Parameters: None
22. mysql_show_grants
Show user permissions.
Parameters:
username
(string, optional): Specific user (default: current user)
Example:
{
"username": "app_user"
}
23. mysql_create_user
Create database users.
Parameters:
username
(string, required): Usernamepassword
(string, required): Passwordhost
(string, optional): Host (default: %)
Example:
{
"username": "new_user",
"password": "secure_password",
"host": "localhost"
}
24. mysql_grant_privileges
Grant user permissions.
Parameters:
username
(string, required): Usernameprivileges
(array, required): Privileges to grantdatabase
(string, optional): Database nametable
(string, optional): Table name
Example:
{
"username": "app_user",
"privileges": ["SELECT", "INSERT", "UPDATE"],
"database": "app_db",
"table": "*"
}
Monitoring & Performance Tools (5 tools)
25. mysql_show_processlist
Show running queries.
Parameters:
full
(boolean, optional): Show full queries
Example:
{
"full": true
}
26. mysql_explain_query
Analyze query execution plan.
Parameters:
sql
(string, required): Query to analyzeformat
(string, optional): Output format (TRADITIONAL, JSON)
Example:
{
"sql": "SELECT * FROM users WHERE age > 25 ORDER BY created_at",
"format": "JSON"
}
27. mysql_show_status
Database server status.
Parameters:
pattern
(string, optional): Status variable pattern
Example:
{
"pattern": "Connections"
}
28. mysql_show_variables
Server configuration variables.
Parameters:
pattern
(string, optional): Variable name pattern
Example:
{
"pattern": "innodb%"
}
29. mysql_table_size
Get table size information.
Parameters:
table_names
(array, optional): Specific tables (default: all)
Example:
{
"table_names": ["users", "orders"]
}
Data Import/Export Tools (4 tools)
30. mysql_export_csv
Export query results to CSV.
Parameters:
sql
(string, required): Query to exportfile_path
(string, required): Output CSV file pathheaders
(boolean, optional): Include headers
Example:
{
"sql": "SELECT name, email, age FROM users",
"file_path": "./exports/users.csv",
"headers": true
}
31. mysql_import_csv
Import CSV data to tables.
Parameters:
table_name
(string, required): Target tablefile_path
(string, required): CSV file pathcolumns
(array, optional): Column mappingskip_header
(boolean, optional): Skip first row
Example:
{
"table_name": "users",
"file_path": "./imports/users.csv",
"columns": ["name", "email", "age"],
"skip_header": true
}
32. mysql_export_json
Export data as JSON.
Parameters:
sql
(string, required): Query to exportfile_path
(string, required): Output JSON file pathpretty
(boolean, optional): Pretty print JSON
Example:
{
"sql": "SELECT * FROM products WHERE category = 'Electronics'",
"file_path": "./exports/electronics.json",
"pretty": true
}
33. mysql_clone_table
Copy table structure/data.
Parameters:
source_table
(string, required): Source table nametarget_table
(string, required): Target table nameinclude_data
(boolean, optional): Copy data (default: true)include_indexes
(boolean, optional): Copy indexes (default: true)
Example:
{
"source_table": "users",
"target_table": "users_backup",
"include_data": true,
"include_indexes": false
}
Utility Tools (4 tools)
34. mysql_transaction
Execute multiple queries in a transaction.
Parameters:
queries
(array, required): Array of query objects
Example:
{
"queries": [
{
"sql": "INSERT INTO users (name, email) VALUES (?, ?)",
"params": ["Alice", "alice@example.com"]
},
{
"sql": "UPDATE users SET last_login = NOW() WHERE email = ?",
"params": ["alice@example.com"]
}
]
}
35. mysql_list_tables
List all tables in the database.
Parameters:
pattern
(string, optional): Table name pattern
Example:
{
"pattern": "user%"
}
36. mysql_describe_table
Get detailed information about a table structure.
Parameters:
table_name
(string, required): Table name
Example:
{
"table_name": "users"
}
37. mysql_health_check
Check the health of the database connection.
Parameters: None
โ๏ธ Configuration
The server uses the following environment variables:
Variable | Default | Description |
---|---|---|
DB_HOST | localhost | MySQL server host |
DB_PORT | 3306 | MySQL server port |
DB_USERNAME | root | Database username |
DB_PASSWORD | (empty) | Database password |
DB_DATABASE | test | Database name |
DB_CONNECTION_LIMIT | 10 | Connection pool limit |
๐ Logging
The server uses Winston for comprehensive logging:
- Console: Colored output for development
- File:
logs/combined.log
for all logs - File:
logs/error.log
for error logs only
Log levels: error
, warn
, info
, debug
๐ก๏ธ Error Handling
Comprehensive error handling includes:
- Connection Errors: Automatic reconnection and connection pooling
- SQL Errors: Detailed error messages with SQL state and error codes
- Transaction Errors: Automatic rollback on failure
- Validation Errors: Input validation for all operations
- Permission Errors: Graceful handling of insufficient privileges
- File I/O Errors: Proper error handling for import/export operations
๐งช Testing
The comprehensive test suite validates all 37 tools:
- Database connection and health checks
- All CRUD operations with various data types
- Schema management operations
- Advanced query operations (joins, aggregates, bulk operations)
- Transaction handling with commit and rollback
- Database administration tools
- User and security operations (where permissions allow)
- Monitoring and performance tools
- Import/export functionality
- Error handling for invalid operations
Run tests with:
npm test
๐ Project Structure
mysql-mcp-server/
โโโ src/
โ โโโ index.js # Main MCP server with all 37 tools
โ โโโ database.js # Database connection and operations
โโโ test/
โ โโโ test-operations.js # Comprehensive test suite
โโโ logs/
โ โโโ .gitkeep # Logs directory
โโโ .env # Environment configuration
โโโ package.json # Project dependencies
โโโ README.md # This documentation
๐ Security Considerations
- Uses prepared statements to prevent SQL injection
- Connection pooling with limits to prevent resource exhaustion
- No sensitive data logged (passwords, connection strings)
- Input validation and sanitization for all operations
- Secure file handling for import/export operations
- Proper error messages without exposing system internals
๐ Performance Features
- Connection pooling for optimal performance
- Bulk operations for large data sets
- Query optimization tools and analysis
- Table optimization and maintenance tools
- Efficient transaction handling
- Streaming for large data exports
๐ Tool Categories Summary
Category | Tools | Description |
---|---|---|
Core Operations | 4 | Basic CRUD operations |
Schema Management | 5 | Table and index management |
Advanced Queries | 5 | Complex queries and bulk operations |
Database Admin | 6 | Backup, restore, optimization |
User & Security | 4 | User management and permissions |
Monitoring | 5 | Performance monitoring and analysis |
Import/Export | 4 | Data exchange in various formats |
Utilities | 4 | Helper tools and health checks |
Total | 37 | Complete MySQL management toolkit |
๐ License
MIT License
MySQL MCP Server v2.0 - The most comprehensive MySQL MCP server with 37 powerful tools for complete database management.