MCP-PostgreSQL-Ops
Copilot instructions160 starsChanged 15 months agoMITView on GitHub
This is a Model Context Protocol (MCP) server built with FastMCP that provides PostgreSQL database monitoring and operations through natural language queries. The server acts as a safe, read-only bridge between AI assistants and PostgreSQL databases. Multi-Database Architecture: All tools accept optional database_name parameter to target specific databases while maintaining a default connection database from POSTGRES_DB env var. Extension Dependencies: Core functionality requires pg_stat_statements extension; pg_stat_monitor is optional. Always check extension availability with check_extension_exists() before using related tools. Version-Aware Tools:…
- Reads credentials
The file
Show its rules and text
We split this copilot-instructions.md into the rules it gives an agent
16 rules. About 0 are common, 6 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 16
Multi-Database Architecture: All tools accept optional database_name parameter to target specific databases while maintaining a default …
- Very specific: line 20
Version-Aware Tools: Use version_compat.py for PostgreSQL 12-17 compatibility.
- Very specific: line 71
Use host.docker.internal for POSTGRES_HOST when connecting from containers to host PostgreSQL
- Very specific: line 86
All MCP tools must return str (never raise exceptions to MCP layer)
- Very specific: line 91
Use format_table_data(results, title) for consistent table output
- Distinctive: line 96
When adding new tools, must update the compatibility matrix in README.md:
- Distinctive: line 98
Document PostgreSQL version support (12-17)
- Distinctive: line 100
Update tool count statistics
- Distinctive: line 104
Comprehensive PG12 Compatibility: All tools now work on PostgreSQL 12
- Very specific: line 158
Run ./scripts/create-test-data.sh to create 4 realistic databases:
- Distinctive: line 165
Test tools with realistic prompts - never use function names directly:
- Very specific: line 177
Extension Assumptions: Always check pg_stat_statements/pg_stat_monitor availability before using performance tools
- Very specific: line 179
Environment Loading: Use scripts/run-mcp-inspector-local.sh which properly loads .env - direct Python execution won't load environment
- Distinctive: line 180
Query Limits: All tools enforce 1-100 limits for performance.
- Very specific: line 181
asyncpg Parameter Binding: Use $1, $2, ... format, not %s - all SQL queries must use asyncpg-compatible parameter binding
- Very specific: line 183
Version-Specific Features: Always use version_compat.py patterns for new tools that query system catalogs
≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
MCP PostgreSQL Operations Server - AI Coding Agent Instructions
Architecture Overview
This is a Model Context Protocol (MCP) server built with FastMCP that provides PostgreSQL database monitoring and operations through natural language queries. The server acts as a safe, read-only bridge between AI assistants and PostgreSQL databases.
Core Components
mcp_main.py: Main MCP server with 24+@mcp.tool()decorated functionsfunctions.py: Database connection layer usingasyncpgwith multi-database supportversion_compat.py: PostgreSQL 12-17 version detection and adaptive feature handlingprompt_template.md: Comprehensive prompt definitions loaded via@mcp.prompt()decorators- Docker stack: PostgreSQL + MCP server + MCPO proxy + Open WebUI integration
Key Patterns
Multi-Database Architecture: All tools accept optional database_name parameter to target specific databases while maintaining a default connection database from POSTGRES_DB env var.
Extension Dependencies: Core functionality requires pg_stat_statements extension; pg_stat_monitor is optional. Always check extension availability with check_extension_exists() before using related tools.
Version-Aware Tools: Use version_compat.py for PostgreSQL 12-17 compatibility. Tools auto-adapt features based on detected version. PostgreSQL 18 is beta and not yet supported - will be added once stable.
Tool Structure: Each MCP tool follows this pattern:
@mcp.tool()
async def get_something(limit: int = 20, database_name: str = None) -> str:
"""Detailed docstring with [Tool Purpose], [Exact Functionality], [Required Use Cases], [Strictly Prohibited Use Cases]"""
try:
# Validate inputs (limit constraints: max 1-100)
# Check extension dependencies if needed
# Execute queries via functions.py
# Return formatted table data
except Exception as e:
logger.error(f"Failed to...: {e}")
return f"Error: {str(e)}"Version Compatibility Pattern: Critical for PostgreSQL 12 support - many tools use version-aware query builders:
# In functions.py
from .version_compat import get_pg_stat_statements_query
async def get_pg_stat_statements_data(limit: int = 20, database: str = None):
base_query = await get_pg_stat_statements_query(database) # Auto-adapts for PG12/13+
query = f"{base_query} LIMIT $1"
return await execute_query(query, [limit], database=database)Development Workflows
Local Development
# Primary development command - loads .env, starts MCP Inspector
./scripts/run-mcp-inspector-local.sh
# Direct execution for debugging with custom log levels
python -m src.mcp_postgresql_ops.mcp_main --log-level DEBUG --type streamable-httpDocker Development
# Full stack with PostgreSQL + test data
docker-compose up -d
# Test data generation (creates 4 databases with 83k+ records)
./scripts/create-test-data.shEnvironment Configuration
- Copy
.env.exampleto.envand modify connection parameters - Critical:
POSTGRES_DBserves dual purpose - default connection target AND Docker database creation name - Use
host.docker.internalforPOSTGRES_HOSTwhen connecting from containers to host PostgreSQL
Code Conventions
Database Connection Pattern
# Multi-database support - database parameter overrides POSTGRES_CONFIG default
async def get_db_connection(database: str = None) -> asyncpg.Connection:
config = POSTGRES_CONFIG.copy()
if database:
config["database"] = database # Override default
return await asyncpg.connect(**config)Error Handling
- All MCP tools must return
str(never raise exceptions to MCP layer) - Log errors with
logger.error()then return user-friendly error messages - Mask sensitive information in connection info with
sanitize_connection_info()
Query Formatting
- Use
format_table_data(results, title)for consistent table output - Apply
format_bytes()andformat_duration()for human-readable values - Enforce limit constraints:
limit = max(1, min(limit, 100))
Tool Compatibility Matrix
When adding new tools, must update the compatibility matrix in README.md:
- Classify as Extension-Independent, Version-Aware, or Extension-Dependent
- Document PostgreSQL version support (12-17)
- List system views/tables used
- Update tool count statistics
Recent Major Changes
- PostgreSQL 18 Support Removed: Now supports 12-17 range (18 is beta)
- Comprehensive PG12 Compatibility: All tools now work on PostgreSQL 12
- Version-Aware Query Generation: Automatic column mapping and NULL handling
- Enhanced Schema Analysis: New tools for table relationships and schema introspection
Project-Specific Integrations
Prompt Template System
The server loads prompts from prompt_template.md using a custom parsing system:
@mcp.prompt("prompt_template_full")- complete template@mcp.prompt("prompt_template_headings")- section list onlyget_prompt_template(section="specific_section")- targeted content
Docker Multi-Service Architecture
- postgres: Percona PostgreSQL (version from
PGSQL_VERSIONenv var, default 13) - postgres-init-extensions: One-shot container that installs extensions and creates comprehensive test data
- mcp-server: Main MCP server container
- mcpo-proxy: HTTP proxy for web-based MCP clients
- open-webui: Web interface for testing
Critical Dependencies
# Required for all database operations
import asyncpg # Not psycopg2 - uses asyncpg exclusively
# MCP framework
from fastmcp import FastMCP
# Extension checks are mandatory for performance tools
await check_extension_exists("pg_stat_statements")PostgreSQL 12 Compatibility Patterns
The major recent work focused on PostgreSQL 12 compatibility. Key patterns:
Column Mapping for pg_stat_statements/pg_stat_monitor: PostgreSQL 12 uses total_time/mean_time while 13+ uses total_exec_time/mean_exec_time. Version-aware queries handle this:
# In version_compat.py
if version.has_pg_stat_statements_exec_time: # PG13+
base_columns.extend(["total_exec_time", "mean_exec_time"])
else: # PG12
base_columns.extend(["total_time as total_exec_time", "mean_time as mean_exec_time"])NULL Column Handling: Many PG13+ columns don't exist in PG12 (e.g., wal_status, n_ins_since_vacuum). Use NULL placeholders:
if version.has_replication_slot_wal_status:
base_columns.append("wal_status")
else:
base_columns.append("NULL as wal_status")Testing Strategy
Test Data Generation
- Run
./scripts/create-test-data.shto create 4 realistic databases:ecommerce: E-commerce with products, orders, customers (~9k records)analytics: Web analytics and sales data (~59k records)inventory: Warehouse management (~3k records)hr_system: Employee and payroll data (~12k records)
Natural Language Testing
Test tools with realistic prompts - never use function names directly:
- ✅ "Show me the slowest queries"
- ❌ "Run get_pg_stat_statements_top_queries"
Configuration Files
mcp-config.json.stdio: Standard CLI integrationmcp-config.json.http: HTTP mode for web clients- Both must have matching port configurations with
docker-compose.yml
Common Pitfalls
- Database Parameter Confusion:
POSTGRES_DBis the default connection database, not a constraint on which databases can be accessed - Extension Assumptions: Always check
pg_stat_statements/pg_stat_monitoravailability before using performance tools - Port Misalignment:
FASTMCP_PORT, Docker external port, and MCP config files must all match - Environment Loading: Use
scripts/run-mcp-inspector-local.shwhich properly loads.env- direct Python execution won't load environment - Query Limits: All tools enforce 1-100 limits for performance; don't assume unlimited results
- asyncpg Parameter Binding: Use
$1, $2, ...format, not%s- all SQL queries must use asyncpg-compatible parameter binding - PostgreSQL Version Support: Currently supports 12-17; PostgreSQL 18 support pending stable release
- Version-Specific Features: Always use
version_compat.pypatterns for new tools that query system catalogs
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

