
Mysql Mcp
io.github.neverinfamousPublished by GitHub account neverinfamousv1.0.0Updated Oct 27, 2026
Enterprise-grade MySQL MCP Server with OAuth 2.0, 106 tools, and Docker deployment
Overview
A local MySQL MCP server exposing 106 tools and many observability resources so an assistant can query, administer and monitor MySQL databases.
- What you can do
- Run read and write SQL queries, manage tables, indexes, views, procedures and triggers
- Handle transactions, savepoints, JSON, text and full-text search operations
- Analyze performance with EXPLAIN, index hints, statistics and schema introspection
- Administer backups, replication, partitioning, roles, security and InnoDB Cluster or ProxySQL setups
- Inspect database state through resources for schema, status, processlist, health, locks and metrics
- Execute multi-step JavaScript in a sandboxed Code Mode tool to save tokens
- When to use it
- Useful when an assistant needs to work directly against a MySQL instance: exploring schemas, running queries, tuning performance, or monitoring a cluster. Tool filtering lets you expose only the groups an IDE can handle.
- Requirements
- Runs as a local process via npx or the npm package, or as a Docker image; Node.js 24 or newer for the npm route. Needs a reachable MySQL server and connection details, given as a connection string or MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD and MYSQL_DATABASE. Optional cluster, Router and ProxySQL settings use further MYSQL_ROUTER_*, PROXYSQL_* and MYSQLSH_PATH variables.
Installation
In SourceWeft
- Open Mysql Mcp in the dashboard and add it to a workspace.
- Enable the server for the chats that should use its tools.
Desktop only via STDIO. STDIO servers start a local process, so they need the SourceWeft desktop host.
Other MCP clients
Follow the launch instructions in the repository.
README
MySQL MCP Server (mysql-mcp)
[GitHub Release] [npm] [Docker Pulls] [MCP] [License: MIT] [Coverage] [E2E]
📚 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.
🎯 Leverage Core Benefits
🤖 Automate Tasks with Guided Workflows
This server includes intelligent prompts for guided workflows:
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:
🚀 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
Run the server:
Or use npx without installing:
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.
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:
- Grafana: 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
🏗️ 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.
[!TIP] 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:
Docker:
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:
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:
In stateless mode: GET /mcp returns 405. DELETE /mcp returns 204. Each POST /mcp instantiates a stateless HTTP transport.
Access Utility Endpoints
🔐 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:
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:
Additional flags:
--oauth-jwks-uri <url>(auto-discovered if omitted),--oauth-clock-tolerance <seconds>(default: 60).
Enforce OAuth Scopes
Enforce access control using OAuth scopes:
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)
[!NOTE] 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.
[!WARNING] HTTP without authentication: Exposing
--transport httpwithout 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.
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 instance- Use
cluster_adminorrootuser with appropriate privileges- See MySQL Ecosystem Setup Guide for cluster setup instructions
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_jsonanddocstoretools- See MySQL Ecosystem Setup Guide for detailed instructions
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 backslashes - For 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
Connect to MySQL on Host Machine
For native local installations, use localhost. If running the server in Docker, use host.docker.internal:
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:
Run MCP server on the same network:
Connect to Remote/Cloud MySQL (RDS, Cloud SQL, etc.)
Use the remote hostname directly:
Tip: Ensure remote MySQL servers allow connections from Docker's IP range. Verify firewalls/security groups permit port 3306.
🛠️ Optimize Limits with Tool Filtering
[!IMPORTANT] 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
-codemodeto your filter:--tool-filter core,json,-codemode
Discover Filtering Options
The --tool-filter argument accepts shortcuts, groups, or tool names — mix and match freely:
Use Predefined Shortcuts
Filter by Tool Groups
Note: Code Mode (
mysql_execute_code) is automatically added to all groups.
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.
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.
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:
⚡ 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.
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:
Debug with MCP Inspector
Use MCP Inspector to visually test and debug mysql-mcp:
Build the server first:
Launch Inspector with mysql-mcp:
Open http://localhost:5173 to browse all tools, resources, and prompts interactively.
CLI mode for scripting:
List all tools:
Call a specific tool:
📖 See the MCP Inspector Wiki for detailed usage.
Run Unit Tests
The project maintains high test coverage using Vitest.
Run coverage report:
Test 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.
Contributing Guidelines • Security Policy • MIT License • Code of Conduct
Source: README.md at commit dd015e3
Tools
0Version history
1- v1.0.0LatestSep 16, 2026
Score
50% of the applicable checks met
How complete this listing is, computed from the registry entry, the endpoint and public sources. Not a rating of the server and not a statement that it is safe or working today: reachability is a dated check, and no installs or reviews go into the score.
- Reached in the last 30 days25 pts
Keep the endpoint answering the MCP handshake; SourceWeft probes it every 30 days.
- Auth declared10 pts
Declare the credential headers in the registry entry, or keep the endpoint answering the probe so its auth can be classified.
- Tools listed15 pts
Answer tools/list without a credential, or ship a package that starts in a sandbox without one.
- DescriptionRequired15 pts
- Logo10 pts
- Documentation15 pts
- License10 pts