mcp-server-postgres
Provides tools to interact with PostgreSQL databases, executing validated SQL queries, schema inspection, transaction management, and more.
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., "@mcp-server-postgres What are the top 5 products by revenue?"
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.
🚀 mcp-server-postgres
Production-Grade, Schema-Aware PostgreSQL Agent via Model Context Protocol (MCP)
mcp-server-postgres is an intelligent database isolation layer designed to bridge the gap between Large Language Models (LLMs) and production PostgreSQL clusters. Developed with a security-first, schema-aware architecture, it translates natural language requests into validated, optimized, and ACID-compliant SQL.
🏗️ Technical Architecture
graph TD
Client[MCP Client/LLM] -->|JSON-RPC| Server[MCP Server Hub]
Server -->|Validation| Guard[Security Guardrails]
Guard -->|AST/Pattern Scan| SQL[Validated SQL]
SQL -->|Execution| Pool[Connection Pool Manager]
Pool -->|Write Ops| Primary[Primary DB]
Pool -->|Read Ops| Replica[Read Replicas]
Pool -->|Auditing| Audit[Pino Structured Logs]Key Architectural Pillars
Zero-Trust Safety Pipeline: Multi-stage validation including "SELECT *" detection, mandatory schema qualification, and SQL injection prevention.
Intelligent Pagination: Transparent query wrapping to ensure result boundedness (Default: 100 rows) without performance degradation.
Dynamic Schema Introspection: Enables LLMs to resolve exact table relationships and indexes in real-time.
Isolation Layers: Implements strict Permission Tiers (
READ_ONLYtoADMIN) to maintain least-privilege principles.
Related MCP server: PostgreSQL MCP Server
🔒 Security Guardrails (Non-Negotiable)
Rule-01: No Unbounded Writes: Rejects any
UPDATEorDELETEmissing an explicitWHEREclause.Rule-04: DDL Confirmation: High-risk schema mutations require a two-step tokenized confirmation flow.
Masking: Native support for PII redaction on sensitive columns (e.g.,
password_hash,ssn).Transaction Wrapping: All multi-statement operations are executed inside durable
BEGIN/COMMITblocks.
🛠️ Configuration
Configure your environment variables in .env:
Variable | Description | Default |
| Primary PostgreSQL DSN | Required |
| Optional replica DSN for read routing |
|
|
|
|
| Comma-separated list of columns to redact |
|
| Hard upper limit for result pages |
|
| Warning threshold for latency |
|
📋 Toolset API
query(sql, params, page, page_size): Executes validated SQL. Includes auto-pagination.nl_query(request, context): High-level translation interface (requires LLM bridge).schema_inspect(schema, table): Deep introspection of schema metadata.list_tables(schema): Optimized enumeration of current database schema.describe_table(schema, table): Column definitions, indexes, and FK relationships.explain(sql, params): Transparent query analyzer with cost estimation.transaction(operations): Atomic batch execution for complex mutations.confirm_ddl(token): Final execution of verified schema changes.
🚦 Getting Started
Development
npm install
npm run build
npm run startIntegration with Claude Desktop
Add to yours claude_desktop_config.json:
{
"mcpServers": {
"postgres": {
"command": "node",
"args": ["/absolute/path/to/mcp-server-postgres/dist/index.js"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/db",
"PERMISSION_TIER": "READ_WRITE"
}
}
}
}📈 Observability & Logging
All operations are logged via pino for enterprise observability.
{
"level": "INFO",
"module": "audit",
"operation_type": "QUERY",
"affected_tables": ["public.users"],
"execution_ms": 12.4,
"row_count": 8,
"agent_identity": "mcp-server-postgres"
}⚖️ License
MIT License. Created with precision by Ismail-2001.
Available Tools
8 toolsconfirm_ddlB
Confirms and executes high-risk DDL operations after receiving a validation token.
Inputs: token (required).
describe_tableB
Returns detailed column, index, and foreign key definitions.
Inputs: table (required), schema.
explainC
Run EXPLAIN (FORMAT JSON) and attach cost estimate and plan summary.
Inputs: sql (required), params, analyze.
list_tablesC
Lists all tables in the specified schema.
Inputs: schema.
nl_queryC
Intelligently translates natural language into validated, optimized SQL and executes it.
Inputs: request (required), context.
queryC
Executes a validated PostgreSQL query with parameterized inputs (Tier: READ_ONLY/READ_WRITE).
Inputs: sql (required), page, params, page_size.
schema_inspectC
Resolve exact table names, column names, types, nullability, and constraints.
Inputs: table, schema.
transactionC
Executes multiple write operations inside an explicit BEGIN/COMMIT block.
Inputs: operations (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Most tools are distinct, but schema_inspect and describe_table both return column/type/constraint information and overlap heavily. query and nl_query are separable by input style, and transaction vs confirm_ddl differ by write scope, but the schema inspection pair creates real misselection risk.
Mixed conventions: list_tables and describe_table follow verb_noun, schema_inspect reverses to noun_verb, nl_query is adjective_noun, and query/explain/transaction are bare single words. Still readable, but not a predictable pattern.
Eight tools is well within the ideal 3-15 range. Each tool maps to a meaningful capability (query, NL query, schema lookup, table listing, description, explain, transactions, DDL) without bloat.
Core lifecycle is covered: read/write queries, NL queries, transactions, DDL, schema inspection, and plan analysis. Minor gaps exist (no schema/database listing, no EXPLAIN ANALYZE, no views/functions inspection), but agents can work around them via query.
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Versioned agent memory in your own Postgres: portable context, permissioned, audit trail.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables LLMs to query and analyze PostgreSQL databases through a controlled interface. Supports SQL query execution, table schema inspection, and optional write operations with safety controls.600 npm178MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases through natural language queries, schema inspection, and safe SQL execution.1ISC
- AlicenseAqualityDmaintenanceEnables AI agents to securely query databases (PostgreSQL, SQLite, MySQL, DuckDB) with read-only defaults and multi-layer SQL injection prevention.81MIT
- FlicenseNot gradedqualityDmaintenanceEnables LLM agents to explore and query a Postgres database through secure, read-only tools.-