Skip to main content
Glama
db-mcp

db-mcp

by openmaxai
README.md
# @openmaxai/db-mcp

A read-only stdio [MCP](https://modelcontextprotocol.io) server that lets an AI agent explore and query a **MySQL** database in natural language. It wraps a pinned version of [DBHub](https://github.com/bytebase/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 `SHOW GRANTS` and logs a warning if it holds anything beyond `SELECT`, `SHOW VIEW`, `SHOW DATABASES` or `USAGE`; with `DB_MCP_GRANT_CHECK=refuse` it refuses to start instead (see [Privilege check](#privilege-check)) |
| Read-only mode (defence in depth) | `execute_sql` runs only statements DBHub classifies as read-only, inside a read-only transaction. These two DBHub layers are not independent: a batch that fools the classifier can end the read-only transaction itself. They are not a permission boundary |
| Row limit | 500 rows per `SELECT` / `WITH` statement (DBHub rewrites the `LIMIT`); capped results carry `"truncated": true`. `SHOW` / `DESCRIBE` / `EXPLAIN` output is not capped. It is a best-effort guardrail against oversized results, not a hard guarantee: on servers whose `sql_mode` includes `NO_BACKSLASH_ESCAPES` or `ANSI_QUOTES`, quoting tricks can hide a `LIMIT` from it (confirmed: a comment-free query returned 200,000 rows; it lets more rows through, never a write; see [SECURITY.md](SECURITY.md), Known gap 9) |
| No SQL comments | SQL containing `#`, `--` or `/*` anywhere (this includes `/*! ... */` executable comments and `/*+ ... */` optimizer hints) is rejected with `COMMENTS_NOT_ALLOWED` before it reaches DBHub, because DBHub and MySQL disagree about where comments end, which let comments hide statements and `LIMIT`s. This also applies inside string literals and quoted names (see [False positives](#comments-are-rejected-false-positives)) |
| Query timeout | 30 seconds (server-side `max_execution_time` plus a client-side cancel) |
| Connection timeout | 15 seconds |
| Connection pool | at most 2 connections |
| Tools | only `execute_sql` and `search_objects` |

- The guardrails are hard-coded in the package. No environment variable, argument or file changes them.
- All configuration comes from environment variables. `DB_PASSWORD` is 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](#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](#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=refuse` makes it refuse such accounts. See [SECURITY.md](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)

```bash
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](#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](#configuration-errors-degraded-mode)).

## Configuration

| Variable | Required | Default | Notes |
|---|---|---|---|
| `DB_TYPE` | no | `mysql` | Only `mysql` in this version. `postgres` is reserved for a later version and is rejected for now. |
| `DB_HOST` | yes | | Public host name: the name in the server certificate. No URL, no `user@`, no `:port`. An IPv4 address is accepted only with `DB_SSLMODE=disable` (a certificate can not be verified for an IP address, see [TLS](#tls)). IPv6 literals are not supported (a host name that resolves to IPv6 is fine). |
| `DB_PORT` | no | `3306` | Empty means the default. |
| `DB_NAME` | yes | | The database (schema) to query. |
| `DB_USER` | yes | | A read-only account. |
| `DB_PASSWORD` | yes | | The only secret. Any characters are allowed; it is not trimmed. |
| `DB_SSLMODE` | no | `verify-full` | `verify-full`: encrypted, and the server certificate must chain to a trusted CA and match `DB_HOST`. `disable`: plaintext, logs a warning. `require` (encrypted without verification) is refused. See [TLS](#tls). |
| `DB_SSL_CA` | no | | Extra trusted CA certificate(s) for `verify-full`, for providers whose server certificates are not issued by a public CA (AWS RDS, Alibaba Cloud RDS, self-signed CAs): the PEM text (one or more `-----BEGIN CERTIFICATE-----` blocks) or the path of a PEM file. Added to Node.js's bundled public CAs. Not allowed with `disable`. |
| `DB_MCP_LOG_LEVEL` | no | `info` | `debug`, `info`, `warn`, or `error` (stderr). |
| `DB_MCP_GRANT_CHECK` | no | `warn` | What to do when the account can write or its privileges cannot be verified: `warn` (default: start, log a warning once) or `refuse` (do not start DBHub; every tool call returns `CONFIG_ERROR` with the reason; opt-in for strict deployments). See [Privilege check](#privilege-check). |

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:

```json
{
  "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 bad `DB_PORT`, `DB_SSLMODE=require`, an IP-address `DB_HOST` under `verify-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](#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 default `warn` these 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](#configuration-errors-degraded-mode)); 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_CA` if set. Without `DB_SSL_CA`, a `NODE_EXTRA_CA_CERTS` from the agent's environment is honoured as well; with `DB_SSL_CA`, it replaces `NODE_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 bundle `https://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 no `DB_SSL_CA`.
- **Use the host name the certificate was issued for.** An IP address can not be verified (`DB_HOST` must be a name under `verify-full`), and a CNAME of your own fails unless the certificate also lists it. Check with `openssl s_client -starttls mysql -connect <host>:3306 -servername <host>` if unsure.
- **`require` is 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=disable` remains 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`, ...), `PROXY` and `WITH GRANT OPTION`.
- **Not verifiable**: role grants and a non-empty server-wide `mandatory_roles` (the session can switch a role's privileges on with `SET ROLE`, so what `SHOW GRANTS` lists 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 in `SHOW GRANTS` and in the variable; the variable is read as well so the check does not depend on that one output detail. On servers without `mandatory_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 privileges `SHOW GRANTS` lists for the session are checked. See [SECURITY.md](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](#configuration-errors-degraded-mode)). 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](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, and `DB_MCP_GRANT_CHECK=refuse` for 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`).

```sql
-- 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 ROUTINE` or any privilege on `mysql.*` or `*.*`. Read-only transactions do not stop functions such as `LOAD_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 `SELECT` on the views only, not on the tables:

  ```sql
  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](#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 |
|---|---|
| `search_objects` | Lists schemas, tables, views, columns, indexes and routines, with a LIKE pattern. Use it first to learn the schema. |
| `execute_sql` | Runs read-only SQL: `SELECT`, `WITH`, `SHOW`, `DESCRIBE` / `DESC`, `EXPLAIN`. Several statements separated by `;` are allowed if every one is read-only. Writes, DDL, `SET`, `CALL`, `LOAD_FILE()`, `INTO OUTFILE` and so on are rejected, usually by DBHub's check with `READONLY_VIOLATION`; a few forms that pass that check (such as `DESC ANALYZE DELETE ...`) are stopped by the read-only transaction instead and come back as an execution error. Neither check is a guarantee (a batch that fools the classifier can end the read-only transaction); only the read-only account is. SQL containing comments (`#`, `--`, `/*`) is rejected with `COMMENTS_NOT_ALLOWED`. |

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](#configuration-errors-degraded-mode)). 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:

1. checks the Node.js version, validates the environment and checks the host (on an error it serves [degraded mode](#configuration-errors-degraded-mode) and stops here);
2. connects once to the checked address and checks the account's privileges with `SHOW GRANTS` (one warning if it can write under the default `DB_MCP_GRANT_CHECK=warn`; degraded mode under `refuse`);
3. writes a DBHub config file (`dbhub.toml`, mode 0600) into a new private temporary directory (mode 0700), and `DB_SSL_CA` as `ca.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 zone `Z` (see [Dates and times](#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;
4. starts the pinned DBHub with `--transport stdio --config <file>`, inside that directory, with a minimal environment (no `DSN`, `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;
5. relays the MCP messages between the client and DBHub through a small JSON-RPC proxy: everything passes through unchanged, except `tools/call` requests containing `#`, `--` or `/*`, which are answered with a tool error and never reach DBHub. The SQL text is not logged;
6. redacts DBHub's stderr, and deletes the directory when DBHub exits (DBHub exits when the client closes stdin) or on `SIGINT` / `SIGTERM` / `SIGHUP`.

## Development

```bash
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 automatically
```

Without `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](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,消息中不含密码,也不回显任何配置值;MCP `initialize` 的 `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

TDQS

B3.4/5.0

Scored across 2 tools

Disambiguation4/5

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.

Naming Consistency4/5

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.

Tool Count3/5

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.

Completeness3/5

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

ActivityMaintained
ResponsivenessNo recent community issues