An MCP (Model Context Protocol) server that connects to any PostgreSQL database and exposes it as a set of tools an AI assistant can call. Point it at a database and ask Claude to explore schemas, describe tables, run queries, profile data quality, get index suggestions, and generate SQL from natural language.
Once connected, Claude can:
- Explore the structure of any schema — tables, columns, types, keys
- Describe individual tables in depth — indexes, foreign keys, DDL
- Traverse the foreign key graph to understand how tables relate
- Execute read-only SQL queries safely
- Explain query plans in plain English
- Profile data quality — null rates, distinct counts, min/max/avg, top values
- Suggest missing indexes and flag unused ones
- Generate SQL from a natural language question using Claude
Ask Claude to explore your database and it will map out every table, column, and relationship.
Claude can traverse the foreign key graph and render an ERD-style diagram showing how tables connect.
Describe what you want in plain English — Claude generates the query, runs it, and shows the results.
Profile any table to surface data quality issues — anomalous sequences, sparse columns, zero-value records.
Claude can chain tools together — traverse relationships, generate a join query, execute it, and interpret the results.
- Node.js 18+
- A running PostgreSQL instance
- Claude Desktop (for MCP integration)
- An Anthropic API key (only required for the
generate_sqltool)
git clone <repo-url>
cd pg-schema-explorer-mcp
npm installCreate a .env file in the project root. You can use either a connection URI or individual fields.
Option A — connection URI (recommended)
PG_CONNECTION_STRING=postgresql://user:password@localhost:5432/mydb
Option B — individual fields
PG_HOST=localhost
PG_PORT=5432
PG_DATABASE=mydb
PG_USER=postgres
PG_PASSWORD=secret
All environment variables
| Variable | Default | Description |
|---|---|---|
PG_CONNECTION_STRING |
— | Full connection URI. Takes priority over individual fields. |
PG_HOST |
localhost |
Database host |
PG_PORT |
5432 |
Database port |
PG_DATABASE |
postgres |
Database name |
PG_USER |
postgres |
Database user |
PG_PASSWORD |
`` | Database password |
PG_SCHEMA |
public |
Default schema |
PG_READ_ONLY |
true |
Block write queries. Set to false to allow writes. |
PG_MAX_ROWS |
1000 |
Maximum rows returned per query |
PG_QUERY_TIMEOUT |
30000 |
Query timeout in milliseconds |
PG_MIN_CONNECTIONS |
1 |
Minimum pool connections |
PG_MAX_CONNECTIONS |
10 |
Maximum pool connections |
ANTHROPIC_API_KEY |
— | Required for generate_sql only |
Add the following to ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"pg-schema-explorer": {
"command": "node",
"args": ["/absolute/path/to/pg-schema-explorer-mcp/src/server.js"],
"env": {
"PG_CONNECTION_STRING": "postgresql://user:password@localhost:5432/mydb",
"PG_READ_ONLY": "true",
"ANTHROPIC_API_KEY": "sk-ant-..."
}
}
}
}Lists all tables in a schema with their columns, primary keys, and foreign keys.
| Parameter | Type | Default | Description |
|---|---|---|---|
schema_name |
string | public |
Schema to explore |
table_filter |
string | — | Optional substring to filter table names |
Deep dive into a single table — columns, types, indexes, foreign keys in both directions, row count estimate, and DDL.
| Parameter | Type | Default | Description |
|---|---|---|---|
table_name |
string | required | Table to describe |
schema_name |
string | public |
Schema name |
Traverses the foreign key graph starting from a given table. Returns nodes (tables) and edges (FK connections) up to a specified depth.
| Parameter | Type | Default | Description |
|---|---|---|---|
table_name |
string | required | Starting table |
schema_name |
string | public |
Schema name |
depth |
number | 1 |
Hops to traverse |
Generates a SQL SELECT statement from a natural language question using Claude. Requires ANTHROPIC_API_KEY.
| Parameter | Type | Default | Description |
|---|---|---|---|
question |
string | required | Natural language question |
schema_name |
string | public |
Schema to use for context |
Executes a SQL query and returns the results. Enforces read-only mode by default.
| Parameter | Type | Default | Description |
|---|---|---|---|
sql |
string | required | SQL to execute |
row_limit |
number | 1000 |
Maximum rows to return |
Runs EXPLAIN (ANALYZE, BUFFERS) on a query and returns the plan, parsed metrics, and a plain-English interpretation.
| Parameter | Type | Default | Description |
|---|---|---|---|
sql |
string | required | SQL to explain |
Analyses the actual data in a table — null rates, distinct counts, min/max/avg for numeric columns, and top values for low-cardinality columns.
| Parameter | Type | Default | Description |
|---|---|---|---|
table_name |
string | required | Table to profile |
schema_name |
string | public |
Schema name |
Reads PostgreSQL runtime statistics to find tables with heavy sequential scans (missing indexes), foreign key columns without indexes, and existing indexes that are never used.
| Parameter | Type | Default | Description |
|---|---|---|---|
schema_name |
string | public |
Schema to analyse |
table_name |
string | — | Limit to a specific table |
Three MCP resources are also exposed:
| Resource | URI | Returns |
|---|---|---|
| List schemas | postgres://schemas |
All non-system schema names |
| List tables | postgres://schemas/{schema}/tables |
Tables in a schema with their type |
| Table DDL | postgres://tables/{table}/ddl |
CREATE TABLE statement. Supports schema.table format. |
- Read-only by default —
PG_READ_ONLY=trueblocks anyINSERT,UPDATE,DELETE,DROP,ALTER, or other write operations. Set tofalseto allow writes. - Row limit — all queries are automatically capped at
PG_MAX_ROWS(default 1000) unless aLIMITis already present. - Parameterized queries — all database queries use
$1, $2placeholders. No user input is ever interpolated into SQL strings. - Read-only transactions —
execute_queryandexplain_querywrap every query inBEGIN READ ONLY.
src/
├── config.js # Environment variable config
├── server.js # MCP server entry point — registers all tools and resources
├── db/
│ ├── pool.js # pg.Pool singleton
│ ├── introspection.js # information_schema + pg_catalog query functions
│ └── safety.js # Read-only enforcement, row limiting, comment stripping
├── tools/
│ ├── schema.js # exploreSchema, describeTable, findRelationships
│ ├── query.js # executeQuery, explainQuery
│ ├── profiling.js # profileTable
│ └── optimization.js # suggestIndexes
└── nlsql/
├── prompts.js # System prompt + schema context builder
└── generator.js # generateSql — Anthropic API calls
Explore the public schema and give me an overview of what this database is for.
Describe the payment table in detail.
Find all tables related to film up to depth 2 and show me how they connect.
Show me the top 10 customers by total amount spent.
Which film categories generate the most revenue?
Find all films that have never been rented.
Generate SQL to find customers who rented more than 40 films.
Profile the payment table and tell me if there's anything unusual about the data.
Suggest indexes for the public schema — are there any missing or wasted indexes?
Find relationships between inventory, rental, and payment up to depth 2, then write a query that joins all of them to show which store makes the most money.
| Concern | Package |
|---|---|
| MCP server | @modelcontextprotocol/sdk |
| PostgreSQL | pg (node-postgres) |
| Environment vars | dotenv |
| NL-to-SQL | @anthropic-ai/sdk |







