db-mcp
Provides tools for interacting with MySQL databases, including schema and table discovery, column search, data sampling, read-only SQL queries, query plan explanation, and optional write operations based on configured access level.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
db-mcp
Database MCP server for L92 Labs: Postgres, MySQL and BigQuery. One tool surface, two runtimes:
Runtime | Entry | Auth | Good for |
Node: published image, stdio, Docker (HTTP) | stdio or Streamable HTTP | Bearer token for HTTP only. Stdio starts without a token. | Local MCP clients, Docker on any host |
Cloudflare Worker: Workers + Hyperdrive |
| bearer token or OAuth 2.1 | Hosted remote MCP (claude.ai, ChatGPT, Cursor…), Postgres/MySQL through Hyperdrive |
Start here: published Docker image, releases and manual publishing, contributing, security, changelog.
Quick start: published image
Requires Docker Compose v2. Images become available after the first successful publish; anonymous pulls require the GHCR package to be public.
git clone https://github.com/L92-Labs/db-mcp.git
cd db-mcp
cp .env.example .env
# Edit .env: real DB connection + strong MCP_BEARER_TOKEN; keep DB_ACCESS=read_only.
# Generate a bearer token: openssl rand -hex 32
docker compose -f docker-compose.image.yml pull
docker compose -f docker-compose.image.yml up -d
(
for attempt in {1..30}; do
if curl --fail --silent --max-time 1 http://127.0.0.1:8787/health; then
exit 0
fi
sleep 1
done
echo "db-mcp health check timed out" >&2
exit 1
)Connect a Streamable HTTP MCP client to http://127.0.0.1:8787/mcp with
Authorization: Bearer <your-token>. /health checks server/config
availability, not database access; call connection_info to verify the
connection.
The database host must be reachable from inside the container;localhost in a DB URL refers to the container itself.
Set DB_MCP_IMAGE=ghcr.io/l92-labs/db-mcp:0.1.0 in .env to select a release,
or use ghcr.io/l92-labs/db-mcp@sha256:<digest> for a pinned image. Available
tags: stable latest, exact SemVer, and sha-<full-commit>. Main commits and
prereleases never advance latest.
For a Cloudflare Tunnel, set TUNNEL_TOKEN, configure the tunnel's public HTTPS
hostname to service http://db-mcp:8787, then run:
docker compose -f docker-compose.image.yml --profile tunnel up -dRemote clients use https://<your-hostname>/mcp with the same bearer header.
Node/Docker uses bearer authentication; OAuth is implemented by the Worker.
Both Compose configurations bind the app to loopback and run it read-only as a
non-root user. The source Compose file also contains optional demo databases.
To update, change DB_MCP_IMAGE if pinned, then repeat pull and up -d.
To roll back, set the previous version/digest and repeat those commands.
Inspect status/logs with docker compose -f docker-compose.image.yml ps and
docker compose -f docker-compose.image.yml logs --tail=100 db-mcp.
Related MCP server: mcp-business-data-server
Node / stdio (Claude Desktop, Cursor, Claude Code)
Needs Node 22 and the pnpm version pinned in package.json (CONTRIBUTING.md).
corepack enable
pnpm install --frozen-lockfile
pnpm run build
cp .env.example .envBefore launching the client, edit .env in the repository root. Configure a
reachable Postgres or MySQL URL, BigQuery, or
DB_CONNECTIONS_JSON. Remove or comment out unused sample URLs. Use the
absolute checkout paths in the client configuration below.
{
"mcpServers": {
"db": {
"command": "node",
"args": ["/absolute/path/to/db-mcp/apps/node/dist/index.js"],
"env": { "DB_ENV_FILE": "/absolute/path/to/db-mcp/.env", "MCP_TRANSPORT": "stdio" }
}
}
}Docker (HTTP)
From the repository root, use Docker Compose v2, Node 22 and the pnpm version
pinned in package.json. Edit .env as indicated before starting Compose.
cp .env.example .env
# Edit .env and set MCP_BEARER_TOKEN plus DATABASE_URL, MYSQL_URL or BigQuery settings.
# Remove or comment out unused sample URLs. Unnamed smoke calls use the default connection.
docker compose up --build -dCompose loads the token into the container. The smoke command loads the token
from .env for the host Node process.
For demo databases with a seeded shop schema, set these values in .env
before startup. Compose supplies them to the container when it starts.
DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres
MYSQL_URL=mysql://root:root@mysql:3306/shopFor the demo, replace the startup command with the block below. It waits for TCP connections to both databases and checks for the final fixture inserted by each seed script. Continue to the health check only when this block succeeds.
(
set -e -o pipefail
docker compose --profile demo up --build -d
for attempt in {1..30}; do
if docker compose exec -T postgres psql -h 127.0.0.1 -U postgres -d postgres \
-Atc 'SELECT id FROM secret.vault WHERE id = 1' | grep -qx 1 &&
docker compose exec -T mysql mysql -h 127.0.0.1 -uroot -proot -N \
-e 'SELECT id FROM secret.vault WHERE id = 1' | grep -qx 1; then
exit 0
fi
sleep 1
done
echo 'Demo databases did not become ready with seed data.' >&2
exit 1
)After startup and any demo readiness checks, run the HTTP health check and smoke test. Check the smoke output for database errors.
curl --fail --retry 10 --retry-connrefused http://127.0.0.1:8787/health &&
corepack pnpm install --frozen-lockfile &&
env -u MCP_BEARER_TOKEN node --env-file=.env scripts/smoke.mjs http://127.0.0.1:8787/mcpLocal MCP clients connect to http://127.0.0.1:8787/mcp with the header
Authorization: Bearer <MCP_BEARER_TOKEN>. Remote access requires an HTTPS reverse
proxy (Caddy, Cloudflare Tunnel). Demo database ports also bind only to loopback.
Cloudflare Workers + Hyperdrive
For AUTH_MODE=bearer, remove the entire [[kv_namespaces]] entry for
OAUTH_KV from apps/worker/wrangler.toml before running Wrangler. For
AUTH_MODE=oauth, run npx wrangler kv namespace create OAUTH_KV from
apps/worker and replace the placeholder ID in that entry with the namespace ID.
Run pnpm install at the repository root, then cd apps/worker. Choose a
database setup before deploying:
Postgres. Run
npx wrangler hyperdrive create db-mcp-main --connection-string="postgres://user:pw@host:5432/db"with your connection string. Set the returned ID on theHYPERDRIVEentry inwrangler.toml.MySQL only. Run
npx wrangler hyperdrive create db-mcp-mysql --connection-string="mysql://user:pw@host:3306/db"with your connection string. Uncomment the MySQL[[hyperdrive]]entry inwrangler.toml, set its ID to the returned ID, remove the entire PostgresHYPERDRIVEentry, and addMYSQL_HYPERDRIVE = "HYPERDRIVE_MYSQL"under[vars]. LeaveMYSQL_URLunset to use the binding.
For bearer mode, run:
npx wrangler secret put MCP_BEARER_TOKEN
pnpm run deployFor local development, run pnpm run dev separately from apps/worker. It uses
localConnectionString or CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING>.
If DB_CONNECTIONS_JSON and DATABASE_URL are both unset, the HYPERDRIVE binding becomes the connection postgres. For more databases, add more [[hyperdrive]] bindings and reference them by name: {"engine":"mysql","hyperdrive":"HYPERDRIVE_MYSQL"}, or set MYSQL_HYPERDRIVE=HYPERDRIVE_MYSQL. BigQuery works on Workers too: set BIGQUERY_* (or JSON) as secrets.
The Worker opens one database client per operation; Hyperdrive does the pooling. Hyperdrive caches read results by default (about 60 s). If an agent writes and then reads right away, create the config with --caching-disabled (or tune --max-age).
OAuth (claude.ai and other remote MCP clients)
Before deploying OAuth, restore the OAUTH_KV entry if you removed it and
configure its namespace ID as above. In apps/worker/wrangler.toml, set
AUTH_MODE = "oauth" under [vars]. Put the chosen sign-in settings below
in a private dotenv file. From apps/worker, deploy with
pnpm run deploy --secrets-file /absolute/path/to/oauth-secrets.env to upload
the settings as Worker secrets with the new mode. Wrangler uses .dev.vars
for local development.
The Worker becomes an OAuth 2.1 authorization server (via @cloudflare/workers-oauth-provider):
discovery (RFC 9728 / 8414), dynamic client registration and Client ID Metadata Documents
PKCE, a consent page and refresh tokens
If configured, the static MCP_BEARER_TOKEN keeps working for CLI clients.
Sign-in | Secrets |
GitHub (recommended) |
|
Password |
|
Scopes: db:read (always granted) and db:write, which the user can tick on the consent page. A token without db:write sees every connection as read_only, so sql_execute disappears. In claude.ai: Settings → Connectors → Add custom connector → https://<worker>/mcp.
Configure
Copy .env.example to .env (Node/Docker), or apps/worker/.dev.vars.example to apps/worker/.dev.vars.
# simplest: one database, read-only
DATABASE_URL=postgres://readonly:pw@db:5432/app # or MYSQL_URL=mysql://…
DB_ACCESS=read_only
MCP_BEARER_TOKEN=long-random-string
# several named connections
DB_CONNECTIONS_JSON='{
"app": {"engine":"postgres","url":"postgres://…","access":"read_write","description":"main app",
"schemas":["public"],"hidden_columns":["users.password_hash","*token*"]},
"legacy": {"engine":"mysql","url":"mysql://…","ssl":"require"},
"warehouse": {"engine":"bigquery","project_id":"my-proj","location":"EU",
"credentials_json":"<base64 or raw key JSON>","default_dataset":"analytics",
"max_bytes_billed":"10000000000","schemas":["analytics"]}
}'
DB_DEFAULT_CONNECTION=appA connection with both url and hyperdrive works everywhere: Workers use the Hyperdrive binding, Node/Docker use the url.
Environment settings. Where: all = every runtime, Node = Node and the Docker image, Compose = docker-compose.image.yml, Workers = the Worker only.
Var | Default | Where | What it controls |
| none | all | Required for Node HTTP (including Docker) and Worker bearer mode. Optional in Worker OAuth mode |
|
| all | Default access level ( |
|
| all | Response budget |
|
| all | Per-statement timeout |
|
| all |
|
| none | all | Hidden column globs for every connection |
| none | all | Several named connections; replaces the single-connection vars below |
| first enumerated connection | all | Used when a tool call names none. Integer-like JSON keys (array indices) are enumerated in ascending numeric order before other keys |
| none | all | One connection each for Postgres, MySQL and BigQuery, named |
| none | all | TLS for that connection: |
|
| all | Access level for that one connection |
| none | all | Schema or dataset allowlist for that one connection |
| none | all | Hidden columns for that one connection |
| none | all | Service-account key (raw JSON or base64), or an access token for local tests |
| none | all | See BigQuery setup |
| none | Workers | Binding name for shorthand |
| none | Workers | Binding name for shorthand |
|
| Node |
|
|
| Node | HTTP listen port |
|
| Node | Path of the env file to load |
|
| Node | Pool size per connection |
|
| Compose | Image to pull: a tag, or |
| none | Compose | Cloudflare Tunnel token for |
|
| Workers |
|
|
| Workers | Sign-in method for OAuth: |
| none | Workers | GitHub OAuth app used for sign-in |
| none | Workers | Comma-separated GitHub logins allowed to sign in |
| none | Workers | Sign-in password for |
| none | Workers | Postgres binding; becomes connection |
| none | Workers | Optional MySQL binding, used through |
| none | Workers | KV namespace; required when |
BigQuery setup
Create a service account. For read-only, grant
roles/bigquery.dataViewer+roles/bigquery.jobUser; for writes, addroles/bigquery.dataEditor.Create a JSON key, then set it as
credentials_json/BIGQUERY_CREDENTIALS_JSON(raw JSON orbase64 -w0 key.json).Set
location(US,EU,europe-west1…) so jobs run in the right region andcolumns_searchcan use region-wideINFORMATION_SCHEMA.Set
max_bytes_billedto cap cost per query. Usesql_explainto see the bytes before running.
For quick local tests, access_token (BIGQUERY_ACCESS_TOKEN, e.g. from gcloud auth print-access-token) works in place of a key.
Engines
Both runtimes share the same code. Postgres uses pg and MySQL uses mysql2; both run on Workers with nodejs_compat. BigQuery talks to the REST API with a service-account JWT signed by WebCrypto (no Google SDK).
Postgres | MySQL 8 (MariaDB: best effort, untested) | BigQuery | |
Node / Docker |
|
|
|
Workers | Hyperdrive or | Hyperdrive or |
|
Read-only enforced by the engine |
|
| dry-run |
| transaction + rollback | transaction + rollback (not DDL) | dry-run job (bytes, no row count) |
Tools
Tool | What it does |
| Configured connections: engine, access level, policy, default |
| Ping + server version, database/project, current user, read-only state |
| Schemas (Postgres), databases (MySQL), datasets (BigQuery) |
| Tables and views (kind, estimated rows, size), filter by name |
| Columns, types, nullability, defaults, comments, PK/FK, indexes, referencing tables, partitioning/clustering, view SQL |
| First N rows, visible columns only. BigQuery uses |
| Find columns by name across tables |
| One read-only statement. Always read-only, whatever the connection allows |
| Plan without executing (Postgres |
| Writes up to the connection's access level. With |
Bind parameters: Postgres $1, $2… from params: [...]; MySQL ? from params: [...]; BigQuery ? from params: [...] or @name from params: {...} (a value can be {"type": "DATE", "value": "2024-01-01"}).
Access levels
Set DB_ACCESS for every connection, and override it per connection with "access" in DB_CONNECTIONS_JSON (or DATABASE_ACCESS / MYSQL_ACCESS / BIGQUERY_ACCESS).
Access | Allows |
|
|
| + |
| + DDL, |
Each statement is checked twice:
SQL classifier (all engines). Comments, strings and dollar quotes are stripped; MySQL
/*! … */executable comments are read as code. A call holds one statement (Postgresadminexcepted). Data-modifying CTEs,SELECT … INTO,EXPLAIN ANALYZE <write>and side-effect functions are refused when access is too low (pg_terminate_backend,set_config,dblink,LOAD_FILE,GET_LOCK…).Engine enforcement
Postgres: reads run in
BEGIN TRANSACTION READ ONLYwithSET LOCAL statement_timeout, through the extended protocol, which accepts one statement only. Rows stream through a cursor.MySQL: reads run in
START TRANSACTION READ ONLY.sql_select_limitsets the default server row limit. An explicitLIMITcan override it, and the adapter caps streamed rows separately. MySQLmax_execution_timeapplies toSELECTonly. MariaDB usesmax_statement_time.multipleStatementsis always off. MySQL DDL commits implicitly, so the classifier is what keeps DDL out.BigQuery: every statement is dry-run first (free). Its
statementTypemust fit the access level.max_bytes_billedcaps cost.
For defense in depth, also use a read-only database user for read-only connections. For BigQuery, give the service account only roles/bigquery.dataViewer + roles/bigquery.jobUser.
Guardrails: schema allowlist and hidden columns
Per connection: "schemas": ["public", "shop"] and "hidden_columns": ["password", "users.ssn", "*token*"]. Shorthand env vars: DATABASE_SCHEMAS, MYSQL_SCHEMAS, BIGQUERY_DATASETS, *_HIDDEN_COLUMNS. DB_HIDDEN_COLUMNS applies to every connection.
Metadata: other schemas and hidden columns disappear from
schemas_list,tables_list,table_describeandcolumns_search.table_sampleselects only visible columns.SQL: any identifier matching a hidden pattern is refused. Then the engine checks what the statement really touches:
Postgres:
search_pathis pinned to the allowlist.EXPLAIN (VERBOSE)is inspected for every scanned relation and the columns read from it, which catchesSELECT *, aliases androw_to_json(t).MySQL: schema-qualified names are checked against the server's schema list, and each result column's origin (
db,orgTable,orgName) is checked before commit.BigQuery: the dry run's referenced tables and output schema are checked.
Admin statements are disabled on a connection that has a policy.
Not a security boundary for SQL hidden inside functions or procedures: use database grants (column privileges, views) for hard guarantees.
Response budget
DB_MAX_ROWS (default 200) caps rows. DB_MAX_RESULT_BYTES (default 100 000) limits the serialized row array, and rows past it are dropped (truncated_by: "bytes"). Metadata and the result envelope add bytes. DB_MAX_CELL_CHARS (default 2 000) cuts long strings and JSON cells. All three keep agents from flooding their context.
Audit log
DB_AUDIT_LOG=meta (default) writes one JSON line per tool call that reaches the registered handler. A call rejected earlier by the SDK's input validation returns an error to the client and writes no audit line. Each line includes principal (stdio, bearer, github:<login>, password), tool, success status and duration. Connection and result fields such as statement class, command, rows, affected rows and the dry-run flag appear when available. Failed calls that are logged include an error. Calls with SQL text include sql_sha256. Use sql to include the SQL text, off to disable. Node writes to stderr (stdout carries stdio MCP). Workers write to Workers Logs ([observability] enabled = true).
Layout
packages/core config, access levels, SQL classifier, policy, audit, tool schemas, dispatch, MCP server,
postgres/ (pg + pg-cursor), mysql/ (mysql2), bigquery/ (REST + WebCrypto JWT)
apps/node stdio + Streamable HTTP, pools per connection
apps/worker /mcp on Workers, Hyperdrive bindings, OAuth 2.1 (GitHub / password sign-in)
Dockerfile Node container image
examples/ seed.sql (Postgres) and seed.mysql.sql demo schemas
scripts/ smoke.mjs (bearer) and oauth-smoke.mjs (full OAuth flow) end-to-end checksTests
pnpm test # unit: classifier, config, policy, budget, audit, dispatch, MCP, BigQuery (mocked)
# Run from the repository root in Bash.
(
set -e
pg=
mysql=
trap 'docker stop ${pg:+"$pg"} ${mysql:+"$mysql"} >/dev/null 2>&1 || true' EXIT
pg=$(docker run -d --rm -p 127.0.0.1:5432:5432 -e POSTGRES_PASSWORD=postgres postgres:17-alpine)
mysql=$(docker run -d --rm -p 127.0.0.1:3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=shop mysql:8.4)
wait_for_db() {
for attempt in {1..30}; do
if "$@" >/dev/null 2>&1; then return 0; fi
sleep 1
done
echo "Database readiness timed out" >&2
return 1
}
wait_for_db docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres
wait_for_db docker exec "$mysql" mysql -h 127.0.0.1 -uroot -proot -e 'SELECT 1'
docker exec -i "$pg" psql -U postgres -d postgres -v ON_ERROR_STOP=1 < examples/seed.sql
docker exec -i "$mysql" mysql -uroot -proot < examples/seed.mysql.sql
TEST_DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/postgres \
TEST_MYSQL_URL=mysql://root:root@127.0.0.1:3306/shop pnpm test
)For the OAuth smoke test, use Node 22 and install dependencies with pnpm install
at the repository root.
Keep or restore the
[[kv_namespaces]]entry withbinding = "OAUTH_KV"inapps/worker/wrangler.toml. Wrangler simulates the namespace locally. Start an isolated database and configure a reachable default connection using the local Hyperdrive settings above. For the sample Postgres binding, use a running local Postgres database at itslocalConnectionString.Copy
apps/worker/.dev.vars.exampletoapps/worker/.dev.varsif needed. In that file, setAUTH_MODE=oauth,OAUTH_LOGIN=passwordandOAUTH_PASSWORDto a value of at least 16 characters. UseDB_ACCESS=read_onlyfor the read test below.Run
pnpm run devfromapps/worker. Once Wrangler listens on port 8787, open a second Bash shell at the repository root and enter the same password at the prompt.
IFS= read -r -s -p 'Worker OAuth password: ' OAUTH_PASSWORD
node scripts/oauth-smoke.mjs http://localhost:8787 "$OAUTH_PASSWORD" readTo check write scope, configure at least one read_write or admin connection,
restart the Worker, and pass write as the final argument.
For either scope, require a PASS sql_query line with a JSON result preview
from SELECT 1 AS one. A bare PASS sql_query can indicate a JSON-RPC error
with no result and does not count as success. Check for FAIL lines as well.
The live tests run only whenTEST_DATABASE_URL / TEST_MYSQL_URL are set, and they create, update and delete fixture data. Use isolated instances and never point them at a production database.
License
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Managed Postgres MCP: projects, SQL, docs search, and storage buckets via OAuth.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Related MCP Servers
- AlicenseAqualityDmaintenanceA self-hostable PostgreSQL MCP server for exploring database schemas and running guarded read/write queries with selectable access modes (readonly, readwrite, admin), plus a dry-run confirm workflow for safety.141MIT
- AlicenseNot gradedqualityCmaintenanceEnables MCP clients such as Claude, ChatGPT and Cursor to answer business questions about sales, customers, orders and spreadsheets in natural language by reading live Postgres/SQLite databases and Google Sheets without exporting files or gaining write access. Guardrails include AST-based read-only SQL validation, read-only database roles, row/byte caps with pagination, PII masking, bearer-token auth for remote HTTP use, and a full JSONL audit log of every tool call.MIT
- AlicenseBqualityCmaintenanceEnables MCP clients to inspect and operate SQLite, PostgreSQL, MySQL/MariaDB, Oracle, SQL Server and MongoDB through 16 tools covering schema discovery, parameterized SQL reads and transactions, MongoDB document operations, and concurrent hybrid SQL/MongoDB queries. Runs locally over stdio or loopback HTTP with pooled connections, bounded concurrency, row and response limits, and read-only defaults.16MIT
- AlicenseNot gradedqualityCmaintenanceEnables MCP-compatible AI agents to run policy-checked SQL against MySQL through a self-hosted Streamable HTTP endpoint, where each request is authenticated by bearer token and constrained by role-based statement allowlists, timeouts, and row limits. It also provides identity introspection, admin-gated configuration reload, and JSONL audit logging of allowed, denied, and errored queries.1Apache 2.0