
MySQL (security-first)
io.github.Kurok1由 GitHub 账号 Kurok1 发布v2.1.0更新于 Oct 24, 2026
Security-first MySQL MCP server with AST validation, table whitelist, schema resources, and audit.
概览
以安全为先的 MySQL MCP 服务器,让助手在 AST 校验、数据表白名单与默认只读限制下查询数据库。
- 可以做什么
- 列出已配置的连接配置,并查看各配置的查询统计与慢查询。
- 适用场景
- 当你希望让 AI 助手以只读或受控方式查询 MySQL 数据库,又不希望它随意改动数据时适用。适合需要多个连接配置、数据表白名单与审计记录的开发或分析场景。
- 运行要求
- 需在本机运行单个可执行文件或 Docker 容器,并提供配置文件(路径可由 --config 或 MYSQL_MCP_CONFIG 指定)。需可连接的 MySQL 8.x 数据库与专用账号,密码通过 MYSQL_MCP_PASSWORD 环境变量提供。
安装
在 SourceWeft 中
- 打开 控制台中的 MySQL (security-first),将其添加到工作区。
- 为需要使用其工具的对话启用该服务。
Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。
其他 MCP 客户端
参照 仓库 中的启动说明。
README
mcp-server-mysql
English | 简体中文
[Release] [License] [Go] [Docker]
A security-first MySQL MCP server. Every SQL statement must survive a full AST parse by an industrial-grade SQL parser (TiDB parser) before it can touch your database — backed by a read-only transaction fallback and a driver-level multi-statement lockout. Three independent layers of defense-in-depth: let AI query your database, without letting it walk off with your database.
Why this one?
Most MySQL MCP servers enforce "read-only" with regex/keyword matching, or by wrapping queries in a read-only transaction. Both are broken:
- Regex checks are defeated by SQL comments and creative rewriting.
- A read-only transaction alone is defeated by
COMMIT; DROP TABLE ...stacked-statement injection — the exact attack Datadog demonstrated against the official Postgres reference server, which has since been archived.
This project puts the security boundary on real SQL semantic parsing instead. Every statement is parsed into an AST by the TiDB parser (MySQL 8.0-grammar compatible); anything the parser cannot understand is rejected — fail-closed, so incomplete grammar coverage can only over-block, never under-block. And because the parser sees real MySQL semantics, tricks like hiding a JOIN mysql.user inside a versioned comment /*!80000 ... */ are extracted and checked like any other table reference.
Highlights
- Independent connection profiles — one process manages multiple MySQL connections, each with its own pool, security rules, audit files, and statistics. Discover names and descriptions with
list_profile, then pass an explicitprofileto every SQL tool. - Statement-class gating —
SELECT/INSERT/UPDATE/DELETE/ DDL are individually switchable; the default is read-only.SET,GRANT,CALL,USE,LOAD DATA,LOCK TABLES, and transaction control (BEGIN/COMMIT/ROLLBACK) are rejected unconditionally — classification itself is an allowlist, so unknown statement types land on the deny side by construction. - Default-deny table whitelist — nothing is visible until whitelisted; patterns like
db.*,db.table,app_*.logs(glob per side, case-insensitive). Every table reference is extracted from the AST: JOINs, subqueries, derived tables, CTEs (scope-aware — a CTE name can't shadow a real table to smuggle it past the check), multi-table DML,INSERT ... SELECT, and versioned comments. - MCP table-schema resources — after the MCP connection initializes, every privilege-visible, whitelisted base table is exposed as
mysql:///schema/{profile}/{database}/{table}. Reading a resource returns liveSHOW CREATE TABLESQL with only the volatile table-levelAUTO_INCREMENT=Ncounter removed. - Execution guardrails — hard row cap, per-query timeout, single-statement enforcement, and a tripwire for
UPDATE/DELETEwithoutWHERE. - Built-in observability — per-query latency and row counts, slow-query flagging, and a
mysql_statstool so you can ask "which query was slowest?" right in the conversation. - Structured audit, opt-in — JSONL with daily rotation; denied SQL is recorded with the exact rule that fired. Off by default: no log files unless you enable it.
- Atomic scripts —
mysql_scriptruns a multi-statement script in a single transaction with every statement individually re-validated; any failure rolls back everything. DDL is banned inside scripts because MySQL's implicit commit would break atomicity. - Query-plan analysis —
mysql_explainwithtraditional/json/treeformats andEXPLAIN ANALYZEsupport. - Interactive query results — MCP Apps-capable hosts render
mysql_queryas a filterable, sortable table with per-view history, selection, column controls, and TSV/CSV/JSON copy; other hosts keep receiving the original text result. - Easy to run, small to trust — a single static Go binary with stdio by default, built on the official MCP Go SDK; the Docker image is distroless and runs as a non-root user.
Tools
All seven mysql_* tools require a non-empty profile string matching a configured name. There is no default connection: missing or unknown profiles are rejected before database access. mysql_describe_table defaults its optional database argument to the selected profile's database.
For example, call list_profile with {}, then mysql_query with {"profile":"dev","sql":"SELECT * FROM myapp.orders LIMIT 10"} or mysql_stats with {"profile":"dev","top_n":5}. Keep the same profile when inspecting, changing, and verifying data.
Resources
The server takes a table snapshot for each profile during MCP initialization/discovery and registers one direct resource per visible base table. Resource names also identify the profile, so identical database and table names on different servers stay distinct:
"Visible" is the intersection of what the profile's MySQL account can see and its security.table_whitelist. Views are not registered. Resource discovery is not capped by security.max_rows, and resource reads remain available even when select is absent from allowed_statements, because both operations execute fixed server-owned metadata SQL rather than user-submitted SQL.
The resource set is a discovery-time snapshot: a table created later appears after the next discovery or reconnect, while a dropped or newly inaccessible table returns MCP Resource Not Found. The resource content is live, so ALTER TABLE is reflected on the next read. Resource discovery and reads do not enter the audit log or mysql_stats; a discovery failure is logged with the profile name and clears only that profile's table resources; other profiles, tools, and the shared query-results App remain available.
The root-level resources.enabled switch applies to every profile. Set it to false to disable the entire resource feature. It defaults to true; when disabled, the server does not advertise Resources, register table or MCP App resources, or query any profile's MySQL during initialization/discovery. The interactive MCP App is therefore unavailable, while all eight tools, including mysql_query's text and structured results, remain available.
Quick start
1. Get the binary
Prebuilt — download the tarball for your platform (linux_amd64 / linux_arm64 / darwin_arm64) from Releases (checksums included), or install with Go:
Docker — multi-arch images are published to GitHub Container Registry:
2. Configure
Copy config.example.yaml and adjust:
A minimal config:
Add sibling entries under profiles for other connections; each accepts the same mysql, security, and audit fields. The annotated example includes two profiles. The client examples below use this minimal config; for other configurations, pass every referenced password environment variable to the MCP process.
3. Wire up your MCP client
Claude Code:
Claude Desktop or any JSON-configured client:
Docker:
Docker note 1 — audit logs must live on a mounted volume. The container is destroyed with the session; if you enable audit logging, point
audit.log_dirat the mounted volume (e.g./data/logs) or the logs vanish with the container.Docker note 2 — reaching MySQL on the host. On macOS/Windows set
mysql.host: host.docker.internal; on Linux also append"--add-host=host.docker.internal:host-gateway"toargs.
Interactive query results (MCP Apps)
mysql_query advertises the embedded ui://mcp-server-mysql/query-results resource to hosts that support MCP Apps. Successful calls include both the existing human-readable text and structured query data with a required profile field, so older or text-only hosts degrade without losing any result information. Query errors retain their text and carry the original {profile, sql} in result metadata so the App can identify the request. list_profile also returns text and structured data; the six remaining tools use text results.
The result view keeps up to 20 snapshots inside the current View, supports global and optional status filtering, natural numeric sorting, column visibility, row selection, and TSV/CSV/JSON copy. Results and history identify their profile, including failed and cancelled requests. Refresh invokes mysql_query through the host with the selected snapshot's original {profile, sql}, including after switching history; if the host does not expose tool calling to apps, the view explains that refresh is unavailable while all read-only controls continue to work. View history is memory-only and disappears when the View closes.
When overlapping requests receive a Host error or cancellation without enough information to identify the request, history marks its source as undetermined and preserves the candidate inputs. It does not assign that notification to a profile based on arrival order.
Local Basic Host development
The production/default transport remains stdio. A stateless Streamable HTTP endpoint is available specifically for local MCP Apps development:
Connect the official Basic Host to http://127.0.0.1:3001/mcp. The HTTP listener rejects wildcard and non-loopback addresses, and its CORS policy only accepts the Basic Host origins on local port 8080; it is not an authenticated remote deployment mode.
Security model
Layer 0 — your MySQL account (strongly recommended). Run the server with a dedicated account that has only the privileges you intend to use (read-only workloads get SELECT only). Never root. This is the containment layer everything below reinforces.
Layer 1 — the AST main gate. Every statement is parsed by the TiDB parser (parse failure ⇒ denied), then must pass, in order: single-statement enforcement → statement-class allowlist (with a read/write tool cross-check: a write sent through mysql_query is denied even if writes are enabled) → per-class enable switches → dangerous-construct scan (SELECT ... INTO OUTFILE/DUMPFILE, LOAD_FILE() at any nesting depth) → missing-WHERE tripwire → full table-reference extraction checked against the default-deny whitelist.
Layer 2 — read-only transaction fallback. Reads executed through the single-statement read path (mysql_query, mysql_explain, mysql_list_tables, mysql_describe_table) and the fixed resource metadata path run inside START TRANSACTION READ ONLY — if the parser ever misclassified a write as a read, MySQL itself rejects it. (Write statements you explicitly enabled, and everything inside mysql_script — reads included — run outside this backstop; there, Layer 1 and Layer 0 are the controls.)
Layer 3 — driver-level lockout. The connection sets multiStatements=false, so COMMIT; DROP TABLE ...-style stacked injection is impossible at the protocol level even if every layer above failed.
Every denial comes back as machine-readable text — DENIED [rule_name]: reason — and the rule names are stable:
mysql_script denials prefix the reason with the position of the offending statement: DENIED [rule]: statement N: reason.
The guard is the test suite's center of gravity: ~100 table-driven cases cover stacked-statement injection, versioned-comment smuggling, CTE-shadowing whitelist bypasses, INSERT ... SELECT table extraction, and more; end-to-end tests — whitelist enforcement, the READ ONLY backstop rejecting writes, script rollback, EXPLAIN-tree denials — run against a real MySQL 8.0 in testcontainers.
The fine print
Security documentation you can't verify is marketing. The precise boundaries:
- The read-only transaction backstop covers the single-statement read path. Write types you explicitly enable — and every statement inside
mysql_script, reads included, since they share the script's read-write transaction — execute without it; there, the AST gate plus your database account privileges (Layer 0) are the controls. unfiltered_writeis a missing-WHEREtripwire, not full-table-write prevention:UPDATE t SET a=1 WHERE 1=1passes it. It catches mistakes, not malice.- Fixed, non-user metadata SQL is used by
mysql_list_tablesand MCP resource discovery/read. Table discovery queriesinformation_schemafor base tables and filters every result through the whitelist; resource reads re-check the whitelist beforeSHOW CREATE TABLE.EXPLAIN FORMAT=TREEis another fixed-prefix path: the innerSELECTstill passes the full guard pipeline first (the TiDB parser cannot parseFORMAT=TREEas a whole statement). - Audit records cover SQL that reaches the guard pipeline, allowed and denied. Not audited: MCP resource discovery/reads,
mysql_statscalls,mysql_describe_tablepre-check denials (invalid_identifierand itstable_whitelistname check), andmysql_explainparameter denials (invalid_query,not_select,invalid_format). Script auditing follows actual execution: a guard-denied script yields one record for the whole script, and statements after a failed one — validated but never executed — are not recorded. - The MySQL connection is plain TCP — no TLS option and no Unix socket yet. Keep the server and the database on a trusted network, or tunnel the connection.
Configuration
profiles is a non-empty map. Names must match [a-z0-9][a-z0-9_-]*; description is optional and defaults to an empty string. Each profile independently applies the same defaults, without inheriting from other profiles. In the table below, mysql.*, security.*, audit.*, and description live under profiles.<name>; only resources.enabled is global.
Full annotated example: config.example.yaml. The governing principle is secure by default: omit allowed_statements and you're read-only; omit table_whitelist and everything is denied; leave block_unfiltered_writes unset and it's on.
And it fails closed at startup: an unreadable file, an unknown/misspelled key, an invalid duration, a malformed whitelist pattern, an unknown statement type, a negative script cap, or a missing mysql.user/mysql.database all abort the process — it refuses to run sick rather than degrade silently.
Secrets never need to live in the file: the whole config is passed through environment-variable expansion before parsing, so ${ENV_VAR} works in any field. The config path itself can come from the MYSQL_MCP_CONFIG environment variable instead of --config.
Migrating a single-connection config
- Move the old root
mysql,security, andauditsections intact under a name such asprofiles.dev; keepresourcesat the root. - Add
profileto all sevenmysql_*tool calls. Uselist_profileto discover available names. There is no implicitdefaultprofile, even with one connection. - Restart the server and reconnect clients to refresh tool schemas and the new profile-qualified Resource URIs.
Legacy root connection settings, empty/invalid profiles, and unknown configuration fields are rejected. Profiles are static until restart. Pool construction is lazy: an unreachable database fails when that profile's tools/resources access it, while list_profile still lists the configured entry. A SQL statement or script uses one profile; existing whitelist-approved cross-schema access within that connection remains available. Cross-profile transactions and runtime profile management are not supported.
Audit log
Disk logging is controlled independently by each profile's audit.enabled — default false: no log files, no log directory created. Each profile has its own in-memory statistics ring and slow-query threshold; mysql_stats reads only the requested profile's window and includes its name. Statistics are shared by callers using that profile in the process, work regardless of disk logging, and reset on restart.
When enabled, JSONL files rotate daily as audit-<profile>-<YYYY-MM-DD>.jsonl (for example, audit-dev-2026-09-15.jsonl). Profiles can share audit.log_dir without sharing files. Each line is one JSON object:
Claude Code skill
skills/mysql-mcp is a companion skill that teaches Claude to use these tools well: pick the right tool, respect the security boundaries (single statement, whitelist, WHERE tripwire), and read DENIED [rule] messages correctly instead of blindly retrying. Install:
Compatibility
- MySQL 8.x — the E2E suite runs against MySQL 8.0 (8.0.45) via testcontainers. MySQL 5.7 and MariaDB are untested.
- MCP — Go SDK v1.7.0, with direct MySQL table-schema resources, the
io.modelcontextprotocol/uiextension, and one embedded MCP App resource. Text fallback remains available to hosts without MCP Apps. - Transport — stdio by default; loopback-only stateless Streamable HTTP is available for local development. Server identity is
mcp-server-mysql; it exposes 8 tools, direct table-schema resources, one shared UI resource, and no prompts.
Development
The frontend uses React/TypeScript, @modelcontextprotocol/ext-apps, and vite-plugin-singlefile. Its build emits one fully inlined HTML file and copies it to internal/ui/query-results.html, which Go embeds into the binary; a normal go build therefore does not require Node. The Dockerfile rebuilds the frontend in a Node stage and overwrites that committed bundle before compiling Go, preventing stale UI in release images.
Design docs live in docs/superpowers — each feature ships with a spec and an implementation plan.
License
来源:README.md,提交 973b84b
工具
0版本历史
1- v2.1.0最新Sep 16, 2026
评分
已满足适用检查项的 50%
该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。
- 近 30 天内可连通25 分
请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。
- 已声明认证方式10 分
请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。
- 已列出工具15 分
请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。
- 描述必需15 分
- 图标10 分
- 文档15 分
- 许可证10 分