Secure MySQL MCP Server
Provides tools for interacting with a MySQL database server: listing databases, tables and views, describing schemas and foreign key relationships, running AST-validated SELECT queries with row/timeout limits, inspecting EXPLAIN plans, and generating database size/engine overviews. Write operations are performed through a staged approval flow (propose_write, write_query, execute_approved_write) that previews affected rows, enforces WHERE clauses on UPDATE/DELETE, and only executes with explicit permission, using separate read-only and write-restricted connection pools.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Secure MySQL MCP Server show me the row count and top 5 rows of the users table"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
๐ก๏ธ Secure MySQL MCP Server
The enterprise-grade, AST-guarded Model Context Protocol (MCP) server for MySQL.
Works seamlessly with Antigravity, Claude Code, Cursor, Devin, Codex, and any MCP client.
๐ Why This MCP Server?
Standard off-the-shelf MySQL MCP servers blindly execute any raw SQL string passed by the AI agent โ allowing unintended table drops, mass updates without WHERE clauses, or data corruption.
Secure MySQL MCP solves this by putting a protective AST parser, configurable permission gate, and automated SSH tunnel directly between the AI and your database.
AI Coding Agent (Antigravity / Claude / Cursor / Devin)
โ
โผ (stdio JSON-RPC)
Secure MySQL MCP Server
โโโ ๐ AST SQL Parser (node-sql-parser)
โ โโโ Blocks multi-statements, INTO OUTFILE, session variables
โ โโโ Enforces WHERE clauses on UPDATE and DELETE
โโโ ๐ฆ Configurable Policy Engine (Strict / Prompt / Autonomous)
โ โโโ Safe by default (Blocks DROP, TRUNCATE, DELETE, DDL)
โ โโโ Granular opt-in auto-approval flags
โโโ ๐ Dual Pool Isolation
โ โโโ ai_agent_reader (SELECT, SHOW VIEW only)
โ โโโ ai_agent_writer (INSERT, UPDATE, DELETE in atomic transactions)
โโโ ๐ Pino Structured Audit Logger (Auto-redacts credentials & keys)
โ
โผ (127.0.0.1:13306 or Direct SSL)
SSH Tunnel / Cloud Database (DigitalOcean, AWS RDS, GCP Cloud SQL, Self-hosted VPS)Related MCP server: MySQL ReadOnly MCP Server
๐ Key Features
๐ก๏ธ Safe by Default: Destructive statements (
DELETE,DROP,TRUNCATE,ALTER,CREATE) are blocked out of the box.โก Fully Customizable Autonomy: Want the AI to write without asking permission? Switch
POLICY_MODE=autonomousor toggle granular flags (POLICY_AUTO_APPROVE_INSERT=true,POLICY_ALLOW_DELETE=true).๐ No Full-Table Accidents: AST parser rejects
UPDATEorDELETEwithout aWHEREclause.๐ Anti-Injection Guardrails: Permanently eliminates
INTO OUTFILE,LOAD DATA INFILE, user session variable tampering (@var), and chained multi-statements.๐ Built-in SSH Tunnel: Automatically provisions and tears down a local SSH tunnel (
ssh -N -L) or connects directly via TLS/SSL.๐ฅ Least-Privilege Architecture: Dual connection pools route reads to a read-only DB user and writes to a write-restricted DB user.
๐ 10 Powerful Tools: 7 inspection & query tools, plus 3 write tools (
propose_write,write_query,execute_approved_write).
๐ฆ Quick Installation
Option 1: Run with npx via GitHub (Zero manual build needed)
Thanks to the automated prepare build lifecycle, you can run directly from GitHub without cloning:
npx github:Kavi-200312/mysql-mcp(Once published to the public npm registry, npx mysql-mcp will also be available).
Option 2: Clone and Build Locally
git clone https://github.com/Kavi-200312/mysql-mcp.git
cd mysql-mcp
npm install
npm test
npm run build๐ค Client Setup Guides
1. Antigravity Setup
Add to ~/.gemini/config/mcp_config.json:
{
"mcpServers": {
"mysql": {
"command": "node",
"args": ["/path/to/mysql-mcp/dist/index.js"]
}
}
}2. Claude Desktop / Claude Code Setup
Add to claude_desktop_config.json (Mac: ~/Library/Application Support/Claude/claude_desktop_config.json, Windows: %APPDATA%\Claude\claude_desktop_config.json):
{
"mcpServers": {
"mysql": {
"command": "node",
"args": ["/path/to/mysql-mcp/dist/index.js"],
"env": {
"DB_HOST": "127.0.0.1",
"DB_PORT": "3306",
"DB_NAME": "my_database",
"DB_READER_USER": "ai_agent_reader",
"DB_READER_PASSWORD": "your_password",
"DB_WRITER_USER": "ai_agent_writer",
"DB_WRITER_PASSWORD": "your_password"
}
}
}
}3. Cursor Setup
In Cursor, go to Settings > Features > MCP, click Add New MCP Server:
Name:
mysqlType:
commandCommand:
node /path/to/mysql-mcp/dist/index.js
Or add to .cursor/mcp.json in your workspace:
{
"mcpServers": {
"mysql": {
"command": "node",
"args": ["/path/to/mysql-mcp/dist/index.js"]
}
}
}4. Devin Setup
Add to your Devin machine configuration or devin.json:
{
"mcpServers": {
"mysql": {
"command": "node",
"args": ["/path/to/mysql-mcp/dist/index.js"]
}
}
}โ๏ธ Configuration Reference (.env)
Copy .env.example to .env in the project root:
cp .env.example .envVariable | Default | Description |
Database Connection | ||
|
| MySQL server host (or localhost if using SSH tunnel) |
|
| MySQL port (e.g. |
|
| Target development database name |
|
|
|
|
| Least-privilege user for read tools |
|
| Password for reader user |
|
| Dedicated user for write tools |
|
| Password for writer user |
SSH Tunneling | ||
|
| Set to |
|
| Remote SSH IP or hostname |
|
| Remote SSH port |
|
| Remote SSH username |
|
| Path to private key (e.g. |
|
| Local forwarding port |
Security & Permission Policies | ||
|
|
|
|
| Enable |
|
| Enable |
|
| Enforce mandatory |
|
| Auto-execute |
|
| Auto-execute |
|
| Auto-execute |
|
| Auto-execute DDL ( |
Limits & Auditing | ||
|
| Max rows returned per query to prevent memory bloat |
|
| Query execution timeout (15s) |
|
| Payload size cap (512 KB) |
|
| Lifetime of write approval tokens (5 min) |
|
| Structured logging level ( |
๐ ๏ธ Available MCP Tools
Read & Inspection Tools
Tool | Description |
| Lists all accessible databases on the host. |
| Lists all tables and views in the configured database. |
| Inspects table schema, columns, data types, keys, and nullability. |
| Executes AST-validated |
| Inspects MySQL execution plan ( |
| Inspects foreign key constraints and referenced tables. |
| Generates summary of table sizes, engine, and row estimates. |
Write & Execution Tools
Tool | Description |
| Previews changes, estimates affected rows, and generates an approval token. |
| Smart execution tool: runs immediately if permitted by policy, or returns a prompt token if approval is required. |
| Atomically executes a previously authorized token with explicit confirmation. |
๐ก๏ธ Database Provisioning Script
Run this on your remote MySQL server to create isolated accounts:
-- 1. Create read-only user (SELECT and SHOW VIEW only)
CREATE USER IF NOT EXISTS 'ai_agent_reader'@'%' IDENTIFIED BY 'STRONG_READER_PASSWORD';
GRANT SELECT, SHOW VIEW ON `my_dev_db`.* TO 'ai_agent_reader'@'%';
-- 2. Create writer user (Restricted to DML only)
CREATE USER IF NOT EXISTS 'ai_agent_writer'@'%' IDENTIFIED BY 'STRONG_WRITER_PASSWORD';
GRANT SELECT, INSERT, UPDATE, DELETE ON `my_dev_db`.* TO 'ai_agent_writer'@'%';
FLUSH PRIVILEGES;๐งช Testing & Security Verification
The test suite runs 40 automated security tests using Vitest:
npm testVerifies:
SELECT,SHOW,DESCRIBE,EXPLAINallowedDELETE,DROP,TRUNCATE,ALTER,CREATEblocked by defaultConfigurable policies allow
DELETEandDDLonly when explicitly enabledUPDATEandDELETEwithoutWHERErejectedSession variable injections (
@var) and comment-obfuscatedINTO OUTFILEpermanently blockedCross-database subqueries, joins, CTEs, and UNIONs strictly prevented
Locking reads (
FOR UPDATE/LOCK IN SHARE MODE) prohibited on read pathApproval tokens reject tampered queries, altered params, and re-executions
Row caps, server-side
LIMITinjection, and query cancellation (KILL QUERY) enforcedSensitive credentials and tokens automatically redacted from audit logs
๐ก๏ธ Security Model & Consent Guarantees
Defense-in-Depth Architecture:
The propose_write + execute_approved_write workflow and the userConfirmed: true flag are designed to prevent accidental model hallucinations and catastrophic runaway updates.
For mission-critical environments where you defend against adversarial prompt injections, always pair this MCP server with:
Dedicated least-privilege MySQL accounts (
ai_agent_reader/ai_agent_writer) created viascripts/create-db-users.sql.Native MCP client permission prompts (e.g. Antigravity / Claude Code UI tool confirmation).
๐ License
Available Tools
10 toolsdescribe_tableB
Get column details, data types, keys, and nullability for a table.
Inputs: table (required), database.
execute_approved_writeA
Execute a previously proposed and user-approved write operation using its short-lived approval token. Strictly requires userConfirmed: true.
Inputs: approvalToken (required), userConfirmed (required).
explain_queryC
Get MySQL query execution plan (EXPLAIN) for a SELECT statement.
Inputs: sql (required), params, database.
get_database_overviewB
Get high-level summary of tables, estimated row counts, storage size, and collation.
Inputs: database.
get_table_relationshipsC
Inspect foreign key relationships and table constraints.
Inputs: table, database.
list_databasesA
List accessible databases on the remote MySQL instance.
Inputs: no named parameters.
list_tablesA
List all tables and views in the development database.
Inputs: database.
propose_writeA
Propose an INSERT, UPDATE, DELETE, or DDL statement. Validates SQL AST, shows preview diff of affected rows, and generates an approval token. NEVER executes immediately.
Inputs: sql (required), params, database, confirmBulk.
read_queryA
Execute a read-only SELECT query against the development database. AST-enforced, single statement only. Max 500 rows.
Inputs: sql (required), limit, params, database.
write_queryA
Execute a write statement (INSERT, UPDATE, DELETE, or DDL). If the operation is configured for auto-approval in policy, it executes immediately in an atomic transaction; otherwise, it returns a pending approval request.
Inputs: sql (required), params, database, userConfirmed.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 10 tools
Discovery tools (list_databases, list_tables, describe_table, get_database_overview, get_table_relationships) each target a distinct metadata scope, and read_query vs explain_query are clearly separated. The only real friction is the write trio: propose_write and write_query overlap in that write_query may just return a pending approval instead of executing, which could make an agent unsure which to call first, though the descriptions do resolve it.
All ten tools use snake_case verb_noun form (list_databases, describe_table, read_query, propose_write, execute_approved_write) with no camelCase or style mixing. The pattern is predictable enough that an agent can infer naming for unseen operations.
Ten tools is well within the ideal band and each earns its place: introspection, read path, explain, relationships, overview, and a three-stage guarded write lifecycle. Nothing looks redundant padding or conspicuously absent.
The surface covers discovery, read-only querying, plan inspection, and a full propose/approve/execute write lifecycle with DDL support, which is strong for a database server. Minor gaps remain: no index listing, no cancellation/rollback or transaction-status tool, and no way to inspect or list pending approval requests, which an agent would likely want.
Maintenance
Related MCP Connectors
Guard AI agents' PostgreSQL/MySQL access via MCP: SQL audit, auth, masking, write approval
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Work with your database from AI tools: ask, export, approved changes, and scheduled jobs.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Related MCP Servers
- 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
- AlicenseAqualityDmaintenanceEnables AI assistants to safely query MySQL databases with read-only access, featuring SQL injection protection, connection pooling, and automatic query limits for secure database exploration.4124 npmMIT
- AlicenseNot gradedqualityNot gradedmaintenanceEnables AI assistants to securely interact with MySQL databases through tools for query execution, schema inspection, and transaction management. It features built-in safety controls like row limits and query validation to ensure safe and standardized database access.798 npm-
- AlicenseAqualityCmaintenanceEnables AI assistants to inspect and query a MySQL database through safe, structured tools, including schema discovery and read-only queries.9104 npmMIT