How to Connect Claude Desktop & Cursor to PostgreSQL Safely (Read-Only AST Validation & PII Masking with MCP)

Giving large language models access to a live database is one of the most useful capabilities in modern developer tooling. When an assistant in Claude Desktop or Cursor can inspect tables, check foreign keys, and run analytical queries, debugging schema issues and writing migrations becomes noticeably faster. At the same time, direct database access introduces severe operational risks. If you connect an AI agent to PostgreSQL with standard read-write credentials or an unconstrained server, three major failure modes frequently occur in production environments: Destructive mutations from prompt drift or hallucinated queries: An agent instructed to "clean up test records" or "fix this schema discrepancy" can execute DROP TABLE, TRUNCATE, or unindexed DELETE queries. Unbounded full-table scans that choke IOPS: An innocent query like SELECT * FROM audit_logs without a LIMIT clause on a table with tens of millions of rows can saturate database CPU and exhaust server memory. PII and con

How to Connect Claude Desktop & Cursor to PostgreSQL Safely (Read-Only AST Validation & PII Masking with MCP)

Giving large language models access to a live database is one of the most useful capabilities in modern developer tooling. When an assistant in Claude Desktop or Cursor can inspect tables, check foreign keys, and run analytical queries, debugging schema issues and writing migrations becomes noticeably faster.

At the same time, direct database access introduces severe operational risks. If you connect an AI agent to PostgreSQL with standard read-write credentials or an unconstrained server, three major failure modes frequently occur in production environments:

  1. Destructive mutations from prompt drift or hallucinated queries: An agent instructed to "clean up test records" or "fix this schema discrepancy" can execute DROP TABLE, TRUNCATE, or unindexed DELETE queries.
  2. Unbounded full-table scans that choke IOPS: An innocent query like SELECT * FROM audit_logs without a LIMIT clause on a table with tens of millions of rows can saturate database CPU and exhaust server memory.
  3. PII and confidential data leakage into model contexts: Returning raw customer records (email addresses, phone numbers, password hashes, auth tokens) sends private data directly to external LLM providers and provider logs.

To address these vulnerabilities, this guide demonstrates how to configure zero-trust database access using PgSafe MCP, an open-source Model Context Protocol server featuring AST parsing, EXPLAIN cost ceilings, and automatic PII redaction.

Layer 1: Enforcing Read-Only Safety via SQL AST Parsing

Setting a database user to read-only permissions (GRANT SELECT) is an important baseline, but it is rarely sufficient on its own. Database users often retain execution privileges on stored procedures, or developers connect using staging credentials with elevated rights.

PgSafe MCP intercepts every incoming query and parses it into an Abstract Syntax Tree (AST) using Python's sqlglot before anything touches the wire. If a query contains any of the following statements, execution is terminated immediately before reaching the database engine:

  • DDL statements: DROP, ALTER, CREATE, RENAME
  • DML mutations: INSERT, UPDATE, DELETE, TRUNCATE
  • Administrative calls: VACUUM, REINDEX, GRANT, REVOKE

Only pure SELECT and EXPLAIN query trees are permitted. Multiple statements chained with semicolons (such as SELECT 1; DROP TABLE users;) are parsed statement by statement; if any node fails the AST inspection, the entire batch is rejected.

Layer 2: Preventing Runaway Queries with Cost Analysis

Even when queries are strictly read-only, complex joins and missing indexes can degrade production performance.

PgSafe MCP runs an automated EXPLAIN (FORMAT JSON) pass prior to executing the user query. The query planner cost is compared against a configurable ceiling (default: 50,000 cost units). If an agent attempts to execute an unindexed Cartesian product or a sequential scan on a massive table, PgSafe halts execution and provides a structured error message to the model:

Query rejected: Estimated plan cost (482190.50) exceeds maximum allowable ceiling (50000.00).
Suggestion: Add a WHERE clause on indexed columns or specify an explicit LIMIT.

This feedback allows the LLM to understand why the query was blocked and self-correct by adding appropriate filters and index constraints.

Layer 3: Dynamic PII and Sensitive Data Redaction

When analytical queries return records, PgSafe inspects both the column names and the cell values against regex masking patterns. Common identifiers are sanitized on the fly before returning the payload to Claude Desktop or Cursor:

  • Email addresses: [email protected] becomes j***[email protected]
  • Phone numbers and credit card patterns: redacted to masked digits (***-****-1234)
  • Columns matching sensitive nomenclature (password_hash, api_key, secret, ssn): values replaced with [REDACTED_SECRET]

Your assistant receives the necessary structural and relational context without ingesting raw personal information.

Step-by-Step Configuration

Because PgSafe MCP is packaged as a standard Python distribution, you do not need to clone the repository or manually manage virtual environments. You can run it ephemerally with uvx.

1. Claude Desktop Setup

Open your configuration file at ~/.config/Claude/claude_desktop_config.json (macOS/Linux) or %APPDATA%/Claude/claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "pgsafe-mcp": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/johannschiffer/pgsafe-mcp",
        "pgsafe-mcp"
      ],
      "env": {
        "PG_HOST": "localhost",
        "PG_PORT": "5432",
        "PG_DATABASE": "production_read_replica",
        "PG_USER": "readonly_analyst",
        "PG_PASSWORD": "your_secure_password"
      }
    }
  }
}

2. Cursor Setup

In your project root, add or update .cursor/mcp.json:

{
  "mcpServers": {
    "pgsafe-mcp": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/johannschiffer/pgsafe-mcp",
        "pgsafe-mcp"
      ],
      "env": {
        "PG_HOST": "127.0.0.1",
        "PG_PORT": "5432",
        "PG_DATABASE": "app_db",
        "PG_USER": "readonly_analyst",
        "PG_PASSWORD": "your_secure_password"
      }
    }
  }
}

Restart Claude Desktop or reload the Cursor window. You will see pgsafe-mcp registered under your active tools, exposing list_tables, describe_table, and execute_safe_query.

Interactive Generator & Ecosystem Resources

If you want to configure your database connection strings, generate unified configuration files, or build matching .cursorrules for your stack:

  • Interactive Setup Guide: Read the complete walkthrough on our PostgreSQL MCP Setup Guide.
  • Live MCP Config Builder: Customize and copy client configurations instantly at https://johannschiffer.github.io/.
  • Genesis Starter Kit (Free / $0+): Download 25+ curated .cursorrules and client configuration templates on Gumroad.
  • Genesis Enterprise Suite ($19 USD): For production engineering teams needing zero-downtime database migration verification and enterprise security middleware, explore the full bundle on Gumroad.

The code for PgSafe is open-source under the MIT license on GitHub. If you find it helpful for securing your AI development workflow, stars and contributions are welcome.

Share