MySQL MCP Server
Supports connections to DigitalOcean managed MySQL databases for remote database operations.
Enables connections to Google Cloud SQL MySQL instances for database operations and management.
Supports OAuth 2.1 authentication integration with Keycloak for enterprise-grade security with granular access control scopes and RFC-compliant identity provider integration.
Provides comprehensive MySQL database management with 191 specialized tools for CRUD operations, JSON functions, spatial/GIS, schema management, performance tuning, replication monitoring, and cluster administration. Includes 18 observability resources for real-time metrics and InnoDB diagnostics.
Provides connectivity to PlanetScale MySQL databases with SSL support for serverless database operations.
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., "@MySQL MCP Server show me the top 5 customers by total purchase amount"
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.
MySQL MCP Server (mysql-mcp)
π Full Documentation (Wiki) β’ Changelog β’ Security β’ Release Article
π Value Proposition
Integrate your AI agents with a production-ready MySQL environment. Deploy MCP v2 stateless architecture via HTTP transport. Optimize token efficiency via Code Mode. Secure your database with OAuth 2.1.
Related MCP server: MCP MySQL Server
π― Leverage Core Benefits
Feature | Description |
Specialized Tools | Access specialized tools for core CRUD, JSON, spatial data, document stores, and clusters. |
Resources | Monitor schema, performance metrics, process lists, replication status, and InnoDB diagnostics in real-time. |
AI-Powered Prompts | Execute guided workflows for query building, schema design, performance tuning, and infrastructure setup. |
Code Mode | Reduce LLM token consumption by consolidating operations inside a secure, sandboxed V8 isolate. |
Token-Optimized Payloads | Maximize token efficiency. Use optional flags to reduce response size for large payloads. |
OAuth 2.1 Security | Enforce granular access control with RFC compliance, strict scopes, and Keycloak integration. |
Smart Tool Filtering | Use tool groups and shortcuts to stay within IDE tool limits. |
Streamable & Stateless HTTP | Support MCP v2 streamable HTTP and stateless HTTP deployments. |
Connection Pooling | Leverage built-in connection pooling for efficient, highly concurrent database access. |
Ecosystem Integrations | Manage MySQL Router, ProxySQL, and MySQL Shell utilities directly from your agent. |
Advanced Encryption | Enforce TLS/SSL connections. Manage data masking, encryption monitoring, and compliance effortlessly. |
Production-Ready Security | Prevent SQL injection with parameterized queries. Rely on strict input validation and audit logging. |
Deterministic Errors | Receive structured responses with actionable suggestions. Eliminate silent failures and raw exceptions. |
Observability | Export Prometheus metrics. Track container logs with Dozzle and audit trails with Grafana Alloy/Loki. |
Strict TypeScript | Rely on strict TypeScript backed by robust test suites. |
MCP v2 Compliant | Fully support the MCP v2 specification. This includes stateless routing, caching, safety hints, and notifications. |
π€ Automate Tasks with Guided Workflows
This server includes intelligent prompts for guided workflows:
Prompt | Description |
| Complete tool index with categories |
| Quick query execution shortcut |
| Quick schema exploration |
| Complete observability stack setup guide (Datadog, etc.) |
Note: This is a subset of available prompts. Use
mysql_tool_indexto discover the full list of guided workflows.
π Improve Observability with Resources
This server exposes a comprehensive set of resources for database observability and telemetry:
Resource | Category | Description |
| Core | Full database schema |
| Core | Table listing with metadata |
| Core | Server configuration variables |
| Core | Server status metrics |
| Core | Active connections and queries |
| Core | Connection pool statistics |
| Extended | Server version, features, and tool categories |
| Extended | Comprehensive database health status |
| Extended | Query performance metrics |
| Extended | Index usage and statistics |
| Extended | Replication status and lag |
| Extended | InnoDB buffer pool and engine metrics |
| Domain | Event Scheduler status and scheduled events |
| Domain | sys schema diagnostics summary |
| Domain | InnoDB lock contention detection |
| Domain | Group Replication / InnoDB Cluster status |
| Domain | Spatial columns and indexes |
| Domain | Document Store collections |
| Analytics | Business insights memo from mysql_append_insight |
| Observability | In-memory token usage, latency, and request metrics |
| Observability | Forensic trail and snapshot of system errors |
| Documentation | Critical gotchas and high-level API reference |
| Documentation | Dynamic group-specific tool reference (e.g., |
π Deploy Your AI Database
Meet Prerequisites
Node.js >= 24.0.0 (See
.node-versionfor the pinned local development version)Bun (for executing repository automation scripts)
MySQL server
pnpm
Install the Server
Install via NPM / PNPM
pnpm add -g @neverinfamous/mysql-mcpRun the server:
mysql-mcp --transport stdio --mysql "mysql://mcp_user:secure_password@localhost:3306/testdb"Or use npx without installing:
npx @neverinfamous/mysql-mcp --transport stdio --mysql "mysql://mcp_user:secure_password@localhost:3306/testdb"Run with Docker
Note on Namespaces: The Docker image uses the
writenotenownamespace. The GitHub repo usesneverinfamous.
Linux Users: For
host.docker.internalon Linux, run the container with--add-host host.docker.internal:host-gateway.
docker run -i --rm -v ./data:/app/data -v ./logs:/var/log/mysql-mcp writenotenow/mysql-mcp:latest \
--transport stdio \
--allowed-io-roots /app/data \
--mysql "mysql://mcp_user:secure_password@host.docker.internal:3306/testdb"Enable Observability via Docker Compose
Launch the full observability stack using the included template. This includes Datadog, OpenTelemetry, Prometheus, and Grafana. This spins up the MCP server, MySQL database, Redis, and observability sidecars:
cd examples/basic-mysql-datadog
cp .env.example .env
docker compose up -dGrafana: Available at
http://localhost:3001(Dashboard pre-loaded).Prometheus: Available at
http://localhost:9090.MCP Server: Available at
http://localhost:3000.
Follow Datadog & OpenTelemetry Observability Rules
Datadog Constraints:
Authentication: Use
pupCLI for authentication.Autodiscovery: Avoid duplicate autodiscovery configurations. Add standard tracking labels (
tags.datadoghq.com/env,tags.datadoghq.com/service,tags.datadoghq.com/version) to your containers.WSL2 Hardening Limits: Enforce
stop_grace_period: 30s,mem_limit: 1536m, and OpenMetrics timeouts of10s.Host Configuration: Use
DD_HOSTNAMEand native/etc/docker/daemon.jsoncgroup configurations ("default-cgroupns-mode": "host"). DisableDD_EXTRA_PERFORMANCE_METRICS.Windows File Tailing: Be warned that Windows
inotifytailing issues may occur with Docker/WSL2 log mapping.
OpenTelemetry Rules:
Semantic Conventions: Enforce
gen_ai.*semantics.Instrumentation: Use auto-instrumentation when possible.
Context Propagation: Ensure
traceparentandtracestatepropagation.Processing & Logging: Utilize batch processors and ensure logs are formatted as JSON logs.
Audit Architecture & Exporter Healthcheck:
The primary MCP server writes execution traces to
mcp-audit.jsonlvia the--audit-logflag.The metrics exporter runs as an independent sidecar process. It reads from
mcp-audit.jsonlusing theAUDIT_LOG_PATHenvironment variable to compute metrics.The exporter isolates its own internal logs by setting its
--audit-logflag toexporter-audit.jsonl.The metrics server and exporter share a single process. Both operate on port
3000. This prevents port contention.Exporter Healthcheck:
wget --spider -q http://127.0.0.1:3000/metrics
Build From Source
git clone https://github.com/neverinfamous/mysql-mcp.git
cd mysql-mcp
pnpm install
pnpm run build
node dist/cli.js --transport stdio --mysql "mysql://mcp_user:secure_password@localhost:3306/testdb"ποΈ Use Infrastructure Templates
We provide production-ready Docker Compose templates in the examples/ directory. Use these to spin up test environments quickly. These templates include full Datadog observability out-of-the-box (Metrics, APM, and Logs).
Basic Template: A lightweight, single-node MySQL setup. Perfect for quick starts.
Enterprise HA Template: A highly-available InnoDB Cluster with MySQL Router and ProxySQL. Perfect for staging or production replicas.
Full Observability Ecosystem: A complete enterprise monitoring stack with Datadog, Prometheus, Grafana, Loki, and Alloy. See the Observability Wiki for deep-dive metrics configuration.
See the README in each directory for quick start instructions.
β‘ Optimize Token Usage with Code Mode
Code Mode (mysql_execute_code) reduces token usage by consolidating operations in a secure sandbox.
Code executes securely in a C++ V8 isolate sandbox. It enforces strict heap limits and synchronous termination. Native wrappers map all API calls across the boundary. This guarantees defense-in-depth and fleet-standard restrictions:
Enforce Engine-Level Restrictions
β Strict V8 Isolate Boundary β Code executes within a physically separate V8 isolate. It ensures native objects and prototypes cannot cross the boundary.
β Memory & CPU Constraints β enforced at the C++ level. This includes synchronous timeouts and strict heap limits.
β API Bindings via Reference β Injects MySQL methods securely using
ivm.Referencewrappers.
Validate Code Statically
β Comprehensive blocked patterns β regex rules block
require(),import(),eval(),Function,process, and__proto__. They also block filesystem/network access and system commands.β Unicode & Comment Sanitization β Strips comments and performs NFKC normalization to prevent regex evasion.
β Configurable code input limit β prevents payload-based resource exhaustion.
Protect the Runtime
β RPC Quotas β Caps RPC API calls per execution. This prevents unbounded loops.
β Execution timeout β enforces timeouts to prevent resource exhaustion. Configurable via schema
timeout.β Egress boundary enforcement β streaming
JSON.stringifyserialization aborts mid-flight when exceeding size caps.β Rate limiting β Enforces per-client limits (CODEMODE_RATE_LIMIT_MAX). Uses Redis with in-memory fallbacks.
β Readonly enforcement β Returns structured errors instead of executing write methods when readonly: true.
β Audit logging β Logs every execution with UUID, client ID, metrics, and redacted code preview.
β Admin scope β Code Mode requires
adminscope when OAuth is enabled.β Full API access β Exposes all tool groups via the
mysql.*namespace.
β‘ Run Only Code Mode
Run with only Code Mode enabled. A single tool provides full capability access. See Option 1: Code Mode below for the recommended IDE configuration.
This exposes just mysql_execute_code. Agents write JavaScript against the typed SDK. They compose queries and chain operations across tool groups. They return exactly the needed data in one execution. This mirrors standard serverless edge execution patterns. It ensures fixed token costs.
Maximize Token Savings: Instruct your AI agent to prefer Code Mode.
"When using mysql-mcp, prefer mysql_execute_code (Code Mode) for multi-step operations. This minimizes token usage."
For maximum savings, run Code Mode as your only tool using --tool-filter codemode. See the Code Mode wiki for full API documentation.
π Enable Remote Access via Streamable & Stateless HTTP
When to use HTTP mode: Deploy
mysql-mcpas a standalone server. Multiple clients can connect remotely. Usestdiomode for local development.
Use cases for HTTP mode:
Run the server in a network-accessible Docker container
Deploy to cloud platforms (AWS, GCP, Azure)
Enable OAuth 2.1 authentication for enterprise security
Share one database connection across multiple AI clients
Use the HTTP transport for remote access:
npx -y @neverinfamous/mysql-mcp \
--transport http \
--server-host 0.0.0.0 \
--port 3000 \
--allowed-io-roots /path/to/data \
--mysql "mysql://mcp_user:secure_password@localhost:3306/testdb"Docker:
docker run --rm -p 3000:3000 \
-v ./data:/app/data \
-v ./logs:/var/log/mysql-mcp \
-e MCP_AUTH_TOKEN=my-secret-token \
writenotenow/mysql-mcp:latest \
--transport http --server-host 0.0.0.0 --port 3000 --allowed-io-roots /app/data --mysql "mysql://mcp_user:secure_password@host.docker.internal:3306/testdb"The server supports Streamable HTTP and Stateless HTTP deployments. Both stateful and stateless clients can connect:
Use Streamable HTTP (Recommended)
Modern MCP protocol β single endpoint, session-based:
Method | Endpoint | Purpose |
|
| JSON-RPC requests (initialize, tools/list, etc.) |
|
| SSE stream for server notifications |
|
| Session termination |
Rate Limit: HTTP transport is rate limited per IP (default 100/min, configurable via
MCP_RATE_LIMIT_MAX). Distribute limits across deployments via Redis using graceful in-memory fallbacks.
The server manages sessions via the Mcp-Session-Id header.
Run Statelessly
Use stateless deployments where sessions are not needed:
node dist/cli.js --transport http --server-host 0.0.0.0 --port 3000 --allowed-io-roots /path/to/data --stateless --mysql "mysql://mcp_user:secure_password@..."In stateless mode: GET /mcp returns 405. DELETE /mcp returns 204. Each POST /mcp instantiates a stateless HTTP transport.
Access Utility Endpoints
Method | Endpoint | Purpose |
|
| Health check (bypasses rate limiting, always available for monitoring) |
|
| Exports Prometheus metrics (available when |
π Protect Your Data with Authentication
mysql-mcp supports two authentication mechanisms for HTTP transport:
Authenticate with Bearer Token (--auth-token)
Use lightweight authentication for development:
node dist/cli.js --transport http --server-host 0.0.0.0 --port 3000 --allowed-io-roots /path/to/data --auth-token my-secret --mysql "mysql://mcp_user:secure_password@..."
# Or via environment variable
export MCP_AUTH_TOKEN=my-secret
node dist/cli.js --transport http --server-host 0.0.0.0 --port 3000 --allowed-io-roots /path/to/data --mysql "mysql://mcp_user:secure_password@..."Clients must include Authorization: Bearer my-secret on all requests. /health and / are exempt. Unauthenticated requests receive 401. Responses include WWW-Authenticate: Bearer headers per RFC 6750.
Authenticate with OAuth 2.1
Use full OAuth 2.1 for production deployments:
node dist/cli.js \
--transport http \
--server-host 0.0.0.0 \
--port 3000 \
--allowed-io-roots /path/to/data \
--mysql "mysql://mcp_user:secure_password@localhost:3306/testdb" \
--oauth-enabled \
--oauth-issuer https://localhost:8080/realms/mysql-mcp \
--oauth-audience mysql-mcp-clientAdditional flags:
--oauth-jwks-uri <url>(auto-discovered if omitted),--oauth-clock-tolerance <seconds>(default: 60).
Enforce OAuth Scopes
Enforce access control using OAuth scopes:
Scope | Access Level |
| Read-only queries (SELECT, EXPLAIN) |
| Read + write operations |
| Full administrative access |
| Grants all access |
| Access to specific database |
| Access to specific table |
Ensure RFC Compliance
This implementation follows full OAuth 2.1 for production multi-tenant deployments:
β RFC 9728 Protected Resource Metadata (
/.well-known/oauth-protected-resource)β RFC 8414 Authorization Server Discovery with caching
β RFC 7591 OAuth 2.1 Dynamic Client Registration
β JWT validation with JWKS support (TTL: 1 hour)
β MySQL-specific scopes:
read,write,admin,full,db:{name},table:{db}:{table}β Per-tool scope enforcement via
AsyncLocalStoragecontext threading
Note for Keycloak users: Add an Audience mapper to your client. This includes the correct
audclaim. (Client β Client scopes β dedicated scope β Add mapper β Audience)
Per-tool scope enforcement: The server enforces scopes at the tool level. Each tool group requires a specific scope. When OAuth is enabled, every tool invocation checks the calling token's scopes before execution. The server skips scope checks entirely when OAuth is not configured.
HTTP without authentication: Exposing --transport http without authentication grants unrestricted access. Always enable authentication for production HTTP deployments. See SECURITY.md for details.
β‘ Simplify AI Integration with Client Configs
Install Agent Skills
For optimal AI performance, mysql-mcp includes specialized agent instructions in the skills/ directory. These skills teach AI coding assistants (like Cline, Antigravity, or Copilot) how to effectively use the server's capabilities, tool filters, and Code Mode.
To install: Copy the .md files from the skills/ directory into your AI assistant's designated skills or custom instructions folder (e.g., .cursor/rules/, .agents/skills/, etc.). This enables your agent to autonomously navigate the mysql-mcp ecosystem without hallucinating usage patterns.
Configure IDE Settings
Add a configuration to your IDE's MCP settings file:
Option 1: Code Mode (Maximum Token Savings, π Recommended)
Best for: General MySQL AI agent tasks. Exposes mysql_execute_code for full sandboxed toolset access.
{
"mcpServers": {
"mysql-mcp": {
"command": "npx",
"args": [
"-y",
"@neverinfamous/mysql-mcp",
"--transport",
"stdio",
"--tool-filter",
"codemode"
],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "mcp_user",
"MYSQL_PASSWORD": "secure_password",
"MYSQL_DATABASE": "testdb"
},
"timeout": 600
}
}
}Option 2: Cluster (Tools for InnoDB Cluster Monitoring)
Best for: Monitoring InnoDB Cluster, Group Replication status, and cluster topology.
β οΈ Prerequisites:
InnoDB Cluster must be configured and running with Group Replication enabled
Connect to a cluster node directly (e.g.,
localhost:3307) β NOT a standalone MySQL instanceUse
cluster_adminorrootuser with appropriate privilegesSee MySQL Ecosystem Setup Guide for cluster setup instructions
{
"mcpServers": {
"mysql-mcp-cluster": {
"command": "npx",
"args": [
"-y",
"@neverinfamous/mysql-mcp",
"--transport",
"stdio",
"--tool-filter",
"cluster"
],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3307",
"MYSQL_USER": "cluster_admin",
"MYSQL_PASSWORD": "cluster_password",
"MYSQL_DATABASE": "mysql"
},
"timeout": 600
}
}
}Option 3: Ecosystem (Tools for InnoDB Cluster Deployments)
Best for: MySQL Router, ProxySQL, MySQL Shell, and InnoDB Cluster deployments.
β οΈ Prerequisites:
InnoDB Cluster requires a running cluster. This enables Router REST API authentication.
Router REST API uses self-signed HTTPS certificates. Set
MYSQL_ROUTER_INSECURE=trueto bypass verification.X Protocol: InnoDB Cluster includes the MySQL X Plugin by default. Set
MYSQL_XPORTto the Router's X Protocol port (e.g.,6448). This enablesmysqlsh_import_jsonanddocstoretoolsSee MySQL Ecosystem Setup Guide for detailed instructions
{
"mcpServers": {
"mysql-mcp-ecosystem": {
"command": "npx",
"args": [
"-y",
"@neverinfamous/mysql-mcp",
"--transport",
"stdio",
"--tool-filter",
"ecosystem"
],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3307",
"MYSQL_XPORT": "6448",
"MYSQL_USER": "cluster_admin",
"MYSQL_PASSWORD": "cluster_password",
"MYSQL_DATABASE": "testdb",
"MYSQL_ROUTER_URL": "https://localhost:8443",
"MYSQL_ROUTER_USER": "rest_api",
"MYSQL_ROUTER_PASSWORD": "router_password",
"MYSQL_ROUTER_INSECURE": "true",
"PROXYSQL_HOST": "localhost",
"PROXYSQL_PORT": "6032",
"PROXYSQL_USER": "radmin",
"PROXYSQL_PASSWORD": "radmin",
"MYSQLSH_PATH": "mysqlsh"
},
"timeout": 600
}
}
}Note: Port
6448is the standard MySQL Router X Protocol port.
Customization Notes:
Replace
/path/to/mysql-mcp/with your actual installation path. This is only needed when building from source. It is also required when running local files directly.Update credentials with your actual values
For Windows: Use forward slashes (e.g.,
C:/mysql-mcp/dist/cli.js) or escape backslashesFor Windows MySQL Shell:
"MYSQLSH_PATH": "C:\\Program Files\\MySQL\\MySQL Shell\\bin\\mysqlsh.exe"Router Authentication: Router REST API authenticates against the InnoDB Cluster metadata. The cluster must be running for authentication to work.
Cluster Resource: Connect to an InnoDB Cluster node. This unlocks the
mysql://clusterresource
π See the Configuration Wiki for more configuration options.
π Integrate Any MySQL Environment
Scenario | Host to Use | Example Connection String |
MySQL on host machine |
|
|
MySQL in Docker | Container name or network |
|
Remote/Cloud MySQL | Hostname or IP |
|
Connect to MySQL on Host Machine
For native local installations, use localhost. If running the server in Docker, use host.docker.internal:
[
"--mysql",
"mysql://mcp_user:secure_password@host.docker.internal:3306/testdb"
]Connect to MySQL in Another Docker Container
For Docker setups, use host.docker.internal. For Docker Compose, use the mysql service name.
Create a network and run MySQL:
docker network create mynet
docker run -d --name mysql-db --network mynet -e MYSQL_ROOT_PASSWORD=pass mysql:latestRun MCP server on the same network:
docker run -i --rm --network mynet writenotenow/mysql-mcp:latest \
--transport stdio --mysql "mysql://mcp_user:secure_password@mysql-db:3306/testdb"Connect to Remote/Cloud MySQL (RDS, Cloud SQL, etc.)
Use the remote hostname directly:
[
"--mysql",
"mysql://mcp_user:secure_password@your-instance.region.rds.amazonaws.com:3306/testdb"
]Provider | Example Hostname |
AWS RDS |
|
Google Cloud SQL |
|
Azure MySQL |
|
PlanetScale |
|
DigitalOcean |
|
Tip: Ensure remote MySQL servers allow connections from Docker's IP range. Verify firewalls/security groups permit port 3306.
π οΈ Optimize Limits with Tool Filtering
AI IDEs like Cursor have tool limits. Filter tools to ensure compatibility with IDE limits. We offer many specialized tools. All shortcuts and tool groups include Code Mode by default. To exclude it, add -codemode to your filter: --tool-filter core,json,-codemode
Discover Filtering Options
The --tool-filter argument accepts shortcuts, groups, or tool names β mix and match freely:
Filter Pattern | Example | Description |
Shortcut only |
| Use a predefined bundle |
Groups only |
| Combine individual groups |
Shortcut + Group |
| Extend a shortcut |
Shortcut - Tool |
| Remove specific tools |
Use Predefined Shortcuts
Shortcut | Use Case | What's Included |
| Standard Package | core, json, transactions, text, codemode |
| Minimal footprint | core, transactions, codemode |
| Power Developer | core, schema, performance, fulltext, transactions, codemode |
| Developer Analytics | core, stats, performance, codemode |
| AI Data NoSQL | core, json, docstore, codemode |
| AI Search | core, text, fulltext, vector, codemode |
| AI Spatial Analyst | core, spatial, transactions, codemode |
| AI Vector Analyst | core, vector, fulltext, codemode |
| DBA Monitoring | core, monitoring, performance, sysschema, optimization, codemode |
| DBA Management | core, admin, backup, replication, partitioning, events, codemode |
| DBA Security | core, security, roles, transactions, codemode |
| DBA Schema | core, schema, introspection, migration, codemode |
| Base Relational | core, transactions, text, schema, codemode |
| Base Analytics | stats, events, codemode |
| Base NoSQL | docstore, spatial, vector, codemode |
| External Tools | cluster, proxysql, router, shell, codemode |
Filter by Tool Groups
Note: Code Mode (
mysql_execute_code) is automatically added to all groups.
Group | Description |
| Code Mode (sandboxed code execution) π Recommended |
| Read/write queries, tables, indexes |
| BEGIN, COMMIT, ROLLBACK, savepoints |
| JSON functions, merge, diff, stats |
| REGEXP, LIKE, SOUNDEX |
| Natural language & boolean search |
| EXPLAIN, query analysis, anomaly detection |
| Index hints, database-wide audits, EXPLAIN recommendations |
| OPTIMIZE, ANALYZE, CHECK, insights |
| PROCESSLIST, status variables |
| Export, import, mysqldump, audit backups |
| Master/slave, binlog |
| Partition management |
| Views, procedures, triggers, constraints |
| Dependency graphs, cascade simulation, snapshots |
| Schema versioning, apply, rollback, history |
| MySQL Shell utilities |
| Event Scheduler management |
| sys schema diagnostics |
| Statistical analysis, window functions, sampling |
| Spatial/GIS operations |
| Audit, SSL, encryption, masking |
| MySQL role management |
| Document Store collections |
| Group Replication, InnoDB Cluster |
| ProxySQL management |
| MySQL Router REST API |
| Vector embeddings, KNN search, hybrid search |
Review Syntax Reference
Legacy Syntax (still supported):
If you start with a negative filter (e.g., -ecosystem), it enables all tools first. It then subtracts the specified tools.
Prefix | Target | Example | Effect |
(none) | Shortcut |
| Whitelist Mode: Enable ONLY this shortcut |
(none) | Group |
| Whitelist Mode: Enable ONLY this group |
(none) | Tool |
| Whitelist Mode: Enable ONLY this tool |
| Group |
| Add tools from this group to current set |
| Group |
| Remove tools in this group from current set |
| Tool |
| Add one specific tool |
| Tool |
| Remove one specific tool |
Customize Tool Selection
List tool names without + prefix to create a custom whitelist.
The easiest way to filter is using whitelist mode. Simply specify the shortcut you want. Everything else is automatically disabled.
# Enable specific tools (whitelist mode)
--tool-filter "mysql_read_query,mysql_write_query,mysql_list_tables"
# Mix tools from different groups
--tool-filter "mysql_read_query,mysql_explain,mysql_json_extract"
# Combine with a shortcut or group
--tool-filter "starter,+mysql_spatial_distance,+mysql_json_diff"Use this for automated clients requiring a minimal capability set.
π See the Tool Filtering Wiki for advanced examples.
π§ Customize with Advanced Configuration
See the configuration templates in the project root for setup details.
For specialized setups, see these Wiki pages:
Topic | Description |
Configure Router REST API access for InnoDB Cluster | |
Configure ProxySQL admin interface access | |
Configure MySQL Shell for dump/load operations |
β‘ Maximize Server Performance
The server caches schema metadata to reduce repeated queries during tool/resource invocations.
Review Performance Benchmarks
The server handles millions of ops/sec across core execution paths. This ensures minimal latency and maximum throughput. Every component is tuned for enterprise-scale workloads. Enjoy sub-millisecond sandbox cold starts and optimized reverse lookups.
Benchmark Baselines:
parseToolFilter: ~32,000-62,000 ops/sec
CodeModeSandbox.create cold start: ~2.78M ops/sec
Sandbox dispose: ~2.37M ops/sec
SandboxPool init: ~109k ops/sec
Set.has tool check: ~4.4M ops/sec
Map.get reverse lookup: ~4.5M ops/sec
Map.get URI match: ~5.1M ops/sec
validateCode safe short: ~173k ops/sec
validateCode blocked: ~298k ops/sec
checkRateLimit: ~205k ops/sec
sanitizeResult small payload: ~1.49M ops/sec
prompt schema parse: ~1.3M ops/sec
Tip: Lower
METADATA_CACHE_TTL_MSfor development (e.g.,5000). Increase it for production with stable schemas (e.g.,300000= 5 min).
Payload optimization: Tools support
summary: trueandlimitparameters. These condense large payloads.
ποΈ Master Server Configuration
Configure CLI Options
Note: Items marked with
βin the CLI flag column are configured exclusively via environment variables.
Option | Environment Variable | Description |
| β | Configuration file path (.yaml or .json) |
| β | Dump current configuration to stdout and exit |
| β | Show version number |
| β | Show help |
| β | Output in JSON format |
| β | Transport type: stdio, http, sse (default: stdio) |
|
| HTTP port for http transport |
|
| Host to bind HTTP transport to (default: localhost) |
| β | MySQL connection string |
|
| MySQL host |
|
| MySQL port |
|
| MySQL username |
|
| MySQL password |
|
| MySQL database name |
|
| Connection pool size (default: 10) |
| β | Connection acquire timeout in ms (default: 30000) |
| β | Queue limit for waiting requests (default: 0) |
|
| Tool filter string |
| β | Server name |
|
| Simple bearer token for HTTP authentication |
| β | Enable stateless HTTP mode |
|
| Trust X-Forwarded-For for client IP |
|
| Enable HTTP Strict Transport Security |
|
| Metrics export format (e.g., prometheus) |
|
| Log level: debug, info, warn, error |
|
| JSON array or comma list of allowed paths for all file I/O operations |
|
| File path for writing audit logs (write-path) |
β |
| File path for the exporter to read audit logs (read-path) |
| β | Enable pre-mutation snapshots |
| β | Include read-scope tool calls in the audit log |
| β | Redact sensitive arguments in the audit log |
| β | Max file size before rotation (bytes) |
| β | Include sample data in pre-mutation snapshots |
| β | Max table size in bytes for data capture |
|
| Enable OAuth 2.1 authentication |
|
| Authorization server URL |
|
| Expected token audience |
|
| JWKS URI (auto-discovered) |
|
| Clock tolerance in seconds |
β |
| MySQL Router URL |
β |
| MySQL Router user |
β |
| MySQL Router password |
β |
| Bypass Router TLS verification |
β |
| MySQL Router REST API version (default: /api/20190715) |
β |
| ProxySQL host |
β |
| ProxySQL port |
β |
| ProxySQL user |
β |
| ProxySQL password |
β |
| Path to MySQL Shell executable |
β |
| MySQL X Protocol port (default 33060) |
β |
| Code Mode isolation level (controls V8 memory limits and strictness) |
β |
| Max Code Mode result payload in bytes |
β |
| Cache TTL for schema metadata |
β |
| Redis connection URL (used for rate limiting) |
β |
| Max HTTP requests per minute per IP (default 100) |
β |
| Max Code Mode executions per minute (default 60) |
Priority: When both
--auth-tokenand--oauth-enabledare set, OAuth 2.1 takes precedence. If neither is configured, the server warns and runs without authentication.
Enforce Scopes
See Enforce OAuth Scopes.
π See the OAuth Wiki for Keycloak setup and detailed configuration.
π» Accelerate Development by Contributing
See Build From Source above for setup. After cloning:
pnpm run lint
pnpm run typecheck
pnpm test
pnpm run test:e2e # Run individually to avoid timeoutsDebug with MCP Inspector
Use MCP Inspector to visually test and debug mysql-mcp:
Build the server first:
pnpm run buildLaunch Inspector with mysql-mcp:
npx @modelcontextprotocol/inspector node dist/cli.js \
--transport stdio \
--mysql mysql://mcp_user:secure_password@localhost:3306/testdbOpen http://localhost:5173 to browse all tools, resources, and prompts interactively.
CLI mode for scripting:
List all tools:
npx @modelcontextprotocol/inspector --cli node dist/cli.js \
--transport stdio --mysql mysql://... \
--method tools/listCall a specific tool:
npx @modelcontextprotocol/inspector --cli node dist/cli.js \
--transport stdio --mysql mysql://... \
--method tools/call --tool-name mysql_list_tablesπ See the MCP Inspector Wiki for detailed usage.
Run Unit Tests
The project maintains high test coverage using Vitest.
pnpm testRun coverage report:
pnpm run test:coverageTest Infrastructure:
Centralized mock factories in
src/__tests__/mocks/All test files use shared mocks for consistency
Tests run without database connection (fully mocked)
Unit tests are mocked. The E2E and stress suites require a live database connection.
Execute Benchmarks
The project includes a performance benchmarking suite. It tracks efficiency of critical paths. These include Code Mode sandbox initialization, tool filtering, and URI routing.
pnpm run benchContributing Guidelines β’ Security Policy β’ MIT License β’ Code of Conduct
Available Tools
43 toolsmysql_check_versionMySQL Check VersionARead-only
Read the current _version of a specific row for optimistic concurrency control.
Inputs: id, name, rowId, table, +2 more. Returns: code, data, error, details, +5 more
mysql_collation_convertMySQL Collation ConvertCRead-only
Convert column values to a different character set or collation.
Inputs: col, name, limit, table, +8 more. Returns: code, data, error, details, +5 more
mysql_concatMySQL CONCATARead-only
Concatenate multiple columns with an optional separator.
Inputs: name, alias, limit, table, +6 more. Returns: code, data, error, details, +5 more
mysql_conditional_updateMySQL Conditional UpdateA
Update a row only if its _version matches expectedVersion. Prevents lost updates in multi-agent environments.
Inputs: id, data, name, rowId, +8 more. Returns: code, data, error, details, +5 more
mysql_create_indexMySQL Create IndexA
Create an index on a table. Supports BTREE, HASH, FULLTEXT, and SPATIAL index types.
Inputs: name, type, table, unique, +4 more. Returns: code, data, error, details, +5 more
mysql_create_tableMySQL Create TableA
Create a new table with specified columns, engine, and charset.
Inputs: name, table, engine, charset, +5 more. Returns: code, data, error, details, +5 more
mysql_describe_tableMySQL Describe TableARead-only
Get detailed information about a table's structure including columns, types, and constraints.
Inputs: name, table, tableName. Returns: code, data, error, details, +5 more
mysql_disable_versioningMySQL Disable VersioningB
Disable optimistic concurrency control (OCC) on a table. Drops the _version column and its trigger.
Inputs: name, table, ifExists, tableName. Returns: code, data, error, details, +5 more
mysql_drop_tableMySQL Drop TableBDestructive
Drop (delete) a table from the database.
Inputs: name, table, ifExists, tableName. Returns: code, data, error, details, +5 more
mysql_enable_versioningMySQL Enable VersioningA
Enable optimistic concurrency control (OCC) on a table. Adds a _version column and an auto-increment trigger.
Inputs: name, table, tableName. Returns: code, data, error, details, +5 more
mysql_execute_codeMySQL Execute CodeADestructive
Execute TypeScript/JavaScript code in a sandboxed environment with access to all MySQL tools via the mysql.* API.
Available API groups:
mysql.core: readQuery, writeQuery, listTables, describeTable, createTable, createIndex (8 methods)
mysql.transactions: begin, commit, rollback, savepoint, execute (7 methods)
mysql.json: extract, set, insert, remove, contains, keys, merge, diff, stats (17 methods)
mysql.text: regexpMatch, likeSearch, soundex, substring, concat, collationConvert (6 methods)
mysql.fulltext: fulltextSearch, fulltextCreate, fulltextBoolean, fulltextExpand (5 methods)
mysql.performance: explain, explainAnalyze, slowQueries, bufferPoolStats, tableStats (8 methods)
mysql.optimization: indexRecommendation, queryRewrite, forceIndex, optimizerTrace (4 methods)
mysql.admin: optimizeTable, analyzeTable, checkTable, repairTable, flushTables, killQuery, serverConfig, appendInsight, auditSearch (9 methods)
mysql.monitoring: showProcesslist, showStatus, showVariables, innodbStatus, poolStats (7 methods)
mysql.backup: createDump, exportTable, importData, restoreDump (4 methods)
mysql.replication: masterStatus, slaveStatus, binlogEvents, gtidStatus, replicationLag (5 methods)
mysql.partitioning: partitionInfo, addPartition, dropPartition, reorganizePartition (4 methods)
mysql.schema: listSchemas, createView, listFunctions, listTriggers (10 methods)
mysql.events: eventCreate, eventAlter, eventDrop, eventList, schedulerStatus (6 methods)
mysql.sysschema: sysSchemaStats, sysStatementSummary, sysIoSummary (8 methods)
mysql.stats: descriptive, percentiles, correlation, regression, timeSeries, histogram (8 methods)
mysql.spatial: distance, distanceSphere, point, polygon, buffer (12 methods)
mysql.security: sslStatus, userPrivileges, audit, sensitiveTables (9 methods)
mysql.cluster: clusterStatus, grStatus, grMembers, clusterTopology (10 methods)
mysql.roles: roleCreate, roleGrant, roleAssign, roleList (8 methods)
mysql.docstore: docCreateCollection, docFind, docAdd, docModify (9 methods)
mysql.router: routerStatus, routerRoutes, routerRouteHealth (9 methods)
Example:
const tables = await mysql.core.listTables();
const results = [];
for (const t of tables.tables) {
const count = await mysql.core.readQuery(`SELECT COUNT(*) as n FROM \`${t.name}\``);
results.push({ table: t.name, rows: count.rows[0].n });
}
return results;Inputs: js, sql, code, eval, +7 more. Returns: code, hint, logs, error, +7 more
mysql_get_indexesMySQL Get IndexesARead-only
Get all indexes for a table including type, columns, and cardinality.
Inputs: name, table, tableName. Returns: code, data, error, details, +5 more
mysql_json_array_appendMySQL JSON Array AppendC
Append a value to a JSON array at the specified path.
Inputs: col, sql, val, name, +12 more. Returns: code, data, error, details, +5 more
mysql_json_containsMySQL JSON ContainsBRead-only
Find rows where JSON column contains a specified value.
Inputs: col, sql, name, path, +15 more. Returns: code, data, error, details, +5 more
mysql_json_diffMySQL JSON DiffARead-only
Compare two JSON documents and identify differences.
Inputs: doc1, doc2, json1, json2, +2 more. Returns: code, data, error, details, +5 more
mysql_json_extractMySQL JSON ExtractCRead-only
Extract values from JSON columns using JSON path expressions.
Inputs: col, sql, name, path, +10 more. Returns: code, data, error, details, +5 more
mysql_json_getMySQL JSON GetCRead-only
Simple JSON value extraction by row ID.
Inputs: col, sql, name, path, +9 more. Returns: code, data, error, details, +5 more
mysql_json_index_suggestMySQL JSON Index SuggestBRead-only
Suggest functional indexes for frequently accessed JSON paths.
Inputs: col, name, table, column, +2 more. Returns: code, data, error, details, +5 more
mysql_json_insertMySQL JSON InsertA
Insert values into JSON columns only if the path does not exist.
Inputs: col, sql, val, name, +12 more. Returns: code, data, error, details, +5 more
mysql_json_keysMySQL JSON KeysARead-only
Get the keys of a JSON object at the specified path.
Inputs: col, sql, name, path, +10 more. Returns: code, data, error, details, +5 more
mysql_json_mergeMySQL JSON MergeARead-only
Merge two JSON documents using JSON_MERGE_PATCH or JSON_MERGE_PRESERVE.
Inputs: doc1, doc2, mode, json1, +4 more. Returns: code, data, error, details, +5 more
mysql_json_normalizeMySQL JSON NormalizeARead-only
Normalize JSON column structure by extracting all unique keys across documents.
Inputs: col, name, limit, rowId, +6 more. Returns: code, data, error, details, +5 more
mysql_json_removeMySQL JSON RemoveC
Remove values from JSON columns at specified paths.
Inputs: col, key, sql, keys, +13 more. Returns: code, data, error, details, +5 more
mysql_json_replaceMySQL JSON ReplaceB
Replace values in JSON columns only if the path exists.
Inputs: col, sql, val, name, +12 more. Returns: code, data, error, details, +5 more
mysql_json_searchMySQL JSON SearchBRead-only
Search for a string value in JSON columns and return matching paths.
Inputs: col, sql, val, mode, +18 more. Returns: code, data, error, details, +5 more
mysql_json_setMySQL JSON SetB
Set or update values in JSON columns at specified paths.
Inputs: col, sql, val, name, +12 more. Returns: code, data, error, details, +5 more
mysql_json_statsMySQL JSON StatsARead-only
Analyze statistics for a JSON column including depth, size, and key frequency.
Inputs: col, sql, name, query, +8 more. Returns: code, data, error, details, +5 more
mysql_json_updateMySQL JSON UpdateC
Simple JSON value update by row ID.
Inputs: col, sql, val, name, +12 more. Returns: code, data, error, details, +5 more
mysql_json_validateMySQL JSON ValidateARead-only
Validate if a string is valid JSON.
Inputs: data, json, value, document, +1 more. Returns: code, data, error, details, +5 more
mysql_like_searchMySQL LIKE SearchBRead-only
Find rows using LIKE pattern matching with % and _ wildcards.
Inputs: col, sql, name, limit, +7 more. Returns: code, data, error, details, +5 more
mysql_list_tablesMySQL List TablesARead-only
List all tables and views in the database with metadata.
Inputs: db, limit, schema, database. Returns: code, data, error, details, +5 more
mysql_read_queryMySQL Read QueryARead-only
Execute a read-only SQL query (SELECT). Uses prepared statements for safety.
Inputs: tx, sql, txId, query, +5 more. Returns: code, data, error, details, +5 more
mysql_regexp_matchMySQL REGEXP MatchCRead-only
Find rows where column matches a regular expression pattern.
Inputs: col, sql, name, limit, +7 more. Returns: code, data, error, details, +5 more
mysql_soundexMySQL SOUNDEXBRead-only
Find rows with phonetically similar values using SOUNDEX.
Inputs: col, name, limit, query, +8 more. Returns: code, data, error, details, +5 more
mysql_substringMySQL SUBSTRINGBRead-only
Extract substrings from column values.
Inputs: col, name, limit, start, +7 more. Returns: code, data, error, details, +5 more
mysql_transaction_beginMySQL Begin TransactionA
Begin a new transaction with optional isolation level. Returns a transaction ID for subsequent operations.
Inputs: level, isolationLevel, isolation_level. Returns: code, data, error, details, +5 more
mysql_transaction_commitMySQL Commit TransactionA
Commit a transaction, making all changes permanent.
Inputs: tx, txId, transactionId. Returns: code, data, error, details, +5 more
mysql_transaction_executeMySQL Atomic ExecuteA
Execute multiple SQL statements atomically. All statements succeed or all are rolled back.
Inputs: sql, level, query, queries, +3 more. Returns: code, data, error, details, +6 more
mysql_transaction_releaseMySQL Release SavepointA
Release a savepoint, removing it without rolling back.
Inputs: id, tx, name, txId, +3 more. Returns: code, data, error, details, +5 more
mysql_transaction_rollbackMySQL Rollback TransactionC
Rollback a transaction, undoing all changes.
Inputs: tx, txId, transactionId. Returns: code, data, error, details, +5 more
mysql_transaction_rollback_toMySQL Rollback to SavepointA
Rollback to a savepoint, undoing changes after that point.
Inputs: id, tx, name, txId, +3 more. Returns: code, data, error, details, +5 more
mysql_transaction_savepointMySQL Create SavepointC
Create a savepoint within a transaction for partial rollback.
Inputs: id, tx, name, txId, +3 more. Returns: code, data, error, details, +5 more
mysql_write_queryMySQL Write QueryA
Execute a write SQL query (INSERT, UPDATE, DELETE). Uses prepared statements for safety.
Inputs: tx, sql, txId, query, +2 more. Returns: code, data, error, details, +5 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
TDQS
Scored across 43 tools
Tools are organized with prefixes like mysql_json_, mysql_transaction_, etc., making them distinct. However, the high number of JSON tools (e.g., mysql_json_get and mysql_json_extract) might cause minor confusion, though their descriptions clarify differences.
All tools follow a consistent mysql_verb_noun pattern (e.g., mysql_create_table, mysql_read_query). No mixing of conventions like camelCase.
43 tools is high for a typical MCP server. While comprehensive for a MySQL client, it feels overloaded and may overwhelm agents, exceeding the typical 3-15 tool range.
Covers a wide range of MySQL operations: CRUD, transactions, JSON, indexing, admin, monitoring, and more. Minor gaps like lack of explicit 'drop view' or 'alter table' exist, but core workflows are well-supported.
Maintenance
Related MCP Connectors
Hosted MCP server for AI-driven data ops. Create apps, manage schemas, and CRUD structured data.
Hosted MySQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Hosted SQL Server MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables SQL query execution, database management, and business intelligence capabilities through MySQL connections.1,462 npmMIT
- AlicenseBqualityDmaintenanceA Model Context Protocol server that enables AI models to interact with MySQL databases through a standardized interface, providing tools for querying, executing commands, and managing database schemas.7MIT
- AlicenseCqualityDmaintenanceA Model Context Protocol server that enables AI models to interact with both MySQL and MongoDB databases through a standardized interface, supporting comprehensive database operations including queries, schema management, and CRUD operations.148MIT
- AlicenseNot gradedqualityDmaintenanceA comprehensive Model Context Protocol server that enables AI assistants to interact with MySQL databases through secure, role-based database operations.4MIT