MySQL Automation MCP Server
Provides tools for interacting with a MySQL database, including connection health testing and runtime credential reconfiguration, table listing, deep schema introspection with caching, safe read-only query execution with automatic LIMIT handling, transactional mutations with safety guardrails, multi-format EXPLAIN query plans, and CSV/JSON query result exports.
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.
MySQL Automation MCP Server
A Model Context Protocol (MCP) server for MySQL database operations, schema exploration, dynamic database switching, query execution, safety guardrails, query history audit logging, and natural language analytics.
Designed for universal, portable distribution across OpenClaw, Claude Desktop, and agentic AI systems on Windows, macOS, and Linux.
Key Features
12 Production-Ready MCP Tools: Connection health testing, dynamic runtime credential reconfiguration, multi-database discovery (
list_databases), on-the-fly database switching (use_database), table listing, deep schema inspection, safe read query execution, transactional mutations, multi-formatEXPLAINquery plans, CSV/JSON query exports, and local query history inspection (get_query_history).Query History Audit Logging & Forensic Trail:
Automatically records every query executed, failed, or blocked by safety guardrails to an append-only JSONL log (
~/.mysql-mcp/logs/query_history.jsonl).Guards against and audits LLM hallucinations: inspect the exact raw query requested, modified query with limit injection, duration, affected rows, and error messages.
Review query history anytime directly in chat via the
get_query_historytool.
Multi-Database Support:
Connects gracefully at the MySQL instance level without requiring a hardcoded initial database.
Dynamically discover all databases with
list_databases().Switch active database context instantly at runtime via
use_database(database_name).Maintains separate schema caches per database.
Universal, Zero-Hardcoding Portability:
Automatically defaults data storage to the user home directory (
~/.mysql-mcp/exportsand~/.mysql-mcp/cache).Supports packaging and instant execution via
uvxwithout needing hardcoded paths or manual environment configuration.Persists dynamic runtime configurations to
~/.mysql-mcp/config.json.
AST-Based Query Safety Guardrails (
sqlparse):Differentiates read-only statements (
SELECT,SHOW,DESCRIBE,EXPLAIN,WITH ... SELECT) from mutations (INSERT,UPDATE,DELETE,DROP,ALTER, etc.).Rejects dangerous unconstrained
UPDATEandDELETEqueries lacking aWHEREclause unlessallow_unfiltered=Trueis explicitly specified.Requires explicit
confirmed=Truefor destructive DDL operations (DROP,TRUNCATE,ALTER).Automatically injects default
LIMIT 50intoSELECTqueries without one, respects lock clauses (FOR UPDATE), and clamps queries exceedingLIMIT 1000.
Pure-Python PyMySQL Connection Pooling:
Thread-safe connection pool with configurable pool size, overflow capacity, and timeouts.
Proactive health pings (
conn.ping()) and automatic recovery of stale or severed connections.Transaction context manager (
transaction()) with automatic commit on success and rollback on exceptions.
Two-Tier Schema Introspection & Caching:
Deep introspection of tables, views, column types, nullability, defaults, indexes, and foreign key constraints (
ON UPDATE,ON DELETE) frominformation_schema.In-memory Tier 1 cache + persistent disk Tier 2 cache (
~/.mysql-mcp/cache/schema_<db>.json).Dual output modes: structured JSON/dictionary and human-readable Markdown summary.
User-Friendly Error Diagnostics:
Translates cryptic MySQL error codes (
1045,1049,1054,1064,1146,1215,1451) into clear diagnostic explanations and suggested remediation actions.
MCP Resources & Prompts:
Resources:
mysql://schemaandmysql://query-patterns.Prompts:
generate_sqlandoptimize_query.
Related MCP server: MySQL MCP Server
Project Structure
mysql-automation-mcp-server/
├── src/
│ └── mysql_mcp/
│ ├── __init__.py
│ ├── audit.py # Thread-safe query audit logger & history tracker
│ ├── config.py # Pydantic Settings, ~/.mysql-mcp persistence, & env config
│ ├── db.py # Pure-Python PyMySQL pooling & transactions
│ ├── errors.py # MySQL error diagnostics & guidance catalog
│ ├── safety.py # sqlparse query classification & safety rules
│ ├── schema.py # Per-database schema extraction, Markdown, & two-tier cache
│ └── server.py # FastMCP server with 12 tools, 2 resources, 2 prompts
├── scripts/
│ ├── seed_demo_db.py # Database initializer and sample data generator
│ └── verify_server_e2e.py # Complete end-to-end server verification script
├── tests/
│ ├── test_audit.py # Unit & integration tests for query audit history (8 tests)
│ ├── test_safety.py # Unit tests for query safety rules (41 tests)
│ ├── test_schema.py # Unit tests for schema extraction & caching (10 tests)
│ ├── test_seed.py # Verification of seeded demo database (1 test)
│ └── test_server.py # Tests for FastMCP tools, resources & prompts (28 tests)
├── .env.example # Environment configuration template
├── openclaw_config.json # Sanitized OpenClaw / Claude Desktop MCP client configuration
├── pyproject.toml # Project metadata, CLI script entrypoint, & pytest settings
├── query-patterns.md # Advanced SQL reference (CTEs, Window, JSON)
├── requirements.txt # Project dependencies
├── SKILL.md # OpenClaw agent skill definition
└── README.mdUniversal Setup & Execution
Option A: Direct Execution via uvx (Recommended for End Users)
Any user on Windows, macOS, or Linux can run the MCP server with zero installation:
{
"mcpServers": {
"mysql-automation": {
"command": "uvx",
"args": ["mysql-automation-mcp-server"],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "your_mysql_username",
"MYSQL_PASSWORD": "your_mysql_password"
}
}
}
}Option B: Local Source Setup (Developers)
git clone https://github.com/shivangbhatt10/mysql-automation-mcp-server.git
cd mysql-automation-mcp-server
# Create virtual environment with Python 3.10+
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies and local package in editable mode
pip install -e .
# Configure environment
cp .env.example .env
# Optional: Seed demo database
python scripts/seed_demo_db.py
# Run verification and tests
python scripts/verify_server_e2e.py
pytest -vMulti-Database Management Workflow
When connecting to MySQL instances hosting multiple databases:
Initial Connect: If no database is specified in
MYSQL_DATABASE, the server connects at the instance level.List Databases: Call
list_databases()to see all databases accessible by the user (with system catalogs flagged).Switch Active Database: Call
use_database("analytics_db")to switch context at runtime without restarting the server.Inspect & Query: All subsequent queries and schema inspections target the newly selected database.
MCP Tools Reference
The server exposes 12 MCP tools:
Tool Name | Parameters | Description |
| None | Pings the active MySQL instance and returns connection status, roundtrip latency (ms), MySQL version, active database, and pool statistics. |
|
| Reconfigures connection credentials dynamically at runtime, rebuilds the connection pool, invalidates caches, confirms connectivity, and optionally persists credentials to |
| None | Returns a list of all databases on the connected MySQL server, identifying the active database and filtering/flagging system catalogs. |
|
| Validates that the database exists, switches the active database context, reinitializes the pool, and updates persistent settings. |
| None | Returns a list of all base tables and views in the active database with estimated row counts, column counts, and primary keys. |
|
| Returns detailed column definitions (types, nullability, defaults, keys, extra) and indexes for the specified table. |
|
| Returns the database schema in human-readable Markdown ( |
|
| Validates that the query is read-only, safely injects or clamps the |
|
| Executes |
|
| Runs |
|
| Executes a read-only query and exports the results to |
|
| Retrieves recent queries executed by the assistant from the local JSONL audit trail ( |
MCP Resources Reference
The server exposes 2 MCP resources:
URI | Content Type | Description |
|
| Returns the active MySQL database schema documentation in Markdown format (tables, columns, indexes, foreign keys). |
|
| Streams the contents of |
MCP Prompts Reference
The server exposes 2 MCP prompts:
Prompt Name | Arguments | Description |
|
| Instructs the model to generate safe, performant SQL following strict guidelines: explicit |
|
| Diagnostic checklist for interpreting MySQL query execution plans: identifying full table scans ( |
Safety Guardrails Reference
Read-Only vs Mutation Enforcement:
execute_querypermits onlySELECT,SHOW,DESCRIBE,EXPLAIN, andWITH ... SELECTqueries.Any attempt to execute
INSERT,UPDATE,DELETE,DROP, orALTERviaexecute_queryraises aQuerySafetyError.
Unconstrained Mutation Protection:
Any
UPDATEorDELETEstatement lacking a top-levelWHEREclause is blocked.Empty
WHEREclauses, comment-only clauses, or subqueries that leave the outer statement unconstrained are detected and rejected.Set
allow_unfiltered=Trueinexecute_mutationto explicitly bypass when intended.
Destructive DDL Confirmation:
DROP,TRUNCATE, andALTERstatements require explicit confirmation viaconfirmed=Trueinexecute_mutation.
Automatic Result Pagination:
SELECTqueries without aLIMITclause automatically receiveLIMIT 50.Existing
LIMITclauses exceeding1000rows are automatically clamped to1000.Semicolons and trailing lock clauses (
FOR UPDATE,FOR SHARE) are preserved in their valid SQL syntax order.
OpenClaw / Claude Desktop Integration
This server can be integrated directly with OpenClaw or Claude Desktop by adding the configuration block from openclaw_config.json.
Sanitized Client Configuration Template
{
"mcpServers": {
"mysql-automation": {
"command": "uvx",
"args": [
"mysql-automation-mcp-server"
],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "${MYSQL_USER:-root}",
"MYSQL_PASSWORD": "${MYSQL_PASSWORD:-}",
"MYSQL_DATABASE": "${MYSQL_DATABASE:-}"
}
}
}
}License
This project is licensed under the MIT License.
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
Query, explore, and manage your databases through natural conversation.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables read-only access to MySQL databases through natural language queries. Provides automatic table schema discovery and executes SELECT, SHOW, DESCRIBE, and EXPLAIN statements within secure read-only transactions.MIT
- AlicenseNot gradedqualityDmaintenanceEnables natural language database operations on MySQL databases with AI integration, supporting CRUD operations, schema inspection, and audit logging with built-in security features including SQL injection protection and permission controls.798 npmMIT
- AlicenseCqualityDmaintenanceEnables monitoring and administration of MySQL databases through natural language, supporting multiple simultaneous connections, health checks, and full DDL/DML/DCL operations.3931 npmMIT
- AlicenseNot gradedqualityDmaintenanceEnables AI tools to interact with MySQL databases through natural language, including schema browsing, queries, CRUD operations, with destructive actions gated behind user approval.52 npm1MIT