db-mcp
Provides read-only SQL access to a MySQL database for AI agents: discovers schemas, tables, views, columns, indexes, and routines, and runs guarded read-only SELECT/WITH/SHOW/DESCRIBE/EXPLAIN queries with a 500-row limit and 30-second timeout.
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., "@db-mcp Show me the 10 most recent orders and their total amounts."
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.
@openmaxai/db-mcp
A read-only stdio MCP server that lets an AI agent explore and query a MySQL database in natural language. It wraps a pinned version of DBHub (MIT) and starts it with guardrails that cannot be changed from the outside:
Guardrail | Value |
Read-only account (hard boundary) | At startup db-mcp reads the account's |
Read-only mode (defence in depth) |
|
Row limit | 500 rows per |
No SQL comments | SQL containing |
Query timeout | 30 seconds (server-side |
Connection timeout | 15 seconds |
Connection pool | at most 2 connections |
Tools | only |
The guardrails are hard-coded in the package. No environment variable, argument or file changes them.
All configuration comes from environment variables.
DB_PASSWORDis the only secret.The database must be reachable over the public internet. Loopback, private, link-local and cloud-metadata addresses are refused.
TLS with certificate verification by default: the server certificate must chain to a trusted CA and match
DB_HOST(see TLS).Logs go to stderr only (stdout carries the MCP protocol). Passwords and DSNs are never logged.
The account's privileges are the only hard write boundary. db-mcp only offers reads, whatever account it connects with, but DBHub's read-only mode and db-mcp's comment ban are defence in depth, not a permission boundary. We strongly recommend a dedicated read-only database account (see Create a read-only account). db-mcp checks the account at startup; by default (owner decision) a write-capable account is still allowed to connect, with one warning on stderr, and
DB_MCP_GRANT_CHECK=refusemakes it refuse such accounts. See SECURITY.md for what DBHub's read-only mode does and does not stop.
Requires Node.js 22.5 or newer (DBHub uses the built-in node:sqlite module). On older versions the server exits with a readable error.
Install (Claude Code)
claude mcp add-json database '{
"command": "npx",
"args": ["-y", "@openmaxai/db-mcp@0.1.1"],
"env": {
"DB_TYPE": "mysql",
"DB_HOST": "db.example.com",
"DB_PORT": "3306",
"DB_NAME": "shop",
"DB_USER": "ai_readonly",
"DB_PASSWORD": "<password of the read-only account>",
"DB_SSLMODE": "verify-full",
"npm_config_omit": "optional",
"npm_config_ignore_scripts": "true"
}
}'If your provider's server certificates are not issued by a public CA (for example AWS RDS or Alibaba Cloud RDS), also set DB_SSL_CA to the provider's CA certificate (see TLS).
Any other MCP client works the same way: run npx -y @openmaxai/db-mcp with the environment below.
The two npm_config_* entries only affect how npx installs the package. DBHub declares drivers for many databases (Oracle, SQL Server, PostgreSQL, MariaDB, ClickHouse…) as optional dependencies, and ssh2 runs a native build script. This package brings its own MySQL driver and needs neither, so skipping optional dependencies and install scripts cuts the first install from about 95 MB to about 37 MB and runs no third-party install scripts on the agent's machine. The OpenMax connector template sets both.
After adding the connection, ask the agent to list the tables once (search_objects). The server connects once at startup to check the account's privileges. By default (DB_MCP_GRANT_CHECK=warn) it starts whatever the outcome: connection problems (wrong password, firewall, unreachable host) come back as tool errors on the first tool call, and a write-capable or unverifiable account produces no tool error at all, only one warning on stderr at startup (check your MCP client's server log). With DB_MCP_GRANT_CHECK=refuse any of these keeps it from connecting DBHub instead: the tools are still listed, and every tool call returns a CONFIG_ERROR tool error with the reason (see Configuration errors).
Related MCP server: easy-mysql-mcp
Configuration
Variable | Required | Default | Notes |
| no |
| Only |
| yes | Public host name: the name in the server certificate. No URL, no | |
| no |
| Empty means the default. |
| yes | The database (schema) to query. | |
| yes | A read-only account. | |
| yes | The only secret. Any characters are allowed; it is not trimmed. | |
| no |
|
|
| no | Extra trusted CA certificate(s) for | |
| no |
|
|
| no |
| What to do when the account can write or its privileges cannot be verified: |
The configuration is checked at startup. If something is missing or invalid, the server lists every problem it found on stderr and in every tool result (see below). The password is never printed, even when it was pasted into the wrong variable: on stderr an invalid value is echoed only masked (and a URL or anything containing @ in DB_HOST is not echoed at all, since it may hold the password), and the text the agent receives echoes no values.
Configuration errors (degraded mode)
When db-mcp can not start safely, it does not exit. It starts a minimal MCP server instead that lists the same two tools (execute_sql, search_objects, with the same input schemas) and answers every tool call with a tool error like this:
{
"success": false,
"error": "DB_HOST=10.0.0.7 is a private network (RFC 1918) address. Only public database addresses are allowed (...)\n\ndb-mcp has not connected to the database and will not until the configuration is fixed. Fix the settings of this database connection (...), then restart the agent session.",
"code": "CONFIG_ERROR"
}So the agent can tell the user what is wrong and how to fix it, instead of seeing "no such tool". The problem is also logged to stderr. The MCP initialize result carries one fixed sentence in instructions ("db-mcp could not start because of a configuration problem; every tool call returns the details as a CONFIG_ERROR tool error."), never the problem text: clients may treat instructions as system-level guidance. This happens for:
an invalid or incomplete environment (a missing
DB_NAME, a badDB_PORT,DB_SSLMODE=require, an IP-addressDB_HOSTunderverify-full: "use the host name your provider gives you (the one in the server certificate)", ...);a refused
DB_HOST: a loopback, private, link-local, CGNAT or cloud-metadata address, a local / internal name, or a name that resolves to one ("private networks, loopback and cloud metadata endpoints are blocked"), or a name that can not be resolved (see Host check);under the opt-in
DB_MCP_GRANT_CHECK=refuse: a privilege check that refuses the account (it can write, or its privileges can not be verified) or that could not connect (wrong password, TLS certificate verification failed, unreachable), with the reason. Under the defaultwarnthese do not stop DBHub, as before.
After a refusal, the details the database server or the driver gave (the error message, the privileges or roles it listed) are untrusted text: a server, or anything on the network path before TLS is verified, can put any text into an error. db-mcp quotes it in the tool error between <<<BEGIN UNTRUSTED SERVER TEXT and END UNTRUSTED SERVER TEXT>>> lines, on one line (line breaks flattened, < / > replaced so it can not close the quote) and cut to 1024 characters, after its own summary of the problem.
In degraded mode no database connection is made (after a configuration or host error none was made at all; after a refusal only the privilege check's own connection), DBHub is not started, and the tool arguments are not looked at. The message never contains the password, and echoes no configuration values. The server exits with code 2 when the client closes the connection. Fix the connection's settings and restart the agent session; db-mcp reads its configuration only at startup.
A Node.js older than 22.5 is the one startup error that still exits immediately (code 2, message on stderr): the server can not run at all.
Host check
DB_HOST and every address it resolves to must be public. These are refused: loopback (127.0.0.0/8, ::1, localhost), private networks (10/8, 172.16/12, 192.168/16, fc00::/7), link-local (169.254/16, fe80::/10), carrier-grade NAT (100.64/10), cloud metadata endpoints (169.254.169.254, 100.100.100.200, fd00:ec2::254, metadata.google.internal, ...), multicast and reserved ranges, IPv4 addresses embedded in IPv6, and .local / .internal names. A host name that cannot be resolved is also refused. A refused host is reported as CONFIG_ERROR on every tool call (see Configuration errors); nothing connects to it.
The host name is resolved once, at startup. The server then connects only to an address it checked (the first IPv4 address, otherwise the first IPv6 address), so a DNS answer that changes after the check (DNS rebinding) cannot redirect the connection. DBHub is given the name (to verify the certificate against it), but its process can only resolve that name to the checked address and can resolve no other name. If your database's DNS record changes (for example after a managed-database failover), restart the agent session so the server resolves the name again.
TLS
With DB_SSLMODE=verify-full (the default) both of db-mcp's connections, the startup privilege check and DBHub's, use TLS and verify the server certificate: it must chain to a trusted CA, and its subject alternative names (or common name) must include DB_HOST. The TCP connection still goes to the checked address. A connection that fails verification is refused (under DB_MCP_GRANT_CHECK=refuse every tool call returns CONFIG_ERROR with the TLS error; otherwise a warning at startup and the TLS error as a tool error).
Trusted CAs are Node.js's bundled public CAs (the Mozilla list), plus
DB_SSL_CAif set. WithoutDB_SSL_CA, aNODE_EXTRA_CA_CERTSfrom the agent's environment is honoured as well; withDB_SSL_CA, it replacesNODE_EXTRA_CA_CERTS.Providers with their own CA: download the provider's CA bundle and put it in
DB_SSL_CA, as PEM text or as a file path. For AWS RDS / Aurora, the global bundlehttps://truststore.pki.rds.amazonaws.com/global/global-bundle.pem(or the bundle for your region); for Alibaba Cloud RDS, the CA certificate you download from the instance's SSL settings in the console. Providers whose certificates come from a public CA (for example Azure Database for MySQL, or a certificate from Let's Encrypt) need noDB_SSL_CA.Use the host name the certificate was issued for. An IP address can not be verified (
DB_HOSTmust be a name underverify-full), and a CNAME of your own fails unless the certificate also lists it. Check withopenssl s_client -starttls mysql -connect <host>:3306 -servername <host>if unsure.requireis refused. Encryption without verification lets an attacker on the network path read the password and the results, so db-mcp offers no such mode.DB_SSLMODE=disableremains for servers without TLS; it sends the password in plaintext and logs a warning.
Private databases, SSH tunnels and VPNs are out of scope for this version. If you need one, run DBHub yourself inside your network and connect to it as a remote MCP server.
Privilege check
Before starting DBHub, db-mcp connects once (same address, TLS mode and credentials), runs SHOW GRANTS and reads @@global.mandatory_roles. Plain SHOW GRANTS (without FOR CURRENT_USER()) also lists what the account holds through no grant row of its own: privileges granted TO PUBLIC (MariaDB 10.11+, in effect for every account without SET ROLE) and the server's mandatory roles (MySQL 8).
Allowed, at any scope:
SELECT,SHOW VIEW,SHOW DATABASES,USAGE.Write-capable: any other privilege at any scope, held directly or granted
TO PUBLIC(MariaDB; reported as... (granted to PUBLIC)), including column-level ones (UPDATE (qty)),ALL [PRIVILEGES],INSERT,UPDATE,DELETE,CREATE,DROP,ALTER,INDEX,CREATE TEMPORARY TABLES,LOCK TABLES,EXECUTE,CREATE ROUTINE,ALTER ROUTINE,EVENT,TRIGGER,FILE,SUPER,PROCESS,RELOAD,SHUTDOWN,REPLICATION ..., dynamic privileges (..._ADMIN, ...),PROXYandWITH GRANT OPTION.Not verifiable: role grants and a non-empty server-wide
mandatory_roles(the session can switch a role's privileges on withSET ROLE, so whatSHOW GRANTSlists for the current session does not bound what it can do), output it cannot parse, or a failed connection. Mandatory roles show up both as a role line inSHOW GRANTSand in the variable; the variable is read as well so the check does not depend on that one output detail. On servers withoutmandatory_roles(MariaDB, MySQL 5.7) the "unknown system variable" error is read as "no mandatory roles"; any other error reading it fails the check.Not seen: views and stored routines that run with their definer's privileges (
SQL SECURITY DEFINER); only the privilegesSHOW GRANTSlists for the session are checked. See SECURITY.md, Known gap 13.
With DB_MCP_GRANT_CHECK=warn (the default, by owner decision: accounts that are not read-only may connect, db-mcp only offers reads) a write-capable or unverifiable account starts, and the server logs one message to stderr listing the offending privileges (never the password); it is not repeated in tool results. With DB_MCP_GRANT_CHECK=refuse (opt-in for strict deployments) the same account keeps DBHub from starting: the server logs the same message and returns it as a CONFIG_ERROR tool error on every tool call (see Configuration errors). The check runs at startup only: restart the agent session after changing the account's grants.
What the default means. With a write-capable account the tool still only runs read-only SQL, but nothing hard stops a write any more: write protection then rests only on DBHub's read-only classifier, its read-only transaction and db-mcp's comment ban. These are best effort, not a guarantee. They are not independent (a batch that fools the classifier can end the read-only transaction itself), and a classifier bypass has been found before (a
#comment hid a write, see SECURITY.md Known gap 12; the comment ban now blocks it). A read-only account remains the only hard write boundary, so we still strongly recommend one, andDB_MCP_GRANT_CHECK=refusefor deployments that must not run with anything else.
Comments are rejected (false positives)
Any #, -- or /* in the SQL is rejected, also inside a string literal or quoted name, because db-mcp cannot know the server's sql_mode and quoting rules. For example WHERE color = '#fff', LIKE '%--%' and SELECT 1--1 are refused. Write them without the sequence: CONCAT('color ', CHAR(35 USING utf8mb4), 'fff') for #, CONCAT('-', '-') for --, CONCAT('/', '*') for /*, 1 - -1 for 1--1. The error message tells the agent this.
Create a read-only account
Create a dedicated account that can only read the database you connect, and connect with that account only. The account's privileges are the hard boundary (db-mcp checks them at startup); db-mcp's read-only mode is defence in depth. Grant privileges directly, not through a role: a session can activate a role's privileges with SET ROLE, so roles (including the server's mandatory_roles) cannot be verified and are reported as not verifiable (a warning by default, CONFIG_ERROR under DB_MCP_GRANT_CHECK=refuse).
-- Replace shop with your database name. Use a long random password.
CREATE USER 'ai_readonly'@'%' IDENTIFIED BY '<long random password>' REQUIRE SSL;
GRANT SELECT, SHOW VIEW ON shop.* TO 'ai_readonly'@'%';
ALTER USER 'ai_readonly'@'%' WITH MAX_USER_CONNECTIONS 5;Do not grant
FILE,SUPER,PROCESS,EXECUTE,CREATE ROUTINEor any privilege onmysql.*or*.*. Read-only transactions do not stop functions such asLOAD_FILE(); only the missing privilege does.To expose only some columns (for example to keep phone numbers and addresses out), create views with just those columns and grant
SELECTon the views only, not on the tables:CREATE VIEW shop.orders_for_ai AS SELECT id, created_at, status, total FROM shop.orders; GRANT SELECT, SHOW VIEW ON shop.orders_for_ai TO 'ai_readonly'@'%';
Network access (egress)
The connection to your database is opened from the machine where the agent runs, not from an OpenMax server. Your database must be reachable from that machine over the public internet. Keep DB_SSLMODE at verify-full (the default) so the traffic is encrypted and the server is authenticated by its certificate (see TLS).
Data and credential caveats
Query results go to the AI model. Everything the agent reads (rows, column names, table names) becomes part of the model context, is sent to the model provider and may appear in the conversation history. Customer tables often contain personal data (names, phone numbers, addresses). Limit what the account can read (views, see above). The 500-row limit reduces, but does not prevent, exposure.
The password is stored in plaintext on the agent machine. The MCP client keeps the server configuration, including
DB_PASSWORD, in its own config file (for Claude Code~/.claude.json, for Codex~/.codex/config.toml). Anyone with access to that machine account can read it. This is why the account must be read-only and narrowly scoped.Never type the database password into a chat. Enter it only in the connection form. An agent should never ask for it.
db-mcp does not keep a query log. Use your database's own audit log if you need one.
Tools
Tool | Description |
| Lists schemas, tables, views, columns, indexes and routines, with a LIKE pattern. Use it first to learn the schema. |
| Runs read-only SQL: |
Results and errors are DBHub's JSON format. Connection problems come back as a tool error such as SOURCE_UNREACHABLE, not as a server crash (under DB_MCP_GRANT_CHECK=refuse, a connection problem at startup gives CONFIG_ERROR instead, see Configuration errors). DBHub names the source by DB_HOST in its messages (for example connection errors such as SOURCE_UNREACHABLE carry "source_id": "db.example.com").
Dates and times
DATETIME and DATE values come back exactly as stored, as ISO strings with a trailing Z: a DATETIME 2026-12-01 21:23:00 is returned as "2026-12-01T21:23:00.000Z" and a DATE 2026-12-01 as "2026-12-01T00:00:00.000Z", whatever the time zone of the agent's machine. These columns have no time zone, so the digits are the server's wall-clock time; the Z is not a claim that the value is UTC. (db-mcp sets the MySQL driver's timezone to Z; up to 0.1.0 the driver used the agent machine's local zone, so on a +08:00 machine 21:23 came back as 13:23Z and dates as the previous day.)
Both tool descriptions start with a note saying this ("DATETIME and DATE values are returned with the digits stored in the database and a trailing "Z" that is only formatting: they have no time zone, so do not convert them to another time zone. ..."), so that the model does not convert them to the user's zone (which would bring the shift back). It is DBHub's source description, which DBHub puts in front of the tool descriptions.
TIMESTAMP values are converted by the server to the session time zone, which db-mcp leaves at the server's default (it does not set time_zone, so NOW(), CURDATE() and comparisons with DATETIME columns behave as in any other client). They are returned with the digits a MySQL client using the server's default time zone shows, again with a cosmetic Z. They are the true UTC instant only when the server's time zone is UTC (SELECT @@session.time_zone, @@system_time_zone tells you). For an unambiguous instant, ask for it in the query: UNIX_TIMESTAMP(ts) returns seconds since the epoch (UTC).
Query timeout and SLEEP()
A statement that runs longer than 30 seconds is stopped by the server (max_execution_time) and normally comes back as a tool error ("Query execution was interrupted, maximum statement execution time exceeded", MySQL error 3024). One exception is MySQL's documented behaviour: a query that consists only of SELECT SLEEP(n) and is interrupted returns 1 and no error, so SELECT SLEEP(40) "succeeds" with 1 after about 30 seconds. SHOW / DESCRIBE statements are not covered by max_execution_time and are cancelled by DBHub's client-side deadline after about 35 seconds.
How it works
On start, db-mcp:
checks the Node.js version, validates the environment and checks the host (on an error it serves degraded mode and stops here);
connects once to the checked address and checks the account's privileges with
SHOW GRANTS(one warning if it can write under the defaultDB_MCP_GRANT_CHECK=warn; degraded mode underrefuse);writes a DBHub config file (
dbhub.toml, mode 0600) into a new private temporary directory (mode 0700), andDB_SSL_CAasca.pem(mode 0600) if set. The file holds the guardrails, the host name (also DBHub's source id), the port, the SSL mode and the driver time zoneZ(see Dates and times). The user name, database name and password are not written to disk: the file references${DB_USER},${DB_NAME}and${DB_PASSWORD}, which DBHub reads from its environment;starts the pinned DBHub with
--transport stdio --config <file>, inside that directory, with a minimal environment (noDSN,DB_*,TRANSPORT,NODE_OPTIONS, API keys or other variables from the agent's environment), and with db-mcp's DNS pin preloaded (--import dist/dns-pin.js): in the DBHub process the database host name resolves only to the checked address, and no other name resolves;relays the MCP messages between the client and DBHub through a small JSON-RPC proxy: everything passes through unchanged, except
tools/callrequests containing#,--or/*, which are answered with a tool error and never reach DBHub. The SQL text is not logged;redacts DBHub's stderr, and deletes the directory when DBHub exits (DBHub exits when the client closes stdin) or on
SIGINT/SIGTERM/SIGHUP.
Development
npm install
npm run build
npm test # unit tests
DB_MCP_IT=1 npm run test:integration # needs Docker: starts mysql:8.4 and mariadb:11.4 automaticallyWithout DB_MCP_IT=1 the integration tests are skipped. They need the openssl CLI: setup creates a throwaway CA and a server certificate for db.dbmcp.test, copies them into the MySQL container and switches the server to them (SET GLOBAL ssl_* and ALTER INSTANCE RELOAD TLS; switched back afterwards), so the tests run with the default DB_SSLMODE=verify-full. With Docker they also start a mariadb:11.4 container for the MariaDB PUBLIC grant tests. To use an existing MySQL 8 server instead of a new container, set DB_MCP_IT_HOST (and optionally DB_MCP_IT_PORT, DB_MCP_IT_ROOT_USER, DB_MCP_IT_ROOT_PASSWORD), and DB_MCP_IT_MYSQL_CONTAINER to the name of its Docker container so setup can install the test certificate; without it the tests connect with DB_SSLMODE=disable and the certificate-verification tests are skipped. The tests create a dbmcp_it database, five dbmcp_* accounts and a dbmcp_reader role; one test briefly creates a dbmcp_writer role and sets it as the server's mandatory_roles, and an afterEach hook resets mandatory_roles to empty and drops the role (also when the test fails or times out), so use a server where nothing else depends on that variable. With DB_MCP_IT_HOST the MariaDB tests are skipped unless you also set DB_MCP_IT_MARIADB_HOST (and optionally DB_MCP_IT_MARIADB_PORT, DB_MCP_IT_MARIADB_ROOT_USER, DB_MCP_IT_MARIADB_ROOT_PASSWORD) to a MariaDB 10.11+ server (the MariaDB tests connect with DB_SSLMODE=disable: they test the privilege check; certificate verification is tested against MySQL); they create a dbmcp_it database and a dbmcp_ro account there, briefly grant INSERT, DELETE ON dbmcp_it.* TO PUBLIC, and revoke it in an afterEach hook.
DBHub is pinned to an exact version in package.json and package-lock.json. To upgrade it, change the version, re-run the security review in SECURITY.md against the new release, run both test suites, and release a new db-mcp version.
Releasing
Pushing a v* tag starts the Release workflow. It needs one approval (the publish job, release environment); provenance verification, dist-tag promotion and holding-tag cleanup then run automatically. A stuck, waiting or failed release does not notify anyone: after tagging, check the Actions tab until the run is green.
Releases are serialized (concurrency with queue: max): if a run's publish approval is never given, that run holds the queue for up to 30 days and every later tag's run waits behind it. To recover, cancel the stuck run in the Actions tab (nothing was published, so nothing needs cleaning up); the next queued run then starts. When re-running an older run's cleanup job by hand, do so only if no newer release run has started since: with that run's publish outputs missing or invalid it removes the publish-staging dist-tag whatever version it points at.
中文说明(摘要)
用途:让 AI Agent 用自然语言只读查询 MySQL。底层是锁定版本的 DBHub,护栏写死:只读、每条
SELECT最多 500 行(尽力而为的护栏,不是硬保证;SHOW/DESCRIBE/EXPLAIN不限行)、查询 30 秒超时、连接 15 秒超时、最多 2 个连接。SQL 中出现#、--或/*(含可执行注释/*! */和优化器提示/*+ */)一律拒绝(COMMENTS_NOT_ALLOWED),字符串和带引号的名字里出现也拒绝;字面量#请写成CHAR(35 USING utf8mb4),--、/*用CONCAT拼接。写入的硬边界只有账号权限。启动时 db-mcp 会执行
SHOW GRANTS(不带FOR CURRENT_USER(),这样 MariaDB 10.11+ 授给PUBLIC的权限和 MySQL 8 的 mandatory roles 也会列出):只允许SELECT、SHOW VIEW、SHOW DATABASES、USAGE;其他任何权限、WITH GRANT OPTION、角色授权或服务器设置了mandatory_roles(会话可以用SET ROLE启用角色的权限,SHOW GRANTS框不住会话实际能用的权限)、无法解析的结果都视为不合格。检查看不到以 definer 权限运行的视图和例程(SQL SECURITY DEFINER)。按 owner 决定,默认DB_MCP_GRANT_CHECK=warn:非只读账号也可以连接,照常启动,只在 stderr 记一次警告并列出越权的权限;工具本身仍然只提供读能力。DB_MCP_GRANT_CHECK=refuse为可选的严格模式,此时不启动 DBHub,每次工具调用都返回CONFIG_ERROR和拒绝原因。注意:用可写账号时没有任何硬性的写入边界,防写只靠 DBHub 的只读分类器、只读事务和 db-mcp 的注释拦截,三者都是尽力而为、不是保证(分类器和只读事务并不独立,评审中曾用#注释绕过分类器写入,现已被注释拦截挡住)。只读账号仍是唯一的硬边界,强烈建议使用只读账号;500 行上限也是尽力而为的护栏。环境变量:
DB_TYPE(默认mysql,本版只支持 MySQL)、DB_HOST(证书上的主机名;IP 地址只能配合DB_SSLMODE=disable)、DB_PORT(默认 3306)、DB_NAME、DB_USER、DB_PASSWORD、DB_SSLMODE(默认verify-full,可选disable;不再支持不校验证书的require)、DB_SSL_CA(可选,额外信任的 CA 证书,PEM 文本或文件路径)、DB_MCP_GRANT_CHECK(默认warn,可选refuse)。启动时只解析一次
DB_HOST,之后只连接校验过的 IP(优先 IPv4,否则 IPv6),防止 DNS rebinding;DBHub 拿到的是主机名(用于校验证书),但它的进程里这个主机名只能解析到校验过的 IP,其他主机名一律解析失败。数据库 DNS 变更(如主备切换)后需重启 Agent 会话。默认校验服务器证书(
DB_SSLMODE=verify-full):权限检查连接和 DBHub 连接都要求证书链到受信任的 CA,且证书上的主机名与DB_HOST一致,否则拒绝连接。受信任的 CA 为 Node.js 内置的公共 CA,加上DB_SSL_CA。阿里云 RDS、AWS RDS 等使用自有 CA 的服务,请把控制台下载的 CA 证书(AWS 为global-bundle.pem)填入DB_SSL_CA。不提供"加密但不校验证书"的模式;disable为明文,仅用于不支持 TLS 的服务器。强烈建议使用只读账号(它是唯一的硬写入边界),建号 SQL 见上文「Create a read-only account」:只授
SELECT, SHOW VIEW,不要给FILE/SUPER等权限;敏感列可用视图隔离。连接从 Agent 所在机器发起,数据库需能从公网访问;请保持默认的
DB_SSLMODE=verify-full。内网、回环、云元数据地址会被拒绝。查询结果会进入模型上下文(发往模型服务商,可能留在对话记录里),注意个人信息。
密码以明文保存在 Agent 机器的 MCP 配置里;不要在聊天里发送数据库密码。
配置错误不再退出(0.1.1 起):环境变量无效、
DB_HOST是 IP 却用verify-full、内网/回环/元数据地址、域名解析失败,以及refuse模式下权限检查不通过(含连接或 TLS 失败)时,db-mcp 仍列出execute_sql和search_objects,但每次调用都返回CONFIG_ERROR,说明问题和修改方法(例如"使用证书上的主机名"、"不允许内网地址");同时写入 stderr。此时不连接数据库、不启动 DBHub,消息中不含密码,也不回显任何配置值;MCPinitialize的instructions只有一句固定的话。refuse时数据库服务器或驱动返回的文字视为不可信内容,压成一行、截到 1024 个字符,并放在<<<BEGIN UNTRUSTED SERVER TEXT/END UNTRUSTED SERVER TEXT>>>之间。修改连接配置后重启 Agent 会话。日期时间:
DATETIME、DATE按存储的数字原样返回,带一个无实际含义的Z(如21:23返回2026-12-01T21:23:00.000Z,与 Agent 机器的时区无关;末尾的Z不代表 UTC;两个工具的描述开头也写明了这一点,提醒模型不要换算时区)。TIMESTAMP按服务器默认会话时区显示(db-mcp 不修改time_zone),只有服务器时区为 UTC 时才是真正的 UTC 时间。查询超时与
SLEEP():超过 30 秒的查询通常返回超时错误(MySQL 3024);但单独的SELECT SLEEP(n)被中断时按 MySQL 的规定返回1而不报错。
License
MIT
Available Tools
2 toolsexecute_sqlARead-only
DATETIME and DATE values are returned with the digits stored in the database and a trailing "Z" that is only formatting: they have no time zone, so do not convert them to another time zone. TIMESTAMP values are in the server's default session time zone. Execute SQL queries on the mysql database [READ-ONLY MODE] (limited to 500 rows; capped results carry "truncated": true)
Inputs: sql (required).
search_objectsBRead-onlyIdempotent
DATETIME and DATE values are returned with the digits stored in the database and a trailing "Z" that is only formatting: they have no time zone, so do not convert them to another time zone. TIMESTAMP values are in the server's default session time zone. Search and list database objects on the mysql database
Inputs: object_type (required), limit, table, schema, +2 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 2 tools
The two tools target clearly different concerns: execute_sql runs arbitrary read-only queries, while search_objects is for metadata exploration (listing tables, columns, etc.). The boundary is mostly clear, though without an explicit schema/object list example, an agent might occasionally try to list tables via execute_sql instead.
Both names follow a verb_noun pattern (execute_sql, search_objects) in snake_case. The only minor deviation is that execute_sql embeds a resource abbreviation (sql) rather than a noun like 'query', but the convention is coherent.
Two tools is thin but defensible for a read-only database access server where execute_sql covers nearly all query needs and search_objects covers metadata. Still, it sits at the borderline of minimalism, lacking any convenience or schema-description helper.
Read-only query and object search are covered, but by design there are no write operations (insert/update/delete) and no dedicated schema/describe tool beyond generic search. For a read-only exploration server this is reasonable, but the surface is notably limited for general database work.
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Work with your database from AI tools: ask, export, approved changes, and scheduled jobs.
Query, explore, and manage your databases through natural conversation.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables AI assistants to safely query MySQL databases with read-only access, featuring SQL injection protection, connection pooling, and automatic query limits for secure database exploration.4MIT
- AlicenseAqualityDmaintenanceEnables AI assistants to inspect and query a MySQL database through safe, structured tools, including schema discovery and read-only queries.943 npmMIT
- AlicenseAqualityDmaintenanceEnables AI agents to explore MySQL database schemas and execute read-only queries through a safe, MCP interface.6ISC
- FlicenseNot gradedqualityBmaintenanceEnables natural language querying of MySQL databases by exposing tools to list tables, retrieve schemas, and run read-only SELECT queries with safety protections.1-