PostgreSQL MCP Server

PostgreSQL MCP Server

postgres_mcp•byjavimaligno

An MCP server for PostgreSQL database operations, available in TypeScript and Python implementations for use with MCP-compatible clients.

License: MIT•Runtime: Awaiting documentation review•Category: databases storage

WHAT IT DOES

  • •Executes SQL queries against PostgreSQL with read-only protection enabled by default, and write operations available only when explicitly enabled.
  • •Provides schema exploration tools for listing schemas, tables, views, and functions, and describing table structures, indexes, and constraints.
  • •Offers performance tools including EXPLAIN plans, table statistics, index listing, and constraint inspection.
  • •Includes optional personal-data redaction that masks sensitive values in results before they reach the model.

BEST FOR

  • •Exploring and describing PostgreSQL schemas and structures from an MCP-compatible assistant.
  • •Running read-only SQL queries and analyzing query performance through an assistant.
  • •Generating documentation such as data dictionaries for a database schema.

ABOUT POSTGRES_MCP

PostgreSQL MCP Server is cataloged as an MCP server attributed to javimaligno. An MCP server for PostgreSQL database operations, available in TypeScript and Python implementations for use with MCP-compatible clients. It is categorized under databases storage. See the capability inspector for recorded interfaces and their independent review status; consult upstream documentation for the current interface.

HOW TO INSTALL

Installation configuration is not reviewed. No executable setup is offered for this entry; inspect the source repository before proceeding.

LICENSE

Catalog license label: MIT. Check the source repository's current license and terms before using, modifying or distributing this software.

能力检查器

能力定义尚未审核。未核验的采集内容不会作为可信接口展示。

Tools (0)

暂无可展示的已审核记录。这不表示上游不支持此能力。

Resources (0)

暂无可展示的已审核记录。这不表示上游不支持此能力。

Prompts (0)

暂无可展示的已审核记录。这不表示上游不支持此能力。

NEWSLETTER - COMING LATER

Newsletter subscriptions are not open yet

Email delivery is not connected. This page does not collect email addresses or create subscriptions.

Browse the registry for current listings instead.

Community Reviews

Coming later

Reviews for PostgreSQL MCP Server are not available yet

Review publishing and storage are not connected. This page does not collect or publish ratings or comments, including after sign-in.

上游原版 README

在 GitHub 查看同一版本原文

README.md · 4077292edf8f · 采集于 2026-11-13 11:58:57 UTC

保留上游原文,不做 AI 改写。为安全起见过滤脚本、表单和不安全链接。

当前显示最后一次成功采集的文档快照,请以来源页面为准。

PostgreSQL MCP Server

CI PyPI version npm version License: MIT

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:

VersionDirectoryStatusMCP protocolInstallation
TypeScript/typescript✅ Recommended (Smithery)2026-07-28 (SDK v2)npm install -g @javiagui/postgresql-mcp
Python/python✅ Stable2026-07-28 (SDK v2)pipx install postgresql-mcp

Note: The TypeScript version is used for Smithery deployments. Both versions provide identical functionality.

Protocol compatibility: both servers speak the 2026-07-28 revision and are dual-era — clients that still open with the 2025-era initialize handshake 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).

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

# Install globally
npm install -g @javiagui/postgresql-mcp

# Or run directly with npx
npx @javiagui/postgresql-mcp

Python

# 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-mcp

Full Installation Guide - Includes database permissions setup, remote connections, and troubleshooting.

Configuration

Environment Variables

VariableRequiredDefaultDescription
POSTGRES_HOSTlocalhostDatabase host
POSTGRES_PORT5432Database port
POSTGRES_USER✅Database user
POSTGRES_PASSWORD✅Database password
POSTGRES_DB✅Database name
POSTGRES_SSLMODEpreferSSL mode
ALLOW_WRITE_OPERATIONSfalseEnable INSERT/UPDATE/DELETE
QUERY_TIMEOUT30Query timeout (seconds)
MAX_ROWS1000Maximum rows returned
REDACT_PIIfalseMask personal data detected in string values (details)
REDACT_COLUMNSComma-separated columns to mask entirely
ALLOWED_COLUMNSComma-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_databases returns the configured aliases with host, database name, write permission and which is the default. Credentials are never returned.
  • Every other tool takes an optional database argument naming an alias. Omit it and you get the default connection — so an existing single-database setup keeps working with no changes at all.
  • allowWrite is per connection, falling back to ALLOW_WRITE_OPERATIONS. A production replica stays read-only while a local database allows writes.
  • default: true marks the connection used when database is 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 a url DSN — 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 database argument 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>", and current_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.
  • query and explain_query run in a READ ONLY transaction, so a query cannot create a temporary table that shadows an allowed one. Functions that write, such as nextval(), fail in query while redaction is on. With nothing configured, nothing changes.
  • If redaction fails, the result is withheld instead of being sent unredacted.
LayerSettingWhat it does
DetectionREDACT_PII=trueScans 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 [REDACTED:<kind>]. Identifiers with a check digit (cards, IBAN, DNI/NIE, Aadhaar) are only masked when the check digit is valid, so order numbers and dates stay readable. Finds personal data whatever the column is called, including inside free text.
Deny listREDACT_COLUMNS=email,customers.phoneMasks every value of the listed columns as [REDACTED:column].
Allow listALLOWED_COLUMNS=orders.*,customers.idReturns only the listed columns. Everything else is masked as [REDACTED:not_allowed].

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-mcp

Cursor 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

ToolDescription
queryExecute read-only SQL queries against the database
executeExecute write operations (INSERT/UPDATE/DELETE) when enabled
explain_queryGet EXPLAIN plan for query optimization

Schema Exploration

ToolDescription
list_schemasList all schemas in the database
list_tablesList tables in a specific schema
describe_tableGet table structure (columns, types, constraints)
list_viewsList views in a schema
describe_viewGet view definition and columns
list_functionsList functions and procedures

Performance & Analysis

ToolDescription
table_statsGet table statistics (row count, size, bloat)
list_indexesList indexes for a table
list_constraintsList constraints (PK, FK, UNIQUE, CHECK)

Database Info

ToolDescription
get_database_infoGet database version and connection info
search_columnsSearch for columns by name across all tables
list_databasesList 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:

PromptDescription
explore_databaseComprehensive database exploration and overview
query_builderHelp building efficient queries for a table
performance_analysisAnalyze table performance and suggest optimizations
data_dictionaryGenerate documentation for a schema

MCP Resources

Browsable database structure:

Resource URIDescription
postgres://schemasList all schemas
postgres://schemas/{schema}/tablesTables in a schema
postgres://schemas/{schema}/tables/{table}Table details
postgres://databaseDatabase 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 mode

Python

cd python
uv sync
uv run pytest -v --cov=postgres_mcp

Running 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 -v

Troubleshooting

Connection Issues

# Verify PostgreSQL is running
pg_isready -h localhost -p 5432

# Test connection with psql
psql -h localhost -U your_user -d your_database

Permission 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 messages

Author

Built by Javier Aguilar - AI Agent Architect specializing in multi-agent orchestration and MCP development.

License

MIT

Install configuration

Are you the maintainer?

Claim this server with your GitHub account to request manual ownership verification.

README Embed Badge
Markdown

Link to the catalog listing for PostgreSQL MCP Server from your README. This badge does not certify ownership, compatibility or security.

[![MCP catalog listing](https://img.shields.io/badge/MCP-awesome--mcp-orange?style=flat-square)](https://awesome-mcp.com/servers/postgres_mcp)

REPOSITORY STATS

GitHub StarsUnavailable
ForksUnavailable

Public repository statistics could not be verified. Check the configured source address; unavailable counts are not zero.

下载与拉取统计

来源、范围和时段分别列出;不相加,不代表安装人数、活跃用户或安全审核。

尚无已审核的包 / 镜像标识,暂不展示下载统计。

Related databases storage MCP Servers

Alternative and complementary servers in the same category

View all in databases storage →
AIStor MCP server
mcp-server-aistor•minio

This is a Model Context Protocol (MCP) server for interacting with AIStor object stores.

Repository stats unavailable
Databases & Storage
InfluxDB v2 MCP Server
influxdb-mcp-server•idoru

A Model Context Protocol (MCP) server that exposes access to an InfluxDB v2 instance using the InfluxDB OSS API v2.

Repository stats unavailable
Databases & Storage