postgres-mcp
Summary: Use postgres-mcp to safely inspect, query, and analyze a PostgreSQL database through MCP tools.
Run read-only SQL queries with
query.Run write statements with
executeonly when writes are explicitly enabled.Get EXPLAIN plans, optionally with ANALYZE execution stats.
Explore schemas, tables, views, and functions/procedures.
Describe table/view structure, columns, definitions, and constraints.
Inspect table statistics, indexes, and constraints.
Search for columns by name and retrieve database/connection info.
Benefit from safeguards described in the README: read-only default, SQL validation, row limits, query timeouts, credential protection, and optional PII redaction.
Note: the provided schema exposes these 14 tools; README-mentioned
list_databasesand per-tooldatabasealias arguments are not present in the schema.
Enables comprehensive PostgreSQL database operations including query execution, schema exploration, table analysis, performance optimization with EXPLAIN plans, and browsable database structure as MCP resources. Provides read-only access by default with optional write operations, SQL injection prevention, and tools for searching columns, analyzing statistics, and generating data dictionaries.
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., "@postgres-mcp show me the structure of the customers table"
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.
PostgreSQL MCP Server
MCP server for PostgreSQL database operations. Works with Claude Code, Claude Desktop, Cursor, and any MCP-compatible client.
Language Versions
This repository contains both TypeScript and Python implementations:
Version | Directory | Status | MCP protocol | Installation |
TypeScript |
| ✅ Recommended (Smithery) |
|
|
Python |
| ✅ Stable |
|
|
Note: The TypeScript version is used for Smithery deployments. Both versions provide identical functionality.
Protocol compatibility: both servers speak the
2026-07-28revision and are dual-era — clients that still open with the 2025-erainitializehandshake are served exactly as before, so no client needs upgrading. The TypeScript package requires patched Node.js 22.23.4 or 24.22.1; the Python package requires Python 3.11+ (CI uses patched 3.11.17 and 3.12.15).
Related MCP server: PostgreSQL MCP Server
Features
Query Execution: Execute SQL queries with read-only protection by default
Schema Exploration: List schemas, tables, views, and functions
Table Analysis: Describe structure, indexes, constraints, and statistics
Performance Tools: EXPLAIN queries and analyze table health
Security First: SQL injection prevention, credential protection, read-only by default
Personal-Data Redaction: Optional masking of emails, phones, cards, IBANs and national IDs before results reach the model, plus column deny and allow lists
MCP Prompts: Guided workflows for exploration, query building, and documentation
MCP Resources: Browsable database structure as markdown
Quick Start
TypeScript (Recommended for Smithery)
# Install globally
npm install -g @javiagui/postgresql-mcp
# Or run directly with npx
npx @javiagui/postgresql-mcpPython
# Install
pipx install postgresql-mcp
# Configure Claude Code
claude mcp add postgres -s user \
-e POSTGRES_HOST=localhost \
-e POSTGRES_USER=your_user \
-e POSTGRES_PASSWORD=your_password \
-e POSTGRES_DB=your_database \
-- postgresql-mcpFull Installation Guide - Includes database permissions setup, remote connections, and troubleshooting.
Configuration
Environment Variables
Variable | Required | Default | Description |
| localhost | Database host | |
| 5432 | Database port | |
| ✅ | Database user | |
| ✅ | Database password | |
| ✅ | Database name | |
| prefer | SSL mode | |
| false | Enable INSERT/UPDATE/DELETE | |
| 30 | Query timeout (seconds) | |
| 1000 | Maximum rows returned | |
| false | Mask personal data detected in string values (details) | |
| Comma-separated columns to mask entirely | ||
| Comma-separated allow list: every other column is masked |
Multiple databases
Most real work touches more than one database. Instead of editing this config and restarting your client every time, declare several connections and pick one per call by alias:
POSTGRES_CONNECTIONS='[
{"alias":"local","host":"localhost","user":"me","password":"…","database":"app","allowWrite":true},
{"alias":"staging","url":"postgresql://reader:…@staging.example.com:5432/app"},
{"alias":"analytics","url":"postgresql://reader:…@warehouse:6543/metrics?sslmode=require","default":true}
]'list_databasesreturns the configured aliases with host, database name, write permission and which is the default. Credentials are never returned.Every other tool takes an optional
databaseargument naming an alias. Omit it and you get the default connection — so an existing single-database setup keeps working with no changes at all.allowWriteis per connection, falling back toALLOW_WRITE_OPERATIONS. A production replica stays read-only while a local database allows writes.default: truemarks the connection used whendatabaseis omitted; otherwise it is the first one declared. At most one connection may be marked default.Each connection accepts either discrete fields (
host,port,user,password,database,sslmode) or aurlDSN — and discrete fields override the DSN, so you can reuse a URL and change one part of it.One pool per alias, opened lazily: a configured but unused database never opens a socket.
POSTGRES_CONNECTIONS and the plain POSTGRES_* variables are mutually
exclusive. When the first is set the others are ignored, so there is never a
question about which one won.
Credentials only ever come from the environment. The
databaseargument names an alias; there is deliberately no way to pass a host, user, password or connection string as a tool argument, because that would put secrets into the conversation. A test enforces this.
Personal data
By default rows are returned as they are stored. Three optional layers keep personal data from reaching the model. All of them run inside the server, after the query and before the result is sent, so the model never sees the masked values.
When any layer is active:
Errors are reduced, because PostgreSQL repeats values in them (
invalid input syntax …: "<value>", andcurrent_setting(col)can dump a whole column into one). With an allow list an error names only its condition, e.g.undefined_column, SQLSTATE 42703. Otherwise it keeps its first line, with every quoted string masked.queryandexplain_queryrun in aREAD ONLYtransaction, so a query cannot create a temporary table that shadows an allowed one. Functions that write, such asnextval(), fail inquerywhile redaction is on. With nothing configured, nothing changes.If redaction fails, the result is withheld instead of being sent unredacted.
Layer | Setting | What it does |
Detection |
| Scans every string, including JSON and arrays, and replaces emails, phone numbers, payment cards, IBANs, US SSNs, Spanish DNI/NIE, and Indian Aadhaar and PAN numbers with |
Deny list |
| Masks every value of the listed columns as |
Allow list |
| Returns only the listed columns. Everything else is masked as |
A rule is column, table.column or schema.table.column. Matching is
case-insensitive and * is a wildcard. Rules are matched against the column
a value was read from, which PostgreSQL reports for every result column, so
SELECT email AS e, subqueries, CTEs and joins do not get around them.
A value that is computed (an expression, an aggregate, a UNION) has no
source column:
the deny list cannot see it, so
upper(email)gets through;the allow list masks it, so
replace(email, '@', ' at '),count(*)and whole-row references (SELECT c FROM customers c) are masked. To expose an aggregate, define a view that computes it and allow the view's columns: views count as sources.
When a layer is active, the query result includes
"redacted": {"email": 2, "not_allowed": 5, …}, so the model knows which values
were masked on purpose. Every layer can be set per connection with
redactPii, redactColumns and allowedColumns in POSTGRES_CONNECTIONS,
which replace the global value for that connection.
Prefer schema.table.column rules in an allow list: customers.id matches a
customers table in any schema.
Which one to use. The allow list is the strictest option this server
offers, on a connection without allowWrite (with writes allowed, a query can
copy a hidden value into an allowed column first). Detection only recognises
ASCII digits. Detection is a safety net for free text, where a column name tells you
nothing. The deny list guards against accidents, not against a query written to
get around it. No output filter stops a query from using a hidden column
(WHERE email LIKE 'a%' still answers through the row count). When that
matters, give the server a database role without access to those columns
(column privileges or views). Database permissions are the only full guarantee,
and these layers work well alongside them.
Claude Code CLI
# TypeScript version
claude mcp add postgres -s user \
-e POSTGRES_HOST=localhost \
-e POSTGRES_USER=your_user \
-e POSTGRES_PASSWORD=your_password \
-e POSTGRES_DB=your_database \
-- npx @javiagui/postgresql-mcp
# Python version
claude mcp add postgres -s user \
-e POSTGRES_HOST=localhost \
-e POSTGRES_USER=your_user \
-e POSTGRES_PASSWORD=your_password \
-e POSTGRES_DB=your_database \
-- postgresql-mcpCursor IDE
Add to ~/.cursor/mcp.json:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["@javiagui/postgresql-mcp"],
"env": {
"POSTGRES_HOST": "localhost",
"POSTGRES_PORT": "5432",
"POSTGRES_USER": "your_user",
"POSTGRES_PASSWORD": "your_password",
"POSTGRES_DB": "your_database"
}
}
}
}Available Tools (15 total)
Every tool below except list_databases accepts an optional database argument
naming a configured connection — see Multiple databases.
Query Execution
Tool | Description |
| Execute read-only SQL queries against the database |
| Execute write operations (INSERT/UPDATE/DELETE) when enabled |
| Get EXPLAIN plan for query optimization |
Schema Exploration
Tool | Description |
| List all schemas in the database |
| List tables in a specific schema |
| Get table structure (columns, types, constraints) |
| List views in a schema |
| Get view definition and columns |
| List functions and procedures |
Performance & Analysis
Tool | Description |
| Get table statistics (row count, size, bloat) |
| List indexes for a table |
| List constraints (PK, FK, UNIQUE, CHECK) |
Database Info
Tool | Description |
| Get database version and connection info |
| Search for columns by name across all tables |
| List the configured connections by alias, with host, database, write permission and which is the default. Never returns credentials. |
MCP Prompts
Guided workflows that help Claude assist you effectively:
Prompt | Description |
| Comprehensive database exploration and overview |
| Help building efficient queries for a table |
| Analyze table performance and suggest optimizations |
| Generate documentation for a schema |
MCP Resources
Browsable database structure:
Resource URI | Description |
| List all schemas |
| Tables in a schema |
| Table details |
| Database connection info |
Example Usage
Once configured, ask Claude to:
Schema Exploration:
"List all tables in the public schema"
"Describe the users table structure"
"What views are available?"
Querying:
"Show me 10 rows from the orders table"
"Find all customers who placed orders last week"
"Count records grouped by status"
Performance Analysis:
"What indexes exist on the orders table?"
"Analyze the performance of the users table"
"Explain this query: SELECT * FROM orders WHERE created_at > '2024-01-01'"
Documentation:
"Generate a data dictionary for this database"
"What columns contain 'email' in their name?"
Security
This MCP server implements multiple security layers:
Read-Only by Default
Write operations (INSERT, UPDATE, DELETE) are blocked unless explicitly enabled via ALLOW_WRITE_OPERATIONS=true.
The check covers the whole statement, not only its first word: data-modifying CTEs
(WITH u AS (UPDATE …) SELECT …), SELECT … INTO, MERGE, DO and CALL are refused, and so
is more than one statement per call. Words inside string literals don't count, so
WHERE action = 'UPDATE' is still a read. This is a keyword check: a function that writes
when called from a SELECT is outside its reach. For a hard guarantee, connect with a role
that only has read privileges.
SQL Injection Prevention
All queries are validated before execution
Dangerous operations (DROP DATABASE, etc.) are always blocked
Multiple statements are not allowed
SQL comments are blocked
Credential Protection
Passwords stored using secure string types
Credentials never appear in logs or error messages
Personal-Data Redaction
Optional detection, deny lists and allow lists, applied to results and error messages before they reach the model — see Personal data
Query Limits
Results limited by
MAX_ROWS(default: 1000)Query timeout configurable via
QUERY_TIMEOUT
Development
TypeScript
cd typescript
npm install
npm run build
npm run dev # Watch modePython
cd python
uv sync
uv run pytest -v --cov=postgres_mcpRunning Tests
# Python unit tests (no database required)
cd python
uv run pytest tests/test_security.py tests/test_settings.py -v
# Integration tests (requires PostgreSQL)
docker-compose up -d
uv run pytest tests/test_integration.py -vTroubleshooting
Connection Issues
# Verify PostgreSQL is running
pg_isready -h localhost -p 5432
# Test connection with psql
psql -h localhost -U your_user -d your_databasePermission Denied
Ensure your database user has SELECT permissions:
GRANT SELECT ON ALL TABLES IN SCHEMA public TO your_user;MCP Server Not Connecting
# Check server status
claude mcp get postgres
# Test server directly
postgresql-mcp # Should wait for MCP messagesLinks
Author
Built by Javier Aguilar - AI Agent Architect specializing in multi-agent orchestration and MCP development.
License
MIT
Available Tools
14 toolsdescribe_tableA
Describe the structure of a table including columns, types, and constraints.
Args:
table_name: Name of the table to describe
schema: Schema name (default: public)
Returns:
Table structure with columns, primary keys, and foreign keys
Inputs: table_name (required), schema.
describe_viewA
Get the definition and columns of a view.
Args:
view_name: Name of the view
schema: Schema name (default: public)
Returns:
View definition SQL and column list
Inputs: view_name (required), schema.
executeA
Execute a write SQL statement (INSERT, UPDATE, DELETE).
WARNING: This tool modifies data. Use with caution.
Only available if ALLOW_WRITE_OPERATIONS=true is set.
Args:
sql: SQL statement to execute
Returns:
Execution result with affected row count
Inputs: sql (required).
explain_queryA
Get the execution plan for a SQL query (EXPLAIN).
Args:
sql: SQL query to explain
analyze: If true, actually runs the query to get real execution stats
(EXPLAIN ANALYZE). Use with caution on slow queries.
Returns:
Execution plan in JSON format with cost estimates
Inputs: sql (required), analyze.
get_database_infoB
Get database and connection information.
Returns:
Database version, connection info, and settings
Inputs: no named parameters.
list_constraintsA
List all constraints for a table (PK, FK, UNIQUE, CHECK).
Args:
table_name: Name of the table
schema: Schema name (default: public)
Returns:
List of constraints with type, columns, and references
Inputs: table_name (required), schema.
list_functionsB
List all functions and procedures in a schema.
Args:
schema: Schema name (default: public)
Returns:
List of functions with name, arguments, and return type
Inputs: schema.
list_indexesB
List all indexes for a table.
Args:
table_name: Name of the table
schema: Schema name (default: public)
Returns:
List of indexes with name, columns, type, and size
Inputs: table_name (required), schema.
list_schemasA
List all schemas in the PostgreSQL database.
Returns:
List of schemas with name and owner
Inputs: no named parameters.
list_tablesA
List all tables in a specific schema.
Args:
schema: Schema name to list tables from (default: public)
Returns:
List of tables with name and type
Inputs: schema.
list_viewsB
List all views in a schema.
Args:
schema: Schema name (default: public)
Returns:
List of views with name
Inputs: schema.
queryA
Execute a SQL query against the PostgreSQL database.
This tool is READ-ONLY by default. Use the 'execute' tool for write operations.
Args:
sql: SQL query to execute (SELECT statements only)
Returns:
Query results with rows, columns, and metadata
Inputs: sql (required).
search_columnsB
Search for columns by name across all tables.
Args:
search_term: Column name pattern to search (case-insensitive)
schema: Optional schema to limit search (default: all user schemas)
Returns:
List of matching columns with table information
Inputs: search_term (required), schema.
table_statsB
Get statistics for a table (row count, size, bloat).
Args:
table_name: Name of the table
schema: Schema name (default: public)
Returns:
Table statistics including row count, sizes, and vacuum info
Inputs: table_name (required), schema.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 14 tools
Each tool has a clearly distinct purpose with no ambiguity. For example, describe_table focuses on table structure, while table_stats provides statistical metrics, and list_constraints is separate from list_indexes. The descriptions clearly differentiate overlapping concepts like query (read-only) vs execute (write operations).
All tools follow a consistent verb_noun pattern with snake_case throughout. The naming convention is perfectly predictable: list_tables, describe_table, search_columns, explain_query, etc. There are no deviations in style or convention across the 14 tools.
14 tools is well-scoped for a PostgreSQL database management server. Each tool earns its place by covering distinct aspects of database interaction: schema exploration, table analysis, query execution, and metadata inspection. The count aligns perfectly with the comprehensive but focused domain coverage.
The tool surface provides complete coverage for PostgreSQL database interaction. It includes schema listing, table/view description, query execution (both read and write), performance analysis (explain_query), metadata inspection (constraints, indexes, functions), and search capabilities. No obvious gaps exist for typical database exploration and management workflows.
Maintenance
Related MCP Connectors
Hosted MCP server for PostgreSQL diagnostics: slow queries, missing indexes, connection pressure.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Managed Postgres MCP: projects, SQL, docs search, and storage buckets via OAuth.
Hosted PostgreSQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA secure MCP server that enables querying PostgreSQL databases through an SSH tunnel with enforced read-only access, connection pooling, and comprehensive data exploration tools.ISC
- AlicenseAqualityCmaintenanceFull-featured MCP server that exposes 36 tools for interacting with PostgreSQL databases, covering schema introspection, query execution, data exploration, performance monitoring, security auditing, and maintenance.365 npmMIT
- AlicenseNot gradedqualityCmaintenanceA cross-platform MCP server for querying and introspecting PostgreSQL databases with SSH tunnel support, featuring multi-layered query safety and read-only enforcement.13 npmMIT
- AlicenseAqualityCmaintenanceA comprehensive PostgreSQL MCP server providing 27 tools for database management and administration, including connection management, query execution, schema introspection, CRUD operations, and server monitoring.2738 npmAGPL 3.0