db-mcp
Provides a read-only interface to PostgreSQL databases, allowing schema exploration, table description, DDL retrieval, index and relationship inspection, and safe read-only SQL queries.
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 tables in the public schema"
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.
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).
Related MCP server: postgres-mcp-readonly
Tools
Tool | Description |
| Databases the read-only role can connect to. |
| Schemas visible to the role (system schemas excluded). |
| Tables/views in a schema: type, row estimate, comment. |
| Columns, PK, FKs, unique/check constraints, indexes. |
| Reconstructed |
| Foreign keys, referenced tables, cardinality hint. |
| Index names, columns, order, uniqueness, type, predicate. |
| A small sample of rows (capped at 50). |
| Validated read-only SQL; returns columns, rows, timing. |
| 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 buildCreate 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 |
| — | Full connection string (wins over |
| — | Discrete connection settings. |
|
|
|
|
| Database driver. |
|
| Hard cap for |
|
| Hard cap for |
|
| Per-statement timeout. |
|
| Reject longer queries. |
|
| Schema used when omitted. |
Running locally
export DATABASE_URL="postgres://readonly_user:***@localhost:5432/your_db"
npm startThe server speaks MCP over stdio. To poke at it interactively, use the MCP Inspector:
npx @modelcontextprotocol/inspector node dist/server.jsConnecting 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 testTests 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 testsAvailable Tools
10 toolsdescribe_tableA
Describe a table: columns (type, nullability, default, comment), primary key, foreign keys, unique constraints, check constraints, and indexes.
Inputs: table (required), schema.
get_indexesA
List indexes on a table: name, access method (btree/gin/gist/...), uniqueness, whether it backs the primary key, ordered columns with sort direction and NULLS ordering, and any partial-index predicate.
Inputs: table (required), schema.
get_relationshipsA
List foreign-key relationships with constraint names, referenced tables/columns, ON UPDATE/DELETE actions, and a cardinality hint (1:1 when the FK columns are uniquely constrained locally, otherwise many:1). Optionally filter by schema and/or table.
Inputs: table, schema.
get_table_ddlA
Return the reconstructed CREATE TABLE DDL for a table (PostgreSQL has no SHOW CREATE TABLE, so this is the closest supported reconstruction from the catalog, including constraints and indexes).
Inputs: table (required), schema.
list_databasesA
List databases the read-only user can connect to, with owner and comment when available.
Inputs: no named parameters.
list_schemasA
List schemas (namespaces) the read-only user can access. Excludes system schemas (pg_*, information_schema).
Inputs: no named parameters.
list_tablesA
List tables and views in a schema. Returns name, type (table/view/materialized view/foreign table), a planner row estimate when available, and any comment. Defaults to the configured default schema.
Inputs: schema.
run_readonly_queryA
Execute a single read-only SQL query (SELECT / EXPLAIN-without-ANALYZE / SHOW). The query is validated with a real PostgreSQL parser and rejected if it contains any write, DDL, data-modifying CTE, multiple statements, or other side effect. Results are capped at the server row maximum. Returns columns, rows, row count, execution time, and a truncation flag.
Inputs: sql (required), limit.
sample_rowsA
Return a small sample of rows from a table. The limit is capped at the server's hard maximum (default 50) regardless of the requested value.
Inputs: table (required), limit, schema.
search_schemaA
Search across the schema for a term (case-insensitive substring). Matches table names, column names, table/column comments, constraint names, and index names. Optionally restrict to a single schema.
Inputs: term (required), schema.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 10 tools
Each tool has a clearly distinct purpose: describing table structure, fetching indexes, listing foreign keys, retrieving DDL, enumerating databases/schemas/tables, running queries, sampling rows, and searching schema metadata. No two tools overlap in functionality.
All tools follow a consistent verb_noun pattern using snake_case (e.g., describe_table, list_schemas, run_readonly_query). The verbs accurately describe the action (describe, get, list, run, sample, search), and there are no mixed naming conventions.
With 10 tools, the server is well-scoped for database introspection and read-only queries. Each tool addresses a distinct need without redundancy or excessive granularity, fitting the typical range of 3-15 tools for a focused domain.
The tool set covers core CRUD-like operations for database metadata (create via DDL retrieval, read via descriptions and queries, and listing). Minor gaps exist, such as missing explicit tools for table size estimation or listing extensions, but most common exploration workflows are supported.
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Hosted MCP server for PostgreSQL diagnostics: slow queries, missing indexes, connection pressure.
Read-only MCP server for ClassQuill, a tutoring-business-management platform.
Read-only MCP server for The Quiet Protocol's engines, benchmarks, proof, and business data.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceRead-only PostgreSQL MCP server that enables running SELECT queries, listing tables and schemas, and describing columns, with built-in protection against writes and malicious SQL attacks.432 npmMIT
- AlicenseAqualityDmaintenanceA secure, read-only PostgreSQL MCP server that provides safe database introspection and querying capabilities.1420 npmMIT
- AlicenseNot gradedqualityDmaintenanceRead-only MCP server for PostgreSQL, enabling schema discovery, table metadata, and safe SELECT queries via READ ONLY transactions.12 npmMIT
- AlicenseNot gradedqualityDmaintenanceProvides a read-only PostgreSQL MCP server with schema introspection. Enforces least-privilege database roles to prevent any writes, even from malicious SQL.MIT