logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

postgres-mcp-pro

A Model Context Protocol server tailored for PostgreSQL, delivering essential capabilities like comprehensive database diagnostics, intelligent index refinement, and secure, controlled SQL command execution to bolster software engineering pipelines.

Author

postgres-mcp-pro logo

crystaldba

MIT License

Quick Info

GitHub GitHub Stars 1264
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

postgrescrystaldbadatabasecrystaldba postgresmcp postgrespostgres mcp
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![PyPI - Version](https://img.shields.io/pypi/v/postgres-mcp)](https://pypi.org/project/postgres-mcp/) [![Discord](https://img.shields.io/discord/1336769798603931789?label=Discord)](https://discord.gg/4BEHC7ZM) [![Twitter Follow](https://img.shields.io/twitter/follow/auto_dba?style=flat)](https://x.com/auto_dba) [![Contributors](https://img.shields.io/github/contributors/crystaldba/postgres-mcp)](https://github.com/crystaldba/postgres-mcp/graphs/contributors)

A robust Postgres MCP endpoint featuring schema introspection, automated index optimization, system health telemetry, and permission-gated SQL execution.

Overview

Postgres MCP Pro serves as an open-source Model Context Protocol (MCP) gateway engineered to support human developers and autonomous AI agents across the complete software lifecycle—spanning from initial code creation, through rigorous testing and deployment, and into production performance monitoring and ongoing maintenance.

This component transcends mere database connection wrapping.

Key capabilities include:

  • 🔍 System Status Telemetry - In-depth analysis of index efficiency, connection pool usage, buffer cache utilization, vacuum status, sequence upper bounds, replication synchronization lag, and numerous other performance indicators.
  • ⚡ Index Optimization - Exploration of potentially thousands of index permutations to discover the optimal configuration for your specific operational workload, utilizing sophisticated, battle-tested algorithms.
  • 📈 Query Plan Analysis - Verification and performance tuning via detailed examination of EXPLAIN outputs, including the capacity to model the effect of hypothetical new indexes.
  • 🧠 Schema Contextualization - Intelligent, context-aware SQL generation derived from a deep, nuanced understanding of the underlying database schema structure.
  • 🛡️ Controlled SQL Invocation - Granular access governance, encompassing read-only operational modes and safe SQL parsing mechanisms, ensuring suitability for both iterative development and high-stakes production environments.

Postgres MCP Pro supports both the Standard Input/Output (stdio) and Server-Sent Events (SSE) communication methodologies, offering deployment flexibility.

For deeper context on the motivation behind Postgres MCP Pro, consult our introductory article.

Demo

From Impaired Functionality to High Velocity - The Obstacle: An application generated via an AI assistant exhibited prohibitively slow performance due to SQLAlchemy ORM interactions. - The Resolution: Leveraging Postgres MCP Pro alongside Cursor, these performance bottlenecks were resolved in mere minutes.

Actions performed: - 🚀 Performance Remediation - Including ORM query fixes, strategic indexing, and caching adjustments. - 🛠️ Feature Repair - By instructing the agent to explore data structure, correct faulty queries, and integrate supplementary content. - 🧠 Result Enhancement - Improving top-tier data surfacing by refining the ORM query logic.

Review the accompanying video or the detailed step-by-step walkthrough.

https://github.com/user-attachments/assets/24e05745-65e9-4998-b877-a368f1eadc13

Quick Start

Prerequisites

To begin, you must possess: 1. Authentication credentials for the target database instance. 2. Either Docker installed or Python version 3.12 or newer.

Authentication Credentials

Validate your connection details using the standard psql utility or a graphical administration tool like pgAdmin.

Docker or Python Environment Choice

The decision between Docker and Python deployment is yours. Docker is often suggested as it isolates dependency issues common in Python environments. Nevertheless, select the method where you possess the greatest familiarity.

Installation

Select one installation path for Postgres MCP Pro:

Option 1: Utilizing Docker

Retrieve the official Postgres MCP Pro server Docker image. This container bundles all required components, ensuring consistent execution across diverse operational settings.

bash docker pull crystaldba/postgres-mcp

Option 2: Employing Python

If pipx is available, install Postgres MCP Pro via:

bash pipx install postgres-mcp

Alternatively, use the uv package installer:

bash uv pip install postgres-mcp

Instructions for installing uv are located in the official uv documentation.

Configuring Your AI Companion

Comprehensive guidance is provided for integrating Postgres MCP Pro with Claude Desktop. Most MCP-compatible clients share analogous configuration mechanisms; these instructions can be adapted for your chosen tool.

Claude Desktop Configuration

Modification of the Claude Desktop configuration file is necessary to incorporate Postgres MCP Pro. File path location varies by operating system: - MacOS: ~/Library/Application Support/Claude/claude_desktop_config.json - Windows: %APPDATA%/Claude/claude_desktop_config.json

You can also pinpoint this file via the Settings interface within Claude Desktop.

Edit the mcpServers segment of the configuration document.

If Utilizing Docker

{ "mcpServers": { "postgres": { "command": "docker", "args": [ "run", "-i", "--rm", "-e", "DATABASE_URI", "crystaldba/postgres-mcp", "--access-mode=unrestricted" ], "env": { "DATABASE_URI": "postgresql://username:password@localhost:5432/dbname" } } } }

The Postgres MCP Pro container image automatically resolves the localhost hostname for internal container networking.

  • MacOS/Windows: Maps transparently to host.docker.internal
  • Linux: Maps transparently to 172.17.0.1 or the appropriate host gateway address
If Utilizing pipx

{ "mcpServers": { "postgres": { "command": "postgres-mcp", "args": [ "--access-mode=unrestricted" ], "env": { "DATABASE_URI": "postgresql://username:password@localhost:5432/dbname" } } } }

If Utilizing uv

{ "mcpServers": { "postgres": { "command": "uv", "args": [ "run", "postgres-mcp", "--access-mode=unrestricted" ], "env": { "DATABASE_URI": "postgresql://username:password@localhost:5432/dbname" } } } }

Connection URI

Substitute the placeholder postgresql://... with your actual Postgres connection string URI.

Operational Mode Selection

Postgres MCP Pro enforces distinct operational modes to govern the scope of actions an integrated AI agent can execute against the database: - Unrestricted Mode: Grants full read/write privileges for both data manipulation and schema definition changes. Ideal for dynamic development environments. - Restricted Mode: Confines operations strictly to read-only transactions and enforces limits on resource consumption (currently restricted to execution duration). This mode is recommended for production deployments.

To engage restricted mode, replace --access-mode=unrestricted with --access-mode=restricted in the preceding configuration samples.

Other MCP Clients

Configuration file structures across various MCP clients are similar to Claude Desktop; adapt the preceding examples accordingly.

  • For Cursor, access the configuration file via the Command Palette, navigating to Cursor Settings, then selecting the MCP tab.
  • For Windsurf, open Windsurf Settings Page from the Command Palette.
  • For Goose, execute goose configure and select Add Extension.

SSE Transport

Postgres MCP Pro is compatible with the SSE transport protocol, enabling multiple MCP consumers to share a single, potentially remote, server instance. To activate this, launch the server using the --transport=sse flag.

Example using Docker:

bash docker run -p 8000:8000 \ -e DATABASE_URI=postgresql://username:password@localhost:5432/dbname \ crystaldba/postgres-mcp --access-mode=unrestricted --transport=sse

Subsequently, configure your MCP client to target this server endpoint. For instance, in Claude Desktop's mcp.json or Cline's cline_mcp_settings.json, you would specify:

{ "mcpServers": { "postgres": { "type": "sse", "url": "http://localhost:8000/sse" } } }

Windsurf's configuration format in mcp_config.json requires a minor variation:

{ "mcpServers": { "postgres": { "type": "sse", "serverUrl": "http://localhost:8000/sse" } } }

Postgres Extension Installation (Optional)

Enabling advanced features like index tuning and comprehensive performance analysis necessitates the loading of the pg_statements and hypopg extensions within your database environment.

  • The pg_statements extension facilitates the capture of executed query statistics. For instance, this data reveals which queries exhibit high latency or consume disproportionate system resources.
  • The hypopg extension empowers Postgres MCP Pro to model the query planner's anticipated execution path when hypothetical indexes are introduced.

Installing extensions on Cloud Managed Services (AWS RDS, Azure SQL, Google Cloud SQL)

For Postgres instances hosted on major cloud platforms, these extensions are typically pre-provisioned. Execution of the following SQL commands using an authorized role is sufficient:

sql CREATE EXTENSION IF NOT EXISTS pg_statements; CREATE EXTENSION IF NOT EXISTS hypopg;

Installing extensions on Self-Managed Postgres

If you administer the Postgres installation directly, additional configuration may be required. Prior to loading pg_statements, it must be declared in the shared_preload_libraries section of the primary Postgres configuration file. Furthermore, hypopg might require manual system-level installation via your operating system's package manager, as it is not always bundled with the core Postgres distribution.

Usage Examples

Obtain Database Health Summary

Prompt:

Inspect the current operational status of the database and flag any encountered anomalies.

Investigate Latent Queries

Prompt:

Which queries exhibit the longest execution times? Furthermore, propose actionable strategies for performance enhancement.

Acquire Acceleration Recommendations

Prompt:

My application performance is suboptimal. What steps can I take to improve responsiveness?

Generate Indexing Suggestions

Prompt:

Analyze the database workload profile and propose an optimal set of indexes to elevate performance metrics.

Tune a Specific SQL Statement

Prompt:

Please optimize the following data retrieval request: SELECT * FROM orders JOIN customers ON orders.customer_id = customers.id WHERE orders.created_at > '2023-01-01';

MCP Server API

The MCP specification delineates several endpoint categories: Tools, Resources, Prompts, and others.

Postgres MCP Pro exclusively exposes its functionality through MCP tools. This design choice prioritizes compatibility with the broader MCP client ecosystem, which heavily favors tool invocation. This contrasts with alternative Postgres MCP implementations, such as the Reference Postgres MCP Server, which rely on MCP resources for schema exposure.

Postgres MCP Pro Tool Set:

Tool Name Functionality Summary
list_schemas Enumerates all recognized database schemas within the running PostgreSQL instance.
list_objects Retrieves a catalog of database constructs (tables, views, sequences, extensions) belonging to a specified schema.
get_object_details Furnishes metadata for a designated database entity, such as column definitions, integrity constraints, and existing indexes.
execute_sql Executes SQL commands against the database; restricted to read-only operations when configured in restricted mode.
explain_query Retrieves the execution plan detailing PostgreSQL's intended query processing steps and exposing the planner's cost estimation. Can simulate the impact of hypothetical indexes.
get_top_queries Reports the most time-consuming SQL statements based on aggregate execution duration, sourced from pg_stat_statements data.
analyze_workload_indexes Scans the operational workload to pinpoint resource-intensive queries, subsequently recommending optimal indexing structures.
analyze_query_indexes Evaluates a selection of up to 10 specific SQL statements and proposes the most effective indexes for each.
analyze_db_health Executes a comprehensive system audit covering: buffer cache efficiency, connection status, constraint integrity, index condition (redundancy/obsolescence/invalidity), sequence capacity, and vacuum necessity.

Postgres MCP Servers - Query MCP. An MCP server for Supabase Postgres featuring a three-layer security framework and Supabase control API integration. - PG-MCP. A PostgreSQL MCP server offering flexible connectivity, execution plan diagnostics, extension context awareness, and more. - Reference PostgreSQL MCP Server. A minimal MCP Server implementation exposing schema details via MCP resources and supporting read-only query execution. - Supabase Postgres MCP Server. This server integrates Supabase administrative functionalities and receives active maintenance from the Supabase community. - Nile MCP Server. Provides an MCP gateway to the administrative interface for Nile's multi-tenant PostgreSQL service. - Neon MCP Server. An MCP server facilitating access to the management API for Neon's serverless PostgreSQL offering. - Wren MCP Server. Delivers a semantic reasoning engine tailored for analytical processing of PostgreSQL and other data sources.

DBA Tools (Including Commercial Solutions) - Aiven Database Optimizer. A platform providing holistic analysis of database workloads, query tuning suggestions, and various performance enhancements. - dba.ai. An AI-driven database administration assistant integrated with GitHub for automated issue resolution in code. - pgAnalyze. A comprehensive platform for monitoring and analytics, designed to pinpoint performance bottlenecks, refine queries, and provide real-time alerts. - Postgres.ai. An interactive conversational interface combining an extensive PostgreSQL knowledge repository with GPT-4 capabilities. - Xata Agent. An open-source agent that autonomously monitors database health, diagnoses system failures, and furnishes recommendations utilizing LLM-driven logic and predefined playbooks.

Postgres Utilities - Dexter. A utility for generating and validating hypothetical indexes within PostgreSQL. - PgHero. A performance dashboard focused on PostgreSQL, complete with optimization advisories. Postgres MCP Pro incorporates health metrics derived from PgHero. - PgTune. A tool applying heuristic rules to tune PostgreSQL configuration parameters.

Frequently Asked Questions

How does Postgres MCP Pro distinguish itself from other PostgreSQL MCP servers? Numerous MCP endpoints permit an AI agent to issue queries against a PostgreSQL database. Postgres MCP Pro fulfills this basic requirement but significantly extends functionality by providing dedicated tools for performance comprehension and enhancement. For instance, it implements a specialized version of the Anytime Algorithm for Database Tuning Advisor found in Microsoft SQL Server, representing a contemporary, industrial-grade technique for automated index optimization.

Postgres MCP Pro Alternative Postgres MCP Servers
✅ Deterministic Health Audits ❌ Non-Reproducible Health Queries Generated by LLMs
✅ Principled Index Search Methodologies ❌ Heuristic Guesswork for Index Enhancements
✅ Workload Analysis for Top Issues ❌ Inconsistent Diagnosis of Performance Problems
✅ Simulation of Performance Gains ❌ Manual Verification Required for Proposed Changes

Postgres MCP Pro augments generative AI capabilities by integrating reliable procedural tools based on established optimization principles. This synthesis delivers both consistency and flexibility.

Why are MCP tools necessary when LLMs can perform reasoning, SQL generation, etc., independently? LLMs excel in tasks involving natural language processing, complex reasoning, and ambiguity resolution. However, when contrasted with deterministic procedural code, LLMs can introduce latency, higher operational cost, non-determinism, and occasional inaccuracies. For database optimization, we possess decades of proven, mathematically sound algorithms. Postgres MCP Pro enables a synthesis of the best attributes of both paradigms: coupling the reasoning power of LLMs with the reliability of classical optimization procedures and dedicated tools.

How is the reliability of Postgres MCP Pro verified? Rigorous testing is fundamental to ensuring the accuracy and dependability of Postgres MCP Pro. We are actively developing a comprehensive suite of adversarial workloads, specifically engineered by AI, to stress-test the server under a wide spectrum of operational scenarios.

Which PostgreSQL versions are compatible? Our current validation efforts are concentrated on PostgreSQL versions 15, 16, and 17. The intended support scope encompasses versions 13 through 17.

Who is the originator of this project? This software initiative is developed and presently sustained by Crystal DBA.

Roadmap

To Be Determined

Your specific requirements will significantly shape future feature development. Share your priorities by filing an issue or submitting a pull request. Direct contact is also welcome via Discord.

Technical Notes

This section outlines key technical design decisions and considerations underpinning Postgres MCP Pro.

Index Tuning

Database performance bottlenecks are frequently traceable to inadequate indexing. Indexes furnish specialized access paths enabling PostgreSQL to rapidly retrieve necessary data for query execution. While indexes offer minimal benefit on small tables, their importance escalates dramatically with data volume, shifting complexity from linear scan (O(n)) toward logarithmic lookup (O(log n)), which is further compounded in multi-table joins.

Index recommendation generation within Postgres MCP Pro follows a multi-stage process:

  1. Identification of Queries Requiring Optimization. If a user specifies a problematic SQL statement, it becomes a tuning target. Alternatively, Postgres MCP Pro can automatically surface candidates by analyzing the overall workload. This relies on the pg_stat_statements extension capturing runtime metrics and resource consumption per query.

    A query is deemed index-tunable if it ranks highly either by cumulative resource usage or by its average execution cost. Currently, execution time serves as the proxy for aggregate resource consumption, though focusing on specific metrics like block access counts or disk reads could be beneficial. The analyze_query_workload tool prioritizes queries based on execution time, using thresholds for execution frequency and mean latency. Agents can first invoke get_top_queries (which discriminates between mean vs. total time) and then feed the results to analyze_query_indexes for specific index suggestions.

    Advanced indexing systems employ "workload compression" to distill a representative sample of queries, mirroring the workload's essence. Postgres MCP Pro implements a basic form of this by canonicalizing structurally identical queries (originating from the same template) into a single entry. It currently applies equal weighting to each query, a pragmatic simplification effective when indexing benefits are substantial.

  2. Candidate Index Generation. Following the selection of target queries for performance enhancement via indexing, the system generates a set of potentially useful indexes. This involves parsing the SQL structure to isolate columns utilized in filtering (WHERE), joining, grouping (GROUP BY), or ordering (ORDER BY).

    To cover all possibilities, we must account for column combinations, as PostgreSQL supports multicolumn indexes. In the current version, we arbitrarily select only one ordering permutation for any given multicolumn set, simplifying the search space because index permutations often yield similar performance profiles. Future enhancements aim to address this limitation.

  3. Optimal Index Configuration Search. The goal is to determine the index set that optimally balances the projected query performance gain against the overhead associated with index storage and update costs. Performance projections are estimated using the hypopg extension’s "what if" simulation capabilities. This simulates how the PostgreSQL planner would interpret the query plan given the newly proposed indexes, reporting cost adjustments based on PostgreSQL's actual cost model.

    A complexity arises because generating accurate query plans typically necessitates knowledge of specific input parameter values used during execution. Query normalization, essential for reducing the candidate set, strips away these constant values. Similarly, parameters passed via bind variables are inaccessible.

    To overcome this, we generate representative constant values by sampling from table statistics for use as input parameters. While PostgreSQL 16 introduced generic EXPLAIN functionality, it has shortcomings (e.g., with LIKE predicates) that our internal implementation avoids.

    The search methodology is crucial, as exhaustively evaluating every possible index combination is computationally feasible only for trivial schemas. This distinction defines various indexing approaches. Mirroring the strategy of Microsoft's Anytime algorithm, we employ a greedy search: first identifying the best single-index solution, then determining the best index to augment that solution, and so on. The search terminates either when the allocated time budget is depleted or when a full iteration yields no performance improvement exceeding a 10% minimum threshold.

  4. Cost-Benefit Assessment. When presented with two indexing choices—one favoring speed, the other favoring storage efficiency—a selection criterion is required. Traditional index advisors require a fixed storage budget. We also consider storage, but integrate cost-benefit evaluation throughout the optimization process.

    We model this as selecting an optimal point on the Pareto front—the set of solutions where improving one metric necessitates degrading another. Ideally, we would quantify storage cost and performance gains monetarily. A simpler, more pragmatic approach is comparing relative improvements. Most stakeholders accept a 100x speedup even with a 2x storage increase. Our implementation uses a configurable ratio for this trade-off. By default, we require the logarithmic (base 10) change in performance improvement to be at least twice the change in the logarithm of the storage cost increase. This translates to permitting up to a 10x storage overhead for a 100x performance benefit.

Our implementation draws closest parallels to the Anytime Algorithm utilized in Microsoft SQL Server. Compared to Dexter, another automated indexing utility for Postgres, we explore a wider solution space and employ distinct heuristics, resulting in superior recommendations at the expense of longer computation times.

Furthermore, we document the incremental work performed during each search iteration, including side-by-side comparisons of query plans before and after index addition. This detailed evidence provides the LLM with richer context for interpreting the indexing suggestions.

Experimental: Index Tuning via LLM

Postgres MCP Pro incorporates an experimental index tuning method inspired by the paper, Optimization by LLM. Instead of relying on predefined heuristics to navigate potential index configurations, this method feeds the database schema and query plans directly to an LLM, soliciting index proposals. We then leverage hypopg to forecast the performance of these suggested indexes, feeding the simulation results back to the LLM for refinement in subsequent iterations. This loop continues until iterative improvements become negligible.

LLM-driven index optimization shows promise when the index search domain is vast, or when indexes involving numerous columns are relevant. Like the traditional search techniques, its efficacy is contingent upon the precision of the performance predictions generated by hypopg.

To enable LLM-based optimization, an active OpenAI API key must be supplied by setting the OPENAI_API_KEY environmental variable.

Database Health

Database health assessments are crucial for preemptively identifying maintenance requirements and tuning opportunities before they manifest as critical service disruptions. In the current iteration, Postgres MCP Pro adopts the health check logic directly from PgHero. We are undertaking full validation of these checks and anticipate expanding the coverage in future releases.

  • Index Condition Checks. Identifies indexes that are either never used, redundant (duplicates), or excessively large (bloated). Bloated indexes waste valuable page space. Postgres's autovacuum process reclaims space from index entries pointing to terminated rows, marking those segments as available. However, it does not typically compact the index pages themselves, leading to pages containing sparse usage.
  • Buffer Cache Hit Ratio. Quantifies the percentage of data reads satisfied from the in-memory buffer cache versus physical disk I/O. A low ratio signals a potential performance bottleneck requiring investigation, as it suggests suboptimal memory utilization.
  • Connection Pool Status. Monitors the number of active connections and their current utilization state. The primary risk is exhausting the connection limit, but a high volume of connections that are idle or actively waiting (blocked) also indicates underlying structural issues.
  • Vacuum Maintenance. Vacuuming is vital for multiple reasons, most critically to avert transaction ID wraparound, which can halt all database writes. PostgreSQL's Multi-Version Concurrency Control (MVCC) assigns a unique ID to every transaction. Since PostgreSQL uses a 32-bit signed integer for these IDs, reuse becomes necessary after approximately two billion transactions. To facilitate reuse, PostgreSQL "freezes" the transaction IDs of very old transactions, marking them as belonging to the distant past. When data pages are flushed to disk, they record visibility information relative to a transaction ID range. Before reusing these IDs, PostgreSQL must update all on-disk records, "freezing" them to erase dependencies on the impending reusable IDs. This specific check monitors tables that are nearing the threshold requiring aggressive vacuuming to prevent ID wraparound.
  • Replication Synchronization. Verifies the health of standby servers by monitoring the synchronization lag relative to the primary, confirming replication status, and tracking the consumption of dedicated replication slots.
  • Constraint Integrity. During standard operations, PostgreSQL rejects transactions that violate defined constraints. However, constraints can become invalid following bulk data loading or during recovery procedures. This check scans for any constraints flagged as invalid.
  • Sequence Capacity. Monitors user-defined sequences to flag those approaching their defined maximum numeric limit, which would otherwise cause insertion failures.

Postgres Client Library

Postgres MCP Pro leverages the psycopg3 driver for asynchronous PostgreSQL connectivity. Internally, psycopg3 relies on the standard libpq library, granting access to the full spectrum of PostgreSQL features through a library maintained and supported directly by the PostgreSQL community.

Some alternative Python-based MCP servers opt for asyncpg, which can simplify deployment by abstracting away the libpq dependency. Anecdotal evidence suggests asyncpg might offer superior raw performance than psycopg3, although we have not independently benchmarked this claim. Older performance comparisons showed a more significant divergence, implying that the recent advancements in psycopg3 have narrowed this gap.

We selected psycopg3 over asyncpg based on a careful evaluation of driver maturity and feature completeness, while remaining open to revisiting this decision as driver technologies evolve.

Connection Configuration Strategy

Similar to the Reference PostgreSQL MCP Server, Postgres MCP Pro accepts the PostgreSQL connection string upon initialization. This is highly efficient for users consistently targeting a single database instance but introduces friction when frequently switching targets.

An alternative pattern, employed by PG-MCP, involves passing connection parameters dynamically via MCP tool calls at the time of need. This enhances usability for context-switching users and allows a single MCP server instance to concurrently serve multiple end-users.

A more optimal architectural approach likely exists between these two models. Both present security vulnerabilities: few MCP clients manage the server configuration securely (Goose is an exception), and credentials supplied via tool calls traverse the LLM, potentially persisting in chat history. Both connection strategies also introduce usability friction depending on the operational context.

Schema Information Provisioning

The function of the schema information tool is to equip the invoking AI agent with the necessary metadata to formulate accurate and performant SQL statements. For example, to answer a query like, "What was the total count of outbound flights from San Francisco to Paris within the last twelve months?", the agent must identify the correct flight data table, the columns designating origin/destination points, and potentially a mapping table linking airport codes to geographical locations.

Why expose schema details via dedicated tools when modern LLMs are often proficient at querying the PostgreSQL metadata directly?

Our empirical testing with Claude has demonstrated high proficiency in generating SQL to explore the PostgreSQL schema by querying the Postgres system catalog and the ANSI-standardized information schema. However, the reliability of this direct exploration method across the entire spectrum of available LLMs remains unconfirmed.

Is using MCP tools preferable to utilizing MCP resources for schema dissemination?

The Reference PostgreSQL MCP Server employs resources to present schema metadata rather than tools. Navigating resources resembles file system traversal, which is intuitively logical in many respects. Nonetheless, resource support is less universally adopted across the MCP client landscape (see example clients) compared to tool invocation. Furthermore, although the MCP standard suggests resources are accessible by both agents and end-users, certain clients restrict interaction to human navigation of the resource hierarchy.

Controlled SQL Execution

The proliferation of AI amplifies existing security challenges inherent in database management, spanning from inadvertent user errors to deliberate, sophisticated intrusions. The defense framework addressing threats—whether accidental or malicious—must cover three pillars: confidentiality, integrity, and availability. The classic conflict between operational convenience and stringent safety protocols is especially pronounced here.

Postgres MCP Pro's protected execution model specifically targets integrity. Within the MCP context, the principal concern is LLM-generated SQL causing unintended harm—such as erroneous data destruction or modification, or unauthorized alterations that bypass established organizational change management procedures.

The most straightforward path to integrity assurance is enforcing that all executed SQL adheres strictly to read-only operations. While creating a dedicated read-only database credential is a valid strategy, it often proves impractical for developers. Since PostgreSQL lacks a native mechanism to place an entire connection or session into a read-only state, Postgres MCP Pro employs a more intricate technique to enforce read-only execution over a standard read-write connection.

Postgres MCP implements a read-only transaction mode designed to block all data and schema modifications. Similar to the approach taken by the Reference PostgreSQL MCP Server, we use read-only transactions to enforce protection.

To fortify this mechanism, we must guard against SQL sequences that might escape the read-only transaction scope, such as executing explicit COMMIT or ROLLBACK commands followed immediately by new transactional statements.

For instance, an LLM could potentially subvert the read-only transaction by issuing a ROLLBACK and then initiating a fresh transaction: sql ROLLBACK; DROP TABLE users;

To neutralize such scenarios, all SQL is subjected to pre-execution parsing using the pglast library. Any submitted script containing explicit commit or rollback keywords is immediately rejected. Fortunately, the most prevalent PostgreSQL procedural languages (PL/pgSQL, PL/Python) inherently disallow COMMIT or ROLLBACK statements within their scopes. If a database permits unsafe procedural languages, the server's read-only protections could theoretically be bypassed.

Presently, Postgres MCP Pro offers two security postures representing the opposite ends of the convenience-to-safety spectrum: - "Unrestricted" prioritizes flexibility above all else. It is suited for development environments where speed and agility are critical, and the data involved holds no significant value or sensitivity. - "Restricted" seeks a prudent equilibrium between operational flexibility and security. This mode is recommended for production systems exposed to external or untrusted entities, where safeguarding valuable or sensitive information is paramount. We also impose limits on query execution time to prevent resource exhaustion.

Unrestricted mode mirrors the philosophy of Cursor's auto-run feature, where the AI agent proceeds with minimal human intervention or explicit approval. We anticipate auto-run deployments will primarily occur in development sandboxes where the impact of errors is negligible, databases lack sensitive information, and rapid restoration from backups is feasible.

Restricted mode was architected conservatively, prioritizing safety even if it introduces minor friction. Operations are confined to read-only requests, and execution duration is capped to safeguard system responsiveness. We plan to implement further safeguards to guarantee the robustness of restricted mode when interacting with live production databases.

Postgres MCP Pro Development

The subsequent instructions are directed towards contributors wishing to engage in active development of Postgres MCP Pro or users who prefer installing the software directly from its source code.

Local Development Environment Setup

  1. Install uv:

bash curl -sSL https://astral.sh/uv/install.sh | sh

  1. Clone the source repository:

bash git clone https://github.com/crystaldba/postgres-mcp.git cd postgres-mcp

  1. Install required packages:

bash uv pip install -e . # Installs in editable mode uv sync # Ensures all dependencies are resolved and installed

  1. Execute the server locally: bash uv run postgres-mcp "postgres://user:password@localhost:5432/dbname"

WIKIPEDIA: XMLHttpRequest (XHR) is a standardized application programming interface accessible via JavaScript objects. Its methods enable the transmission of HTTP requests from a client-side web browser to a remote server. These functions allow web-based applications to communicate with the server asynchronously following page load, enabling dynamic content retrieval. XMLHttpRequest forms the technological foundation of Ajax programming paradigms. Prior to its widespread adoption, server interaction relied primarily on traditional hyperlink navigation or HTML form submissions, which typically mandated a complete page reload.

See Also

`