PostgreSQL MCP Server

PostgreSQL MCP Server

Enables AI assistants to safely interact with PostgreSQL databases through read-only operations, providing schema discovery, table inspection, and query execution capabilities with structured context awareness.

Category
Visit Server

README

PostgreSQL MCP Server Demo

Overview

This project implements a Model Context Protocol (MCP) server that provides a standardized interface for AI assistants to interact with PostgreSQL databases. MCP enables secure, structured communication between AI models and external data sources through well-defined tools, resources, and prompts.

Theoretical Foundation

Core Objectives

  1. Database Accessibility: Enable AI assistants to safely query PostgreSQL databases without direct database access
  2. Structured Interaction: Provide standardized tools for database operations through MCP protocol
  3. Security: Implement read-only operations with strict query validation to prevent data manipulation
  4. Context Awareness: Supply database schema information and context for intelligent query generation

Architecture Components

1. MCP Server Framework

  • FastMCP: Lightweight MCP server implementation providing transport layers (stdio/SSE)
  • Transport Layer: Dual transport support for local development (stdio) and network deployment (SSE via HTTP)
  • Registration System: Decorators for automatic registration of tools, resources, and prompts

2. Configuration Management

  • YAML-based Configuration: Centralized settings for database connections and server parameters
  • Environment Variables: Runtime configuration override capabilities
  • Validation Layer: Pydantic models ensuring data integrity and type safety

3. Database Abstraction

  • Connection Pooling: Async PostgreSQL connections with automatic lifecycle management
  • Query Execution Engine: Isolated read-only operations with comprehensive error handling
  • Result Serialization: Consistent data format conversion for MCP protocol compatibility

4. Component Organization

  • Tools: Executable database operations (schema listing, table inspection, query execution)
  • Resources: Static/contextual data endpoints providing database metadata
  • Prompts: Dynamic instruction templates guiding AI query generation

Implementation Description

Entry Point Architecture

The main application serves as a transport-aware launcher that initializes the MCP server with appropriate communication protocols. It supports both local development through standard I/O streams and production deployment via HTTP streaming.

Configuration System

Externalized settings management loads database credentials and server parameters from structured configuration files. The system provides fallback mechanisms and environment variable overrides for flexible deployment across different environments.

Database Connection Layer

Asynchronous connection management establishes secure PostgreSQL connections using connection pooling. The abstraction layer handles connection lifecycle, error recovery, and resource cleanup while maintaining connection isolation for concurrent operations.

MCP Tools Implementation

Six specialized tools provide comprehensive database interaction capabilities:

  • Health Monitoring: Basic connectivity verification returning server status
  • Schema Discovery: Enumerates available database schemas for navigation
  • Table Enumeration: Lists tables within specified schemas with metadata
  • Schema Inspection: Retrieves detailed column information and constraints
  • Query Execution: Safe SQL execution with forbidden operation filtering
  • Performance Analysis: Query optimization insights through EXPLAIN plan generation

Resource Management

Contextual data endpoints serve static database information and schema-specific guidance. These provide AI assistants with domain knowledge about table relationships, data types, and common query patterns without requiring direct database inspection.

Prompt Engineering

Dynamic instruction templates guide AI assistants in generating appropriate database queries. The system provides structured workflows for safe query construction, emphasizing read-only operations and performance considerations.

Testing Framework

Connection validation utilities enable developers to verify database connectivity and explore schema structures. The testing module provides diagnostic capabilities for troubleshooting deployment issues and validating configuration correctness.

Setup

  1. Install dependencies:
uv sync
  1. Configure database connection in config.yaml

  2. Install Cloudflare Tunnel (for exposing server):

# macOS
brew install cloudflared

# Or download from: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/

Running the Server

Local Development (stdio)

MCP_TRANSPORT=stdio uv run python main.py

Expose via Cloudflare Tunnel (SSE)

  1. Start the server (defaults to SSE transport):
uv run python main.py

The server will start on http://127.0.0.1:8000 by default.

  1. In another terminal, start Cloudflare tunnel:
cloudflared tunnel --url http://127.0.0.1:8000

Cloudflare will provide a public URL (e.g., https://xxxxx.trycloudflare.com) that you can use to access your MCP server.

Environment Variables

  • MCP_TRANSPORT: Transport type - sse (default) or stdio
  • MCP_HOST: Host address (default: 127.0.0.1)
  • MCP_PORT: Port number (default: 8000)

Example:

MCP_PORT=3000 MCP_HOST=0.0.0.0 uv run python main.py

Tools Available

  • ping: Health check
  • list_schemas: List all database schemas
  • list_tables: List tables in a schema
  • get_table_info: Get table schema information
  • run_sql_query: Execute read-only SQL queries
  • run_explain_query: Get query performance metrics

Resources

  • db://context: Database context information
  • db://schema/{schema_name}: Schema-specific context

Prompts

  • get_table_data_prompt: Prompt to generate queries for table data

Notes

  • The server uses main.py as the entry point
  • SSE transport is used for HTTP/network access (Cloudflare tunnel)
  • stdio transport is used for local development

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured