Cover image
Try Now
2025-04-08

3 years

Works with Finder

5

Github Watches

10

Github Forks

431

Github Stars

PostgreSQL Model Context Protocol (PG-MCP) Server

A Model Context Protocol (MCP) server for PostgreSQL databases with enhanced capabilities for AI agents.

More info on the pg-mcp project here:

https://stuzero.github.io/pg-mcp/

Overview

PG-MCP is a server implementation of the Model Context Protocol for PostgreSQL databases. It provides a comprehensive API for AI agents to discover, connect to, query, and understand PostgreSQL databases through MCP's resource-oriented architecture.

This implementation builds upon and extends the reference Postgres MCP implementation with several key enhancements:

  1. Full Server Implementation: Built as a complete server with SSE transport for production use
  2. Multi-database Support: Connect to multiple PostgreSQL databases simultaneously
  3. Rich Catalog Information: Extracts and exposes table/column descriptions from the database catalog
  4. Extension Context: Provides detailed YAML-based knowledge about PostgreSQL extensions like PostGIS and pgvector
  5. Query Explanation: Includes a dedicated tool for analyzing query execution plans
  6. Robust Connection Management: Proper lifecycle for database connections with secure connection ID handling

Features

Connection Management

  • Connect Tool: Register PostgreSQL connection strings and get a secure connection ID
  • Disconnect Tool: Explicitly close database connections when done
  • Connection Pooling: Efficient connection management with pooling

Query Tools

  • pg_query: Execute read-only SQL queries using a connection ID
  • pg_explain: Analyze query execution plans in JSON format

Schema Discovery Resources

  • List schemas with descriptions
  • List tables with descriptions and row counts
  • Get column details with data types and descriptions
  • View table constraints and indexes
  • Explore database extensions

Data Access Resources

  • Sample table data (with pagination)
  • Get approximate row counts

Extension Context

Built-in contextual information for PostgreSQL extensions like:

  • PostGIS: Spatial data types, functions, and examples
  • pgvector: Vector similarity search functions and best practices

Additional extensions can be easily added via YAML config files.

Installation

Prerequisites

  • Python 3.13+
  • PostgreSQL database(s)

Using Docker

# Clone the repository
git clone https://github.com/stuzero/pg-mcp-server.git
cd pg-mcp

# Build and run with Docker Compose
docker-compose up -d

Manual Installation

# Clone the repository
git clone https://github.com/stuzero/pg-mcp-server.git
cd pg-mcp-server

# Install dependencies and create a virtual environment ( .venv )
uv sync

# Activate the virtual environment
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Run the server
python -m server.app

Usage

Testing the Server

The repository includes test scripts to verify server functionality:

# Basic server functionality test
python test.py "postgresql://username:password@hostname:port/database"

# Claude-powered natural language to SQL conversion
python example-clients/claude_cli.py "Show me the top 5 customers by total sales"

The claude_cli.py script requires environment variables:

# .env file
DATABASE_URL=postgresql://username:password@hostname:port/database
ANTHROPIC_API_KEY=your-anthropic-api-key
PG_MCP_URL=http://localhost:8000/sse

For AI Agents

Example prompt for use with agents:

Use the PostgreSQL MCP server to analyze the database. 
Available tools:
- connect: Register a database connection string and get a connection ID
- disconnect: Close a database connection
- pg_query: Execute SQL queries using a connection ID
- pg_explain: Get query execution plans

You can explore schema resources via:
pgmcp://{conn_id}/schemas
pgmcp://{conn_id}/schemas/{schema}/tables
pgmcp://{conn_id}/schemas/{schema}/tables/{table}/columns

A comprehensive database description is available at this resource:
pgmcp://{conn_id}/

Architecture

This server is built on:

  • MCP: The Model Context Protocol foundation
  • FastMCP: Python library for MCP
  • asyncpg: Asynchronous PostgreSQL client
  • YAML: For extension context information

Security Considerations

  • The server runs in read-only mode by default (enforced via transaction settings)
  • Connection details are never exposed in resource URLs, only opaque connection IDs
  • Database credentials only need to be sent once during the initial connection

Contributing

Contributions are welcome! Areas for expansion:

  • Additional PostgreSQL extension context files
  • More schema introspection resources
  • Query optimization suggestions

相关推荐

  • Joshua Armstrong
  • Confidential guide on numerology and astrology, based of GG33 Public information

  • https://suefel.com
  • Latest advice and best practices for custom GPT development.

  • Emmet Halm
  • Converts Figma frames into front-end code for various mobile frameworks.

  • Elijah Ng Shi Yi
  • Advanced software engineer GPT that excels through nailing the basics.

  • https://maiplestudio.com
  • Find Exhibitors, Speakers and more

  • Alexandru Strujac
  • Efficient thumbnail creator for YouTube videos

  • Yusuf Emre Yeşilyurt
  • I find academic articles and books for research and literature reviews.

  • Carlos Ferrin
  • Encuentra películas y series en plataformas de streaming.

  • https://zenepic.net
  • Embark on a thrilling diplomatic quest across a galaxy on the brink of war. Navigate complex politics and alien cultures to forge peace and avert catastrophe in this immersive interstellar adventure.

  • https://reddgr.com
  • Delivers concise Python code and interprets non-English comments

  • apappascs
  • 发现市场上最全面,最新的MCP服务器集合。该存储库充当集中式枢纽,提供了广泛的开源和专有MCP服务器目录,并提供功能,文档链接和贡献者。

  • ShrimpingIt
  • MCP系列GPIO Expander的基于Micropython I2C的操作,源自ADAFRUIT_MCP230XX

  • pontusab
  • 光标与风浪冲浪社区,查找规则和MCP

  • av
  • 毫不费力地使用一个命令运行LLM后端,API,前端和服务。

  • 1Panel-dev
  • 🔥1Panel提供了直观的Web接口和MCP服务器,用于在Linux服务器上管理网站,文件,容器,数据库和LLMS。

  • GeyserMC
  • 与Minecraft客户端/服务器通信的库。

  • Mintplex-Labs
  • 带有内置抹布,AI代理,无代理构建器,MCP兼容性等的多合一桌面和Docker AI应用程序。

  • awslabs
  • AWS MCP服务器 - 将AWS最佳实践直接带入您的开发工作流程的专门MCP服务器

  • WangRongsheng
  • 🧑‍🚀 llm 资料总结(数据处理、模型训练、模型部署、 o1 模型、mcp 、小语言模型、视觉语言模型)|摘要世界上最好的LLM资源。

    Reviews

    1 (1)
    Avatar
    user_fu4J41QX
    2025-04-17

    I've been using pg-mcp-server for a few months now, and it has greatly simplified my workflow. Developed by stuzero, this server application is incredibly reliable and well-documented. The ease of integration and robust performance makes it stand out. Highly recommend it to anyone looking for an efficient MCP application server. Check it out on GitHub!