Sponsored by Deepsite.site

MCP Server for PostgreSQL

Created By
JaviMalignoa month ago
MCP server with 14 tools for PostgreSQL database operations. Query databases, explore schemas, analyze tables, list indexes/constraints, and get performance statistics. Features security-first design with SQL injection prevention and read-only mode by default. Works with Claude Desktop, Claude Code, and any MCP-compatible client.
Content

PostgreSQL MCP Server

CI PyPI version Python 3.10+ License: MIT

MCP server for PostgreSQL database operations. Works with Claude Code, Claude Desktop, and any MCP-compatible client.

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
  • MCP Prompts: Guided workflows for exploration, query building, and documentation
  • MCP Resources: Browsable database structure as markdown

Quick Start

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

Available Tools (14 total)

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

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.

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 Pydantic's SecretStr
  • Credentials never appear in logs or error messages

Query Limits

  • Results limited by MAX_ROWS (default: 1000)
  • Query timeout configurable via QUERY_TIMEOUT

Installation Options

pipx install postgresql-mcp
# or
pip install postgresql-mcp

From Source

git clone https://github.com/JaviMaligno/postgres_mcp.git
cd postgres_mcp
uv sync

Configuration

claude mcp add postgres -s user \
  -e POSTGRES_HOST=localhost \
  -e POSTGRES_PORT=5432 \
  -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": "postgresql-mcp",
      "env": {
        "POSTGRES_HOST": "localhost",
        "POSTGRES_PORT": "5432",
        "POSTGRES_USER": "your_user",
        "POSTGRES_PASSWORD": "your_password",
        "POSTGRES_DB": "your_database"
      }
    }
  }
}

Environment Variables

VariableRequiredDefaultDescription
POSTGRES_HOSTYeslocalhostDatabase host
POSTGRES_PORTNo5432Database port
POSTGRES_USERYespostgresDatabase user
POSTGRES_PASSWORDYes-Database password
POSTGRES_DBYespostgresDatabase name
POSTGRES_SSLMODENopreferSSL mode
ALLOW_WRITE_OPERATIONSNofalseEnable write operations
QUERY_TIMEOUTNo30Query timeout (seconds)
MAX_ROWSNo1000Maximum rows returned

Development

Requirements

  • Python 3.10+
  • uv for dependency management
  • PostgreSQL for integration tests

Setup

git clone https://github.com/JaviMaligno/postgres_mcp.git
cd postgres_mcp
uv sync

Running Tests

# Unit tests (no database required)
uv run pytest tests/test_security.py tests/test_settings.py tests/test_models.py tests/test_utils.py -v

# Integration tests (requires PostgreSQL)
docker-compose up -d
export POSTGRES_HOST=localhost POSTGRES_PORT=5433 POSTGRES_USER=testuser POSTGRES_PASSWORD=testpass POSTGRES_DB=testdb
uv run pytest tests/test_integration.py -v

# All tests
docker-compose up -d && uv run pytest -v

# All tests (requires PostgreSQL)
uv run pytest -v --cov=postgres_mcp

CI/CD Pipeline

The project uses GitHub Actions:

  • Every push to main: Runs tests on Python 3.10, 3.11, 3.12
  • Pull requests: Full test suite
  • Tags (v*): Tests, builds, and publishes to PyPI

To release a new version:

# 1. Update version in postgres_mcp/__version__.py
# 2. Commit and push
git add -A && git commit -m "release: v0.2.0"
git push origin main

# 3. Create and push tag (triggers PyPI publish)
git tag v0.2.0
git push origin v0.2.0

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

License

MIT

Server Config

{
  "mcpServers": {
    "postgres": {
      "command": "postgresql-mcp",
      "env": {
        "POSTGRES_HOST": "localhost",
        "POSTGRES_PORT": "5432",
        "POSTGRES_USER": "your-user",
        "POSTGRES_PASSWORD": "your-password",
        "POSTGRES_DB": "your-database"
      }
    }
  }
}
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
DeepChatYour AI Partner on Desktop
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Y GuiA web-based graphical interface for AI chat interactions with support for multiple AI models and MCP (Model Context Protocol) servers.
CursorThe AI Code Editor
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
WindsurfThe new purpose-built IDE to harness magic
Amap Maps高德地图官方 MCP Server
Serper MCP ServerA Serper MCP Server
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Tavily Mcp
Playwright McpPlaywright MCP server
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
ChatWiseThe second fastest AI chatbot™