Skip to main content

MCP server for PostgreSQL database operations

Project description

PostgreSQL MCP Server

A Model Context Protocol (MCP) server for PostgreSQL database operations. Provides AI assistants with standardized CRUD operations and database management capabilities.

Status: ✅ COMPLETED - Fully implemented, tested, and published to PyPI

Features

  • CRUD Operations: Create, read, update, and delete entities
  • Dynamic Table Support: Work with any table without pre-configuration
  • Secure Connections: Environment variable-based configuration with validation
  • Parameterized Queries: SQL injection protection
  • Table Management: Create, alter, and drop tables
  • Schema Information: Detailed table schemas and database metadata
  • Comprehensive Testing: Unit, integration, and Docker tests

Available Tools

CRUD Operations

  • create_entity: Insert new rows into tables
  • read_entity: Query tables with optional conditions
  • update_entity: Update existing rows based on conditions
  • delete_entity: Remove rows from tables

Table Management Operations

  • create_table: Create new tables with specified schema
  • alter_table: Modify existing table structures
  • drop_table: Remove tables from database

Schema Operations

  • get_tables: Get list of all tables in the database
  • get_table_schema: Get detailed schema information for a specific table
  • get_database_info: Get database metadata and version information

Available Resources

Database Resources

  • database://tables: List of all tables in the database
  • database://info: Database metadata and version information
  • database://connection: Database connection parameters (host, port, database, username, password, etc.)
  • database://schema/{table_name}: Schema information for specific tables

Quick Start

Prerequisites

  • Python 3.10 or higher
  • PostgreSQL database (version 12 or higher)
  • uv package manager (latest version)

Installation

  1. Configure your MCP client (e.g., Claude Desktop): Add the server configuration to your MCP client settings using uvx:

    Claude Desktop Configuration Example:

    {
      "mcpServers": {
        "postgres-mcp": {
          "command": "uvx",
          "args": ["mcp-postgres-duwenji"],
          "env": {
            "POSTGRES_HOST": "localhost",
            "POSTGRES_PORT": "5432",
            "POSTGRES_DB": "your_database",
            "POSTGRES_USER": "your_username",
            "POSTGRES_PASSWORD": "your_password",
            "POSTGRES_SSL_MODE": "prefer",
            "MCP_LOG_LEVEL": "INFO",
            "MCP_DEBUG": "true",
            "MCP_LOG_DIR": "C:\\Logs\\mcp-postgres"
          }
        }
      }
    }
    

    Docker Automatic Setup Configuration:

    For automatic PostgreSQL Docker container setup, use the following configuration:

    {
      "mcpServers": {
        "postgres-mcp": {
          "disabled": false,
          "timeout": 60,
          "type": "stdio",
          "command": "uvx",
          "args": ["mcp-postgres-duwenji"],
          "env": {
            "MCP_DOCKER_AUTO_SETUP": "true",
            "MCP_DOCKER_IMAGE": "postgres:16",
            "MCP_DOCKER_CONTAINER_NAME": "mcp-postgres-auto",
            "MCP_DOCKER_PORT": "5432",
            "MCP_DOCKER_DATA_VOLUME": "mcp_postgres_data",
            "MCP_DOCKER_PASSWORD": "postgres",
            "MCP_DOCKER_DATABASE": "mcp-postgres-db",
            "MCP_DOCKER_USERNAME": "postgres",
            "MCP_DOCKER_MAX_WAIT_TIME": "30",
            "MCP_LOG_LEVEL": "INFO",
            "MCP_DEBUG": "true",
            "MCP_LOG_DIR": "C:\\Logs\\mcp-postgres"
          }
        }
      }
    }
    

    This configuration will automatically:

    • Start a PostgreSQL Docker container when the MCP server starts
    • Use the specified Docker image (postgres:16)
    • Create a persistent data volume for data storage
    • Set up the database with the specified credentials
    • Enable external access (listen on all interfaces)
    • Enable debug logging for troubleshooting

    For detailed Docker setup instructions, see Docker Auto Setup Guide.

External Program Access

When using Docker auto-setup, the PostgreSQL container is configured to allow external connections:

  • Listen address: * (all interfaces)
  • Port: Configurable via MCP_DOCKER_PORT (default: 5432)
  • Authentication: Password-based authentication

External Python programs can use the connection information from the database://connection resource to connect directly to the PostgreSQL database.

Configuration

Environment Variables

The PostgreSQL MCP Server supports the following environment variables for configuration:

Database Connection Variables

  • POSTGRES_HOST: PostgreSQL server hostname (default: localhost)
  • POSTGRES_PORT: PostgreSQL server port (default: 5432)
  • POSTGRES_DB: Database name (required)
  • POSTGRES_USER: Database username (required)
  • POSTGRES_PASSWORD: Database password (required)
  • POSTGRES_SSL_MODE: SSL mode (default: prefer)

Docker Auto-Setup Variables

  • MCP_DOCKER_AUTO_SETUP: Enable automatic Docker setup (true/false, default: false)
  • MCP_DOCKER_IMAGE: PostgreSQL Docker image (default: postgres:16)
  • MCP_DOCKER_CONTAINER_NAME: Docker container name (default: mcp-postgres-auto)
  • MCP_DOCKER_PORT: Docker container port (default: 5432)
  • MCP_DOCKER_DATA_VOLUME: Data volume name (default: mcp_postgres_data)
  • MCP_DOCKER_PASSWORD: Database password for Docker setup (default: postgres)
  • MCP_DOCKER_DATABASE: Database name for Docker setup (default: mcp-postgres-db)
  • MCP_DOCKER_USERNAME: Database username for Docker setup (default: postgres)
  • MCP_DOCKER_MAX_WAIT_TIME: Maximum wait time for container startup in seconds (default: 30)

Logging and Debug Variables

  • MCP_LOG_LEVEL: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL, default: INFO)
  • MCP_DEBUG: Enable debug mode (true/false, default: false)

Environment Variable Usage Examples

Using .env File

Create a .env file in your project directory:

# Database Connection
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=my_database
POSTGRES_USER=my_username
POSTGRES_PASSWORD=my_password
POSTGRES_SSL_MODE=prefer

# Docker Auto-Setup
MCP_DOCKER_AUTO_SETUP=false
MCP_DOCKER_IMAGE=postgres:16
MCP_DOCKER_CONTAINER_NAME=mcp-postgres-auto
MCP_DOCKER_PORT=5432
MCP_DOCKER_DATA_VOLUME=mcp_postgres_data
MCP_DOCKER_PASSWORD=postgres
MCP_DOCKER_DATABASE=mcp-postgres-db
MCP_DOCKER_USERNAME=postgres
MCP_DOCKER_MAX_WAIT_TIME=30

# Logging
MCP_LOG_LEVEL=INFO
MCP_DEBUG=false

Using System Environment Variables

Set environment variables directly in your shell:

# Windows PowerShell
$env:POSTGRES_HOST="localhost"
$env:POSTGRES_DB="my_database"
$env:POSTGRES_USER="my_username"
$env:POSTGRES_PASSWORD="my_password"

# Linux/macOS
export POSTGRES_HOST=localhost
export POSTGRES_DB=my_database
export POSTGRES_USER=my_username
export POSTGRES_PASSWORD=my_password

Usage Examples

Once configured, you can use the MCP tools through your AI assistant:

Create a new user:

{
  "table_name": "users",
  "data": {
    "name": "John Doe",
    "email": "john@example.com",
    "age": 30
  }
}

Read users with conditions:

{
  "table_name": "users",
  "conditions": {
    "age": 30
  },
  "limit": 10
}

Update user information:

{
  "table_name": "users",
  "conditions": {
    "id": 1
  },
  "updates": {
    "email": "newemail@example.com"
  }
}

Delete users:

{
  "table_name": "users",
  "conditions": {
    "id": 1
  }
}

Development

Project Structure

mcp-postgres/
├── src/mcp_postgres_duwenji/     # Main package
├── test/                         # Testing
├── docs/                         # Documentation
├── scripts/                      # Utility scripts
├── memory-bank/                  # Project memory bank
├── pyproject.toml                # Project configuration
└── README.md                     # English README

Running the Server

To run the server directly for testing:

uvx mcp-postgres-duwenji

Direct Execution with Environment Variables:

You can also run the server directly with environment variables:

# Using .env file
uvx mcp-postgres-duwenji

# Using command-line environment variables (Linux/macOS)
POSTGRES_HOST=localhost POSTGRES_DB=my_database POSTGRES_USER=my_username POSTGRES_PASSWORD=my_password uvx mcp-postgres-duwenji

# Using command-line environment variables (Windows PowerShell)
$env:POSTGRES_HOST="localhost"; $env:POSTGRES_DB="my_database"; $env:POSTGRES_USER="my_username"; $env:POSTGRES_PASSWORD="my_password"; uvx mcp-postgres-duwenji

Code Quality Tools

This project uses comprehensive code quality tools:

  • Black: Code formatting
  • Flake8: Linting and style checking
  • MyPy: Static type checking
  • Bandit: Security scanning

See docs/code-quality-checks-guide.md and docs/linting-and-type-checking-guide.md for detailed usage instructions.

Adding New Tools

  1. Create a new tool definition in src/mcp_postgres_duwenji/tools/
  2. Add the tool handler function
  3. Register the tool in the appropriate handler function
  4. The tool will be automatically available through the MCP interface

Security Considerations

  • Always use environment variables for sensitive connection information
  • The server uses parameterized queries to prevent SQL injection
  • Limit database user permissions to only necessary operations
  • Consider using SSL/TLS for database connections in production

License

Apache 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mcp_postgres_duwenji-1.2.14.tar.gz (31.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcp_postgres_duwenji-1.2.14-py3-none-any.whl (39.9 kB view details)

Uploaded Python 3

File details

Details for the file mcp_postgres_duwenji-1.2.14.tar.gz.

File metadata

  • Download URL: mcp_postgres_duwenji-1.2.14.tar.gz
  • Upload date:
  • Size: 31.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for mcp_postgres_duwenji-1.2.14.tar.gz
Algorithm Hash digest
SHA256 6fc20d36061e44a723c10989b776157a1aeb0910255759641ca8a14e6a2843e5
MD5 53d5b6f8290b2603f56698a7b515c7a6
BLAKE2b-256 7b481c3115dce3c2cc35ed8873fe70b183184b08c8f7d152d3efb40492991f16

See more details on using hashes here.

Provenance

The following attestation bundles were made for mcp_postgres_duwenji-1.2.14.tar.gz:

Publisher: publish.yml on duwenji/mcp-postgres

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file mcp_postgres_duwenji-1.2.14-py3-none-any.whl.

File metadata

File hashes

Hashes for mcp_postgres_duwenji-1.2.14-py3-none-any.whl
Algorithm Hash digest
SHA256 aae4777b953dca7fb0fc5628313c1759e3cd8c6053257b0e458c0831d6ca4d72
MD5 f7ac2e92149c0b7a9e54743c8a35ef1a
BLAKE2b-256 16c033b6f89cce2d5be204f59793d33e9397888512fbc26e4286109897d25729

See more details on using hashes here.

Provenance

The following attestation bundles were made for mcp_postgres_duwenji-1.2.14-py3-none-any.whl:

Publisher: publish.yml on duwenji/mcp-postgres

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page