Skip to content

About

A Javascript based MCP that lets an agent explore a database

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

pg-schema-explorer-mcp

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.

MCP server connected in Claude Desktop


What it does

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

Demo

Exploring a schema

Ask Claude to explore your database and it will map out every table, column, and relationship.

Schema exploration showing tables and views

Relationship graph

Claude can traverse the foreign key graph and render an ERD-style diagram showing how tables connect.

ERD diagram generated from find_relationships

Natural language to SQL

Describe what you want in plain English — Claude generates the query, runs it, and shows the results.

Generate SQL for customers who rented more than 40 films

Data profiling

Profile any table to surface data quality issues — anomalous sequences, sparse columns, zero-value records.

Payment table profiled showing anomalies

Multi-step analysis

Claude can chain tools together — traverse relationships, generate a join query, execute it, and interpret the results.

Multi-step query joining inventory, rental, payment Revenue query results by store


Prerequisites

  • Node.js 18+
  • A running PostgreSQL instance
  • Claude Desktop (for MCP integration)
  • An Anthropic API key (only required for the generate_sql tool)

Installation

git clone <repo-url>
cd pg-schema-explorer-mcp
npm install

Configuration

Create 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

Claude Desktop setup

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-..."
      }
    }
  }
}

Tool permission prompt in Claude Desktop


Tools reference

explore_schema

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

describe_table

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

find_relationships

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

generate_sql

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

execute_query

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

explain_query

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

profile_table

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

suggest_indexes

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

Resources

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.

Safety

  • Read-only by default — PG_READ_ONLY=true blocks any INSERT, UPDATE, DELETE, DROP, ALTER, or other write operations. Set to false to allow writes.
  • Row limit — all queries are automatically capped at PG_MAX_ROWS (default 1000) unless a LIMIT is already present.
  • Parameterized queries — all database queries use $1, $2 placeholders. No user input is ever interpolated into SQL strings.
  • Read-only transactions — execute_query and explain_query wrap every query in BEGIN READ ONLY.

Project structure

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

Example prompts to try

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.

Tech stack

Concern Package
MCP server @modelcontextprotocol/sdk
PostgreSQL pg (node-postgres)
Environment vars dotenv
NL-to-SQL @anthropic-ai/sdk

About

A Javascript based MCP that lets an agent explore a database

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages