db-mcp
Read-only PostgreSQL database MCP server for safely exploring schema, tables, relationships, and sample data without modification.
README
db-mcp — Read-Only Database MCP Server
A Model Context Protocol server that lets AI assistants safely explore a PostgreSQL database — schema, tables, columns, relationships, indexes, constraints, DDL, and sample data — without ever modifying it.
Safety model
Read-only is enforced at three independent layers, so a failure in any one layer is still caught by the others:
- Least-privilege database role. You connect with a role that only has
CONNECT/USAGE/SELECT. The database itself rejects anything else. - Read-only transaction. Every query runs inside
BEGIN TRANSACTION READ ONLYon a session forced todefault_transaction_read_only = onwith astatement_timeout. The query is always rolled back. - Application-level validation. Arbitrary SQL (the
run_readonly_querytool) is parsed withlibpg-query— the real PostgreSQL parser compiled to wasm — and rejected unless it is a single read-only statement. This catches multi-statement input, DDL/DML,EXPLAIN ANALYZE,SELECT INTO, and data-modifying CTEs (WITH x AS (INSERT ... RETURNING ...) SELECT ...).
Additional guards: a maximum query length, a hard row cap on every result, a sample-row cap (default 50), and secrets are never logged (config is redacted before any diagnostic output).
Tools
| Tool | Description |
|---|---|
list_databases |
Databases the read-only role can connect to. |
list_schemas |
Schemas visible to the role (system schemas excluded). |
list_tables |
Tables/views in a schema: type, row estimate, comment. |
describe_table |
Columns, PK, FKs, unique/check constraints, indexes. |
get_table_ddl |
Reconstructed CREATE TABLE DDL (+ indexes). |
get_relationships |
Foreign keys, referenced tables, cardinality hint. |
get_indexes |
Index names, columns, order, uniqueness, type, predicate. |
sample_rows |
A small sample of rows (capped at 50). |
run_readonly_query |
Validated read-only SQL; returns columns, rows, timing. |
search_schema |
Search names + comments across tables/columns/constraints/indexes. |
Requirements
- Node.js >= 18.17
- A reachable PostgreSQL database and a read-only role (see below).
Setup
npm install
npm run build
Create a least-privilege read-only role
Run as a superuser or the database owner:
CREATE ROLE readonly_user LOGIN PASSWORD 'CHANGE_ME';
GRANT CONNECT ON DATABASE your_db TO readonly_user;
GRANT USAGE ON SCHEMA public TO readonly_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly_user;
-- Optional extra safety:
ALTER ROLE readonly_user SET default_transaction_read_only = on;
Configure
Copy .env.example and fill in your connection. Configuration is read from the
environment (no .env is loaded automatically — export the vars, or have your
MCP client pass them in its env block).
| Variable | Default | Purpose |
|---|---|---|
DATABASE_URL |
— | Full connection string (wins over PG*). |
PGHOST / PGPORT / PGDATABASE / PGUSER / PGPASSWORD |
— | Discrete connection settings. |
PGSSLMODE |
disable |
require/verify-* enable TLS. |
DB_MCP_DRIVER |
postgres |
Database driver. |
DB_MCP_MAX_ROWS |
1000 |
Hard cap for run_readonly_query. |
DB_MCP_SAMPLE_MAX_ROWS |
50 |
Hard cap for sample_rows. |
DB_MCP_STATEMENT_TIMEOUT_MS |
5000 |
Per-statement timeout. |
DB_MCP_MAX_QUERY_LENGTH |
10000 |
Reject longer queries. |
DB_MCP_DEFAULT_SCHEMA |
public |
Schema used when omitted. |
Running locally
export DATABASE_URL="postgres://readonly_user:***@localhost:5432/your_db"
npm start
The server speaks MCP over stdio. To poke at it interactively, use the MCP Inspector:
npx @modelcontextprotocol/inspector node dist/server.js
Connecting from Claude Code
Add an entry to your MCP config (e.g. .mcp.json in your project, or the global
Claude Code config):
{
"mcpServers": {
"db-mcp": {
"command": "node",
"args": ["/absolute/path/to/db-mcp/dist/server.js"],
"env": {
"DATABASE_URL": "postgres://readonly_user:***@localhost:5432/your_db"
}
}
}
}
Then ask Claude to, e.g., "list the tables in the public schema" or "show me the DDL for the orders table".
Tests
npm test
Tests are pure unit tests (no live database required): exhaustive SQL-validation cases (allowed reads vs. rejected mutations and bypass attempts), identifier quoting, DDL reconstruction, and config parsing/redaction.
Extending to other databases
Tools depend only on the DatabaseDriver interface (src/db/driver.ts). To add
MySQL, SQLite, or Snowflake:
- Implement
DatabaseDriverfor the new engine undersrc/db/<engine>/. - Register it in
createDriver(src/db/factory.ts). - Provide an engine-appropriate read-only enforcement (read-only role + read-only session/transaction) and SQL validation.
Project layout
src/
server.ts MCP server setup + stdio transport
config.ts env parsing + secret redaction
errors.ts typed error classes
types.ts shared result types
validation/
validateReadOnly.ts libpg-query-based read-only enforcement
db/
driver.ts DatabaseDriver interface
factory.ts driver selection
postgres/
pool.ts read-only pool, transactions, row-capped cursor
identifiers.ts safe identifier quoting
introspection.ts catalog/information_schema queries
ddl.ts CREATE TABLE reconstruction (pure)
PostgresDriver.ts DatabaseDriver implementation
tools/ one module per MCP tool + registry
tests/ pure unit tests
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。