A fast, read-only MySQL Server for the Model Context Protocol (MCP) written in Go.
This project exposes safe MySQL introspection tools to Claude Desktop via MCP. Claude can explore databases, describe schemas, and execute controlled read-only SQL queries — ideal for secure development assistance, debugging, analytics, and schema documentation.
MySQL Server implementation for Model Context Protocol (MCP) written in Go.
Sterne
44
Tools
—
Uptime
—
Features
Fully read-only (blocks all non-SELECT/SHOW/DESCRIBE/EXPLAIN)
Multi-DSN Support: Connect to multiple MySQL or MariaDB instances, switch via tool
MariaDB Support: Native compatibility with MariaDB 10.x, 11.x and 12.x
Vector Search (MySQL 9.0+): Similarity search on vector columns
MCP tools:
list_databases, list_tables, describe_table
run_query (safe and row-limited)
ping, server_info
list_connections, use_connection (multi-DSN)
vector_search, vector_info (MySQL 9.0+)
Supports MySQL 8.0, 8.4, 9.x, 26.x and MariaDB 10.x, 11.x, 12.x (CI-tested on MySQL 8.0, 8.4, 9.7, 26.10 and MariaDB 11.4, 12.3)
Query timeouts, structured logging, audit logs; optional live token metrics and /status dashboard in HTTP mode
Performance: configurable pool/query timeouts, server-side row caps, explain_query plan warnings
Single Go binary
Unit and integration tests (Testcontainers)
Native integration with Claude Desktop MCP
Installation
Homebrew (macOS/Linux)
brew install askdba/tap/mysql-mcp-server
Update local installation (after a new release):
brew update && brew upgrade mysql-mcp-server
Apple Silicon — “Cannot install under Rosetta 2 in ARM default prefix (/opt/homebrew)”
Your shell is running Homebrew under Rosetta (Intel) while /opt/homebrew is ARM. They must match. Use one of:
Run upgrades as ARM: arch -arm64 brew upgrade mysql-mcp-server (or arch -arm64 /opt/homebrew/bin/brew upgrade mysql-mcp-server).
Terminal.app → Get Info → uncheck Open using Rosetta, then open a new terminal.
Put /opt/homebrew/bin first in PATH so you use the ARM brew and binary.
Claude Desktop: on Apple Silicon, point command at /opt/homebrew/bin/mysql-mcp-server. /usr/local/opt/mysql-mcp-server/... is normally Intel Homebrew and can stay on an old version.
Tip:brew info askdba/tap/mysql-mcp-server shows a config reminder after install.
Option B: Build from Source
git clone https://github.com/askdba/mysql-mcp-server.git
cd mysql-mcp-server
make build
When running from a cloned repo you can also use the interactive setup script:
./scripts/quickstart.sh
This will test your MySQL connection, optionally create a read-only MCP user, and generate your Claude Desktop configuration.
Configuration
Environment variables:
Variable
Required
Default
Description
MYSQL_DSN
Yes
–
MySQL DSN
MYSQL_MAX_ROWS
No
200
Max rows returned per query
MYSQL_QUERY_TIMEOUT_SECONDS
No
30
Query timeout (seconds); wins over MYSQL_QUERY_TIMEOUT when both are set
MYSQL_QUERY_TIMEOUT
No
–
Query timeout in milliseconds (e.g. 30000); used only if MYSQL_QUERY_TIMEOUT_SECONDS is unset
MYSQL_POOL_SIZE
No
–
Alias for MYSQL_MAX_OPEN_CONNS (pool size); MYSQL_MAX_OPEN_CONNS overrides when both are set
MYSQL_MCP_EXTENDED
No
0
Enable extended tools (set to 1)
MYSQL_MCP_ENABLE_ADD_CONNECTION
No
0
Set 1 to expose the MCP tool add_connection (runtime DSN registration; see add_connection). Requires MYSQL_MCP_EXTENDED=1. Not available over the HTTP REST API.
MYSQL_MCP_JSON_LOGS
No
0
Enable JSON structured logging (set to 1)
MYSQL_MCP_TOKEN_TRACKING
No
0
Enable estimated token usage tracking (set to 1)
MYSQL_MCP_TOKEN_MODEL
No
cl100k_base
Tokenizer encoding to use for estimation
MYSQL_MCP_TOKEN_CARD
No
on when MYSQL_MCP_HTTP is set
/status live token dashboard + listing in GET /api; omit to use default on; set to 0 to disable
MYSQL_MCP_AUDIT_LOG
No
–
Path to audit log file
MYSQL_MCP_ALLOWED_DATABASES
No
–
Comma-separated schema allowlist (empty = all allowed). With an allowlist, run_query rejects SHOW DATABASES / SHOW DATABASES LIKE—use list_databases.
MYSQL_MCP_STRICT_READ_ONLY
No
0
Set 1 to enable transaction_read_only=ON on new connections
MYSQL_MCP_ALLOW_SYSTEM_SCHEMAS
No
0
Set 1 to allow read-only access to information_schema, performance_schema, and sys (for diagnostics: index cardinality, index usage, redundant/unused indexes). mysql stays blocked regardless.
MYSQL_MCP_PROCESS_ADMIN
No
0
Set 1 to enable process_list / kill_query (extended); kill_query issues KILL QUERY (cancels the running statement only, not the connection)
MYSQL_MCP_READ_AUDIT_TOOL
No
0
Set 1 to enable read_audit_log when audit path is set
MYSQL_MCP_SLOW_QUERY_TOOL
No
0
Set 1 to enable slow_query_log tool (extended)
MYSQL_MCP_VECTOR
No
0
Enable vector tools for MySQL 9.0+ (set to 1)
MYSQL_MCP_HTTP
No
0
Enable REST API mode (set to 1); mutually exclusive with stdio MCP
MYSQL_MCP_METRICS_HTTP
No
0
With stdio MCP only: expose /status + /api/metrics/tokens on MYSQL_HTTP_PORT (same process as Claude/Cursor)
MYSQL_HTTP_PORT
No
9306
Port for REST API, MCP HTTP transport, or metrics sidecar
MYSQL_MCP_TRANSPORT
No
stdio
MCP transport: stdio or http (MCP Streamable HTTP). http cannot be combined with MYSQL_MCP_HTTP=1
MYSQL_MCP_HTTP_BIND
No
127.0.0.1
Listen address (host or IP, no port; [::1] is accepted) for the MCP HTTP transport. Any non-loopback address requires a token and TLS
MYSQL_MCP_HTTP_PATH
No
/mcp
MCP endpoint path: a literal path without trailing / or wildcards, not /health, /status or /api/metrics/tokens
MYSQL_MCP_HTTP_TOKEN
No
–
Bearer token clients must send (Authorization: Bearer …). Required for non-loopback binds
MYSQL_MCP_HTTP_TOKEN_FILE
No
–
File containing the bearer token (keeps it out of the environment)
MYSQL_MCP_HTTP_TLS_CERT / MYSQL_MCP_HTTP_TLS_KEY
No
–
Serve HTTPS. Required for non-loopback binds
MYSQL_MCP_HTTP_ALLOW_INSECURE
No
0
Set 1 to allow a non-loopback bind without TLS when a reverse proxy terminates TLS in front. The token is still required
MYSQL_MCP_HTTP_STATELESS
No
0
Set 1 for stateless sessions (no Mcp-Session-Id); use_connection then only lasts one request
MYSQL_MCP_HTTP_SESSION_TIMEOUT_MINUTES
No
30
Close idle MCP HTTP sessions after this many minutes
MYSQL_MCP_HTTP_ALLOWED_ORIGINS
No
–
Comma-separated browser origins, each scheme://host[:port] with no path (e.g. https://app.example.com), allowed to call the endpoint: they get CORS headers and pass cross-origin protection. Other origins get no CORS headers, and their state-changing requests (POST, DELETE) to the MCP endpoint are rejected
MYSQL_MCP_HTTP_ALLOWED_HOSTS
No
–
Comma-separated public host names a reverse proxy on the same machine forwards to the loopback listener (e.g. mcp.example.com). Without it, such requests fail the DNS-rebinding check with 403. Setting it requires a token, because the proxy makes the server reachable from outside
MYSQL_HTTP_RATE_LIMIT
No
0
Enable rate limiting for HTTP mode (set to 1)
MYSQL_HTTP_RATE_LIMIT_RPS
No
100
Rate limit: requests per second
MYSQL_HTTP_RATE_LIMIT_BURST
No
200
Rate limit: burst size
MYSQL_MAX_OPEN_CONNS
No
10
Max open database connections (overrides MYSQL_POOL_SIZE when both are set)
MYSQL_MAX_IDLE_CONNS
No
5
Max idle database connections
MYSQL_CONN_MAX_LIFETIME_MINUTES
No
30
Connection max lifetime in minutes
MYSQL_CONN_MAX_IDLE_TIME_MINUTES
No
5
Max idle time before connection is closed
MYSQL_PING_TIMEOUT_SECONDS
No
5
Database ping/health check timeout
MYSQL_MCP_DB_RETRY_MAX
No
3
Retries for transient errors on run_query and ping (0 disables retries)
MYSQL_MCP_DB_RETRY_MAX_INTERVAL_MS
No
10000
Max exponential-backoff interval between retries (milliseconds)
MYSQL_HTTP_REQUEST_TIMEOUT_SECONDS
No
60
HTTP request timeout in REST API mode
MYSQL_SSL
No
–
Enable SSL/TLS for connections (true, false, skip-verify, preferred)
SSL/TLS Configuration
Enable encrypted connections to MySQL servers:
SSL Value
Description
true
Enable TLS with certificate verification
false
Disable TLS (default)
skip-verify
Enable TLS without certificate verification (self-signed certs)
preferred
Maps to skip-verify (Go MySQL driver limitation)
Note: The Go MySQL driver doesn't support tls=preferred. When you specify preferred, it is automatically mapped to skip-verify to ensure TLS is enabled.
Environment variable:
# Enable SSL for all connections
export MYSQL_SSL="true"
# Or per-connection SSL
export MYSQL_DSN_1_SSL="skip-verify"
Security — host keys (read this): By default the server verifies the SSH bastion’s host key (same idea as OpenSSH). Without that, a network attacker could present a fake bastion and intercept database traffic. Use a known_hosts file (default: ~/.ssh/known_hosts) or pin the key with MYSQL_SSH_HOST_KEY_FINGERPRINT. Paths support ~. Turning verification off is opt-in only and dangerous: set MYSQL_SSH_STRICT_HOST_KEY_CHECKING=false or YAML strict_host_key_checking: false (JSON: ssh_strict_host_key_checking: false) only if you accept that risk.
Connect to MySQL through an SSH bastion when the database is not directly reachable:
Variable
Description
MYSQL_SSH_HOST
Bastion hostname
MYSQL_SSH_USER
SSH username
MYSQL_SSH_KEY_PATH
Path to private key file (~ expanded)
MYSQL_SSH_PORT
SSH port (default 22)
MYSQL_SSH_KNOWN_HOSTS
Path to OpenSSH known_hosts file (optional; default ~/.ssh/known_hosts when verifying)
MYSQL_SSH_HOST_KEY_FINGERPRINT
Pin server key, e.g. SHA256:... or legacy MD5:... / aa:bb:... (optional; overrides file lookup for the callback)
MYSQL_SSH_STRICT_HOST_KEY_CHECKING
Default strict. Set to false / 0 / no / off to disable host key verification (insecure)
Environment variables:
export MYSQL_SSH_HOST="bastion.example.com"
export MYSQL_SSH_USER="deploy"
export MYSQL_SSH_KEY_PATH="$HOME/.ssh/id_rsa"
export MYSQL_SSH_KNOWN_HOSTS="$HOME/.ssh/known_hosts"
# Optional: instead of a file, pin the bastion key (from ssh-keygen -lf):
# export MYSQL_SSH_HOST_KEY_FINGERPRINT="SHA256:...."
export MYSQL_DSN="user:pass@tcp(mysql.internal:3306)/mydb?parseTime=true"
Config file:
connections:
production:
dsn: "user:pass@tcp(mysql.internal:3306)/mydb?parseTime=true"
ssh:
host: "bastion.example.com"
user: "deploy"
key_path: "~/.ssh/id_rsa"
port: 22 # optional, default 22
strict_host_key_checking: true # default when omitted; false = insecure, opt-in only
known_hosts: "~/.ssh/known_hosts" # optional
host_key_fingerprint: "SHA256:...." # optional alternative to known_hosts
Multi-DSN Configuration
Configure multiple MySQL connections using numbered environment variables:
Runtime vs static DSNs: Connections defined here (env vars, MYSQL_CONNECTIONS, or YAML) are loaded at process startup into the shared ConnectionManager. The optional MCP tool add_connection (requires MYSQL_MCP_EXTENDED=1 and MYSQL_MCP_ENABLE_ADD_CONNECTION=1) can register additional named DSNs later without restart. New names must not collide with existing connection names. Runtime-registered pools use the same global “active” connection as config-loaded ones—see add_connection. There is no separate per-client session; all MCP clients using the same server process share one active DSN unless you run multiple server instances.
Configuration File
As an alternative to environment variables, you can use a YAML or JSON configuration file.
# Use specific config file
mysql-mcp-server --config /path/to/config.yaml
# Validate config file
mysql-mcp-server --validate-config /path/to/config.yaml
# Print current configuration as YAML
mysql-mcp-server --print-config
# Silent mode: suppress INFO/WARN logs (only errors to stderr)
mysql-mcp-server --silent --config /path/to/config.yaml
# Daemon mode: run HTTP server in background (Unix; use with MYSQL_MCP_HTTP=1)
MYSQL_MCP_HTTP=1 mysql-mcp-server --daemon --config /path/to/config.yaml
Silent and daemon mode: Use -s / --silent to reduce log noise in production (INFO and WARN are suppressed; ERROR still goes to stderr). Use -d / --daemon to run the HTTP server detached in the background on Unix. For long-running services, use the example systemd unit or launchd plist. See Silent and daemon mode for details.
Note: If Claude Desktop cannot find the binary, replace "mysql-mcp-server" with the full path from which mysql-mcp-server.
Token dashboard (/status) in the same process as MCP: stdio MCP does not open HTTP by default. Set MYSQL_MCP_METRICS_HTTP=1 so this instance also listens on MYSQL_HTTP_PORT (default 9306) for http://127.0.0.1:9306/status and /api/metrics/tokens — the same counters as Claude’s tool calls. Use MYSQL_MCP_TOKEN_TRACKING=1 so the dashboard is meaningful. Do not set MYSQL_MCP_HTTP=1 here (that mode replaces MCP with full REST only).
Token dashboard (/status) in the same process as MCP: Same behavior as Claude Desktop — stdio MCP does not open HTTP by default. Set MYSQL_MCP_TOKEN_TRACKING=1, MYSQL_MCP_METRICS_HTTP=1, and MYSQL_HTTP_PORT (default 9306) for http://127.0.0.1:9306/status and /api/metrics/tokens. Do not set MYSQL_MCP_HTTP=1 here (full REST replaces stdio MCP).
Claude Code supports MCP servers via the CLI or a project-scoped .mcp.json file.
Option 1: CLI (quick setup)
claude mcp add --transport stdio \
--env MYSQL_DSN="user:password@tcp(127.0.0.1:3306)/mydb?parseTime=true" \
--env MYSQL_MCP_EXTENDED=1 \
mysql -- mysql-mcp-server
Option 2: Project .mcp.json
This repo includes a .mcp.json that Claude Code auto-discovers when you open the project. Set your DSN in the shell before starting Claude Code:
export MYSQL_DSN="user:password@tcp(127.0.0.1:3306)/mydb?parseTime=true"
claude # start Claude Code — MySQL tools will be available automatically
To use the same config in your own project, copy .mcp.json to your project root and set MYSQL_DSN in your shell.
Verify the integration by asking Claude Code: "List all databases on this MySQL server."
Remote MCP over HTTP (Streamable HTTP)
Besides stdio, the server can speak MCP over the Streamable HTTP transport, so MCP clients connect over the network without launching a local process. It serves the same tools, prompts and resources as stdio, and the same safety rules apply (read-only validation, allow-lists, column masking, audit log).
Local (loopback only, no token needed):
export MYSQL_DSN="user:password@tcp(127.0.0.1:3306)/mydb?parseTime=true"
export MYSQL_MCP_TRANSPORT=http # MCP at http://127.0.0.1:9306/mcp
mysql-mcp-server
claude mcp add --transport http mysql http://127.0.0.1:9306/mcp
claude mcp add --transport http mysql https://db-tools.example.com:9306/mcp \
--header "Authorization: Bearer $(cat /etc/mysql-mcp/token)"
Behavior and safety:
Refuses to start unsafely: a non-loopback bind without a token, or without TLS, is a startup error. --validate-config runs the same checks, with the same environment overrides. With --daemon, the TLS key pair and the listen address are checked before the process detaches, so a bad certificate or a busy port is reported instead of exiting silently.
Behind a reverse proxy (nginx, Caddy, …) that terminates TLS:
If the proxy forwards to the loopback listener (default bind), list its public names in MYSQL_MCP_HTTP_ALLOWED_HOSTS. Otherwise the DNS-rebinding check rejects its Host header. A token is then required, as for any non-loopback bind.
If it forwards to a non-loopback bind, also set MYSQL_MCP_HTTP_ALLOW_INSECURE=1; the token is still required.
Browser protections:
On the MCP endpoint, cross-origin requests that can change state (POST, DELETE) are rejected unless the origin is listed in MYSQL_MCP_HTTP_ALLOWED_ORIGINS.
Listed origins get CORS headers on the MCP endpoint, /health and /api/metrics/tokens, including answers to preflight requests, so browser-based clients work. (/status is a page to open directly, not to fetch cross-origin.) Other origins get no CORS headers anywhere on the port, so their pages cannot read the responses. /health and /api/metrics/tokens never send Access-Control-Allow-Origin: * here, unlike on the REST API.
On localhost, requests on any route whose Host header is not a localhost name (or an allowed host) are rejected (DNS-rebinding protection).
Per-session connections:use_connection and add_connection switch the active connection for that MCP session only; other HTTP clients keep theirs. If a session's connection is removed, its tools fail with "connection '…' no longer exists" instead of silently running on another server. In stateless mode (MYSQL_MCP_HTTP_STATELESS=1) a switch lasts only for the request that made it. A session's choice also ends with the session (idle timeout or DELETE): a client that starts a new session is back on the default connection. So when the session can see more than one connection, every tool result names the connection it ran on, both as a final text line connection: <name> and in _meta["mysql-mcp-server/connection"]. Each tool call stays on one connection from start to finish, even if use_connection runs concurrently in the same session. Configured connection names cannot start with mcp-session/, which is reserved for these session connections.
add_connection over HTTP belongs to the session (MYSQL_MCP_ENABLE_ADD_CONNECTION=1; off by default):
The new connection is visible only to the session that added it, in list_connections and use_connection. Other sessions cannot see or use it, or its credentials.
Names are per session: two sessions can each add staging. A name that is already a configured, process-wide connection is refused.
It is closed (pool and SSH tunnel) when the session ends: when the client sends DELETE with its Mcp-Session-Id, or after MYSQL_MCP_HTTP_SESSION_TIMEOUT_MINUTES without requests. A dropped connection or a crashed client does not end the session, so its connections stay open until the idle timeout. Lower the timeout if clients often go away without ending their session.
Each session can register at most 5 connections, and all sessions together at most 20. Each of these connections has a pool of at most 2, so add_connection over HTTP can open at most 40 MySQL connections.
It is refused in stateless mode, where the connection would close as soon as the request ends.
It still lets any token holder make the server connect to any host the server can reach, so enable it for remote deployments only when every token holder is trusted.
Other endpoints on the same port:GET /health (no auth) and GET /api/metrics/tokens (same token). /status is served only when no token is configured, because a browser cannot send the bearer token.
MYSQL_HTTP_RATE_LIMIT applies to this transport too. Behind a reverse proxy on the same host, limits are per client only if the proxy sets or appends X-Forwarded-For (nginx: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;): the server uses the rightmost entry, the one the proxy adds. A proxy that passes the client's header through unchanged lets clients choose their own bucket. Request headers must arrive within 10s and bodies within 30s, so slow clients cannot hold connections open. Long tool calls and event streams are not affected. On SIGINT/SIGTERM, in-flight requests get 5s, then open event streams are closed, and a second later any connection still open (for example a client stalled mid-body) is closed, so shutdown takes about 6s at most.
It cannot run in the same process as the REST API (MYSQL_MCP_HTTP=1); run two processes if you need both.
Config file equivalent:
transport: http
http:
port: 9306
mcp:
bind: 0.0.0.0
path: /mcp
token_file: /etc/mysql-mcp/token # the token itself is never stored in the config file
tls_cert: /etc/mysql-mcp/cert.pem
tls_key: /etc/mysql-mcp/key.pem
session_timeout_minutes: 30
# stateless: false
# allowed_origins: ["https://app.example.com"] # browser clients (CORS)
# allowed_hosts: ["mcp.example.com"] # reverse proxy forwarding to loopback
# allow_insecure: false
Offset pagination (SELECT/UNION without an existing LIMIT in the SQL): pass offset (zero-based). The tool appends LIMIT (max_rows+1) OFFSET n server-side, returns at most max_rows rows, and sets has_more / next_offset when another page may exist. Do not add your own LIMIT when using offset.
Rejects non-read-only SQL
Enforces row limit
Enforces timeout
Retries transient connection/network errors with backoff (see MYSQL_MCP_DB_RETRY_MAX)
MCP tool. Available when the server runs in MCP mode (stdio or Streamable HTTP) with MYSQL_MCP_EXTENDED=1 and MYSQL_MCP_ENABLE_ADD_CONNECTION=1. It registers a new named MySQL connection at runtime and switches to it: over stdio the process-wide active connection changes; over Streamable HTTP the connection belongs to the calling MCP session: only that session sees and uses it, and it is closed when the session ends (details). There is no REST API route to register a new DSN. REST API mode (MYSQL_MCP_HTTP=1) is a separate process: GET /api/connections and POST /api/connections/use only list and switch connections loaded in that HTTP server instance—they do not see names added via MCP in a stdio process, and MCP does not reach into a separate HTTP-only deployment.
Non-empty; must not match an existing connection name (atomic check in ConnectionManager).
dsn
Yes
Non-empty; must parse as a valid MySQL DSN. root as the MySQL user is rejected at registration time.
description
No
Stored with the connection metadata.
Behavior: builds a ConnectionConfig, opens a pool, Ping() with the tool request context (timeouts/cancellation), then activates it. On activation failure after a successful add, the server removes the new pool (rollback). Over stdio, the active connection applies to all tools on this process until switched again (use_connection or another add_connection). Over Streamable HTTP, it applies only to the requesting MCP session.
Output (success):
{
"success": true,
"active": "analytics",
"message": "Added and switched to connection 'analytics'"
}
Typical errors (tool returns an error result): duplicate name, invalid DSN, root user blocked, unreachable host (ping failure), activation/rollback failure. See Runtime connection registration (add_connection) for security implications.
CREATE USER 'mcp'@'localhost' IDENTIFIED BY 'strongpass';
GRANT SELECT ON *.* TO 'mcp'@'localhost';
Runtime connection registration (add_connection)
When MYSQL_MCP_ENABLE_ADD_CONNECTION=1 (and extended mode), any MCP client that can invoke tools may call add_connection. This server exposes MCP over stdio by default; it does not add a separate HTTP Basic/API-key layer beyond whatever protects access to that MCP process (typically local stdio from the host application). Treat MCP access as privileged: anyone who can call tools can attempt to register a new outbound DSN to hosts reachable from the server. If you also run REST API mode (MYSQL_MCP_HTTP=1) in another process or deployment, secure that interface independently—it is separate from MCP.
Controls enforced by the server today:
DSN parsing: Invalid DSNs are rejected before opening a connection.
User blocklist: The literal MySQL user root is rejected for runtime registration to reduce accidental high-privilege pools.
Duplicate names: Registration is refused if the name already exists (ConnectionManager); adds are not silently merged with static config names.
Unsafe driver options: DSNs with allowAllFiles=true (would let the MySQL server read local files of this process) or multiStatements=true are rejected. DSNs from the config file or environment are not affected.
Connectivity check: A pool is opened and Ping() runs before the connection is considered registered; failures do not leave a half-open registration (failed adds are rolled back if activation fails after add).
Read-only mode: If MYSQL_MCP_STRICT_READ_ONLY=1, new pools still get transaction_read_only=ON on the driver path like other connections.
Operational guidance: Disable MYSQL_MCP_ENABLE_ADD_CONNECTION (default 0) unless you need runtime registration. Prefer firewall/network policies so the server host can only reach approved database endpoints. Use least-privilege MySQL users in registered DSNs (same as Recommended MySQL User). Review Multi-DSN Configuration for how static and runtime entries coexist in one process.
Token counts are estimates using tiktoken encoding, not actual LLM billing
For payloads exceeding 1MB, a heuristic (~4 bytes per token) is used to prevent memory spikes
The feature is disabled by default to avoid overhead when not needed
Query Timing
All queries are automatically timed and logged with:
Execution duration (milliseconds)
Row count returned
Tool name
Truncated query (for debugging)
Performance Tuning
Connection pool and query timeouts
Configure the pool and how long queries may run (see also MYSQL_POOL_SIZE and MYSQL_QUERY_TIMEOUT / MYSQL_QUERY_TIMEOUT_SECONDS in the configuration table):
export MYSQL_MAX_OPEN_CONNS=20 # Max open connections (or use MYSQL_POOL_SIZE as an alias)
export MYSQL_MAX_IDLE_CONNS=10 # Max idle connections
export MYSQL_CONN_MAX_LIFETIME_MINUTES=60 # Connection lifetime
export MYSQL_QUERY_TIMEOUT=30000 # Optional: timeout in ms (30 s) if you do not use MYSQL_QUERY_TIMEOUT_SECONDS
run_query applies a server-side LIMIT when absent, returns truncated when more rows exist than the cap (non-pagination mode), returns has_more / next_offset when offset pagination is used, and may warning on SELECT *. Use explain_query for plan warnings (full scans, filesort, etc.).
MySQL max_execution_time vs MCP timeouts: The server enforces MYSQL_QUERY_TIMEOUT_SECONDS (or MYSQL_QUERY_TIMEOUT in ms) on the Go side for every tool. That is independent of the MySQL session variable max_execution_time (often 0, meaning “no engine-side cap”). For operator clarity: configure MCP query timeout for how long the client should wait; configure MySQL if you also want the optimizer to abort expensive SELECTs.
Concurrent tool calls: Each parallel MCP tool call may use a pooled connection. If the host issues several tools at once, set MYSQL_MAX_OPEN_CONNS (alias MYSQL_POOL_SIZE) high enough—e.g. 10–20—so threads do not queue behind a single connection.
Security options and privileged tools (extended mode)
Variable
Purpose
MYSQL_MCP_ALLOWED_DATABASES
Comma-separated schema allowlist. When set, tools that take a database argument must use an allowed name; list_databases / database_size only expose allowed schemas; run_query requires database and cannot be used to hop schemas via omission. run_query rejects SHOW DATABASES and SHOW DATABASES LIKE (use list_databases). Qualified names in SQL, EXPLAIN (including FORMAT= / EXTENDED), and inner DML in EXPLAIN are checked against the allowlist. slow_query_log (table mode) only returns mysql.slow_log rows whose db column matches an allowed schema (case-insensitive); rows with null/empty db are omitted.
MYSQL_MCP_STRICT_READ_ONLY
When 1, new driver connections run with transaction_read_only=ON (harder to accidentally issue writes if grants allow them).
MYSQL_MCP_ALLOW_SYSTEM_SCHEMAS
When 1, lifts the default block on the read-only diagnostic schemas information_schema, performance_schema, and sys so run_query / explain_query may reference them (e.g. information_schema.STATISTICS for index cardinality, sys.schema_redundant_indexes / sys.schema_unused_indexes, performance_schema.table_io_waits_summary_by_index_usage). The mysql schema remains blocked unconditionally. Off by default; reads still require the connection's MySQL grants. This flag and MYSQL_MCP_ALLOWED_DATABASES are orthogonal and both enforced: the flag lifts the hardcoded system-schema guard, while the allowlist (when set) independently rejects any schema not on it. So if you run with an allowlist, you must also add information_schema / performance_schema / sys to MYSQL_MCP_ALLOWED_DATABASES for these queries to pass; with no allowlist (the default), the flag alone is sufficient. The flag never unlocks mysql.
MYSQL_MCP_PROCESS_ADMIN
Enables process_list and kill_query (issues KILL QUERY, not connection kill; plus HTTP /api/processlist, /api/kill). Requires appropriate MySQL privileges (CONNECTION_ADMIN / PROCESS, etc.).
MYSQL_MCP_READ_AUDIT_TOOL
Enables read_audit_log when MYSQL_MCP_AUDIT_LOG is set (tail of the audit JSON file).
MYSQL_MCP_SLOW_QUERY_TOOL
Enables slow_query_log (reads mysql.slow_log when log_output includes TABLE, otherwise returns file settings).
server_info: Pass detailed: true (MCP) or ?detailed=1 (HTTP) for ping latency, Threads_running, Slow_queries, Questions, and InnoDB buffer pool hit rate when stats are available. If MYSQL_MCP_TOKEN_TRACKING=1, token_metrics is always included (cumulative since process start).
YAML file equivalents live under security: in the config file (allowed_databases, strict_read_only, allow_system_schemas, process_admin, read_audit_tool, slow_query_tool).
Testing
Prerequisites
Go 1.26+
Docker and Docker Compose (for integration tests)
MySQL client (optional, for manual database access)
Unit Tests
Run unit tests (no external dependencies):
make test
Integration Tests
Integration tests run against real MySQL instances using Docker Compose.
Test against MySQL 8.0 (default):
make test-integration-80
Test against MySQL 8.4:
make test-integration-84
Test against MySQL 9.0 / 9.7 / 26.10:
make test-integration-90
make test-integration-97
make test-integration-2610
Smoke-test the built binary end to end (REST API, stdio MCP, and MCP Streamable HTTP with auth, TLS, CORS, unsafe-config refusals and session scoping; about 1.5 minutes, Docker required):
make smoke-http # MySQL 8.0
make smoke-http SMOKE_MYSQL_VERSION=26.10 # or scripts/smoke-mcp-http.sh 26.10
make smoke-http SMOKE_MYSQL_VERSION=mariadb:11.4
Test against all supported versions (MySQL & MariaDB):
make test-integration-all
Test specifically against MariaDB 11.4 or 12.3:
make test-integration-mariadb-11
make test-integration-mariadb-12
If a host port clashes with a server already running locally, override it, e.g. make test-integration-84 MYSQL84_PORT=13307. The variables are MYSQL80_PORT, MYSQL84_PORT, MYSQL90_PORT, MYSQL97_PORT, MYSQL2610_PORT, MARIADB11_PORT and MARIADB12_PORT.
The testcontainers-based client test in internal/mysql defaults to mysql:8.4; set MYSQL_TC_IMAGE (e.g. mariadb:12.3) to run it against another image. It is skipped when no Docker daemon is reachable.
Sakila Database Tests
The Sakila sample database provides comprehensive integration testing with a realistic DVD rental store schema featuring:
16 tables with foreign key relationships
Views, stored procedures, and triggers
FULLTEXT indexes and ENUM/SET types
Sample data for complex query testing
Run Sakila tests:
# Against MySQL 8.0
make test-sakila
# Against MySQL 8.4
make test-sakila-84
# Against MySQL 9.0
make test-sakila-90
For a multi-version Sakila test matrix (including alternate ports and health-check helpers), see test-steps.md at the repo root (canonical) or docs/sakila-test-steps.md.
# Start MySQL 8.0 container
make test-mysql-up
# Start all MySQL and MariaDB versions
make test-mysql-all-up
# Stop all test containers
make test-mysql-down
# View container logs
make test-mysql-logs
Environment Variables
When running tests manually, set the DSN:
# MySQL 8.0 (host port 13306 in docker-compose.test.yml — avoids local MySQL on 3306)
export MYSQL_TEST_DSN="mcpuser:mcppass00@tcp(127.0.0.1:13306)/testdb?parseTime=true"
# MySQL 8.4 (port 3307)
export MYSQL_TEST_DSN="mcpuser:mcppass00@tcp(127.0.0.1:3307)/testdb?parseTime=true"
# MySQL 9.0 (port 3308)
export MYSQL_TEST_DSN="mcpuser:mcppass00@tcp(127.0.0.1:3308)/testdb?parseTime=true"
# MySQL 9.7 (13309), MySQL 26.10 (13311), MariaDB 11.4 (3310), MariaDB 12.3 (13312)
export MYSQL_TEST_DSN="mcpuser:mcppass00@tcp(127.0.0.1:13309)/testdb?parseTime=true"
# Sakila tests read MYSQL_SAKILA_DSN (falls back to MYSQL_TEST_DSN)
export MYSQL_SAKILA_DSN="mcpuser:mcppass00@tcp(127.0.0.1:13309)/sakila?parseTime=true"
Test credentials are mcpuser / mcppass00 (see tests/sql/mcp_test_user.sql). On testdb, this user has DDL/DML so integration tests can create fixtures; sakila stays read-only via mcp_test_user_sakila.sql. After upgrading an existing Docker volume, recreate it so init scripts run: docker compose -f docker-compose.test.yml down -v.
Prefer 127.0.0.1 over localhost when the database runs in Docker (especially on macOS): localhost may resolve to IPv6 (::1) while the published port is IPv4-only, causing connection timeouts until the DSN uses 127.0.0.1.
The mysql80 service publishes 13306 on the host (not 3306) so integration tests do not accidentally connect to a different MySQL instance already listening on 3306.
Then run tests directly:
go test -v -tags=integration ./tests/integration/...
Windows: Use a Windows Service wrapper or run in a terminal; --daemon is not supported.
Use --silent to suppress INFO/WARN logs when running under a service manager. See docs/silent-and-daemon.md.
API Endpoints
Discovery (GET /api): The JSON response includes an endpoints map that lists only routes the server has registered for the current configuration—same rules as the mux: core routes always; extended routes only if MYSQL_MCP_EXTENDED=1; /api/processlist and /api/kill only if extended andMYSQL_MCP_PROCESS_ADMIN=1; /api/audit-log only if extended and read-audit is enabled (MYSQL_MCP_READ_AUDIT_TOOL=1 with MYSQL_MCP_AUDIT_LOG); /api/slow-log only if extended andMYSQL_MCP_SLOW_QUERY_TOOL=1; vector routes only if MYSQL_MCP_VECTOR=1; /status appears in the index only when the token card is enabled. modes in the JSON reflects extended, vector, and token_card.
Runtime DSN registration: There is no REST API route to register a new connection. The MCP tool add_connection (optional; MYSQL_MCP_EXTENDED=1 and MYSQL_MCP_ENABLE_ADD_CONNECTION=1) is the only supported registration path and is available over MCP (stdio or Streamable HTTP) only. In REST API mode, the process never registers tools; GET /api/connections lists only connections configured for that HTTP server process (not connections added by MCP elsewhere).
Method
Endpoint
Description
GET
/health
Health check
GET
/api
API index: registered endpoints + modes (see Discovery above)
GET
/api/databases
List databases
GET
/api/tables?database=
List tables
GET
/api/describe?database=&table=
Describe table
POST
/api/query
Run SQL query
GET
/api/ping
Ping database
GET
/api/server-info
Server info
GET
/api/connections
List connections (masked DSNs) known to this HTTP server process (config-loaded; no MCP add_connection in REST mode)
POST
/api/connections/use
Switch active connection: JSON body {"name": "<connection_name>"}. Invalid JSON or missing name → 400. Unknown connection name → 200 with success: false in the JSON body (same semantics as MCP use_connection).
POST /api/connections/use response: JSON with success, active, message, database when applicable (see Response Format).
Not implemented over HTTP:POST /api/connections (register new DSN) — use MCP add_connection when enabled.
Tail lines from the MCP audit log (JSON). Listed only when extended andMYSQL_MCP_READ_AUDIT_TOOL=1 with MYSQL_MCP_AUDIT_LOG configured.
GET
/api/slow-log?limit=
Slow query log rows or file/table settings. Listed only when extended andMYSQL_MCP_SLOW_QUERY_TOOL=1.
GET
/api/processlist
Active MySQL threads (SHOW FULL PROCESSLIST). Listed only when extended andMYSQL_MCP_PROCESS_ADMIN=1. Requires MySQL PROCESS (or equivalent) to succeed.
POST
/api/kill
Cancel the current statement on a connection: JSON body {"id": <positive integer>} (same id as /api/processlist). Executes KILL QUERY—the client connection stays open. Listed only when extended andMYSQL_MCP_PROCESS_ADMIN=1. Requires privilege to run KILL QUERY for that thread (e.g. CONNECTION_ADMIN or PROCESS as applicable).
Vector endpoints (requires MYSQL_MCP_VECTOR=1):
Method
Endpoint
Description
POST
/api/vector/search
Vector similarity search
GET
/api/vector/info?database=
Vector column info
Token metrics (HTTP mode; /status defaults on when MYSQL_MCP_HTTP is set—use MYSQL_MCP_TOKEN_CARD=0 to hide it; YAML features.token_card applies when not using that default):
SQL Query Optimization Guide: Practical optimization patterns and query rewriting techniques using the Stack Exchange schema.
Comprehensive MySQL Query Optimization Guide: Deep technical insights into the query optimizer, advanced indexing strategies, execution plan analysis, and operational best practices.
Project Structure
cmd/mysql-mcp-server/
├── main.go -> Server entrypoint and tool registration
├── types.go -> Input/output struct types for tools
├── tools.go -> Core MCP tool handlers
├── tools_extended.go -> Extended MCP tool handlers
├── http.go -> HTTP REST API handlers and server
├── connection.go -> Multi-DSN connection manager
└── logging.go -> Structured and audit logging
internal/
├── api/ -> HTTP middleware and response utilities
├── config/ -> Configuration loader from environment
├── mysql/ -> MySQL client wrapper + tests
└── util/ -> Shared utilities (SQL validation, identifiers)
examples/ -> Example configs and test data
scripts/ -> Quickstart and utility scripts
bin/ -> Built binaries
Examples
The examples/ folder contains:
claude_desktop_config.json - Example Claude Desktop configuration
test-dataset.sql - Demo database with tables, views, and sample data
Load the test dataset:
mysql -u root -p < examples/test-dataset.sql
This creates a mcp_demo database with:
5 categories, 13 products, 8 customers
9 orders with 16 order items
Views: order_summary, product_inventory
Stored procedure: GetCustomerOrders
Stored function: GetProductStock
Development
make fmt # Format code
make lint # Run linter
make test # Run unit tests
make build # Build binary
make release # Build release binaries
Releasing
Releases are automated via GitHub Actions and GoReleaser. Full checklist: docs/releasing.md.
Quick steps: update CHANGELOG.md, commit, then git tag vX.Y.Z and git push origin vX.Y.Z. After the workflow runs, complete post-release steps (CHANGELOG on main if needed, Homebrew tap README, local brew upgrade). See the doc for details.
Noch keine Tool-Liste. Remote-Server erhalten eine nach dem ersten Health-Check.
FAQ
Fragen
Wie installiere ich Mysql?
Kopieren Sie auf dieser Seite die stdio-Konfiguration für Cursor, Claude Desktop, Claude Code oder VS Code. Sie nutzt die Installation des Herausgebers, keinen PlugMCP-Proxy.
Benötigt Mysql einen API-Schlüssel?
In diesem Eintrag ist keine erforderliche Umgebungsvariable aufgeführt.
Welchen Transport verwendet Mysql?
Mysql läuft lokal über stdio.
Wann wurde Mysql zuletzt geprüft?
Zuletzt geprüft: 2026-10-28. MySQL Server implementation for Model Context Protocol (MCP) written in Go.