MCPg is a production-grade Model Context Protocol (MCP) server for PostgreSQL, designed to enable AI agents to safely inspect, query, operate, and tune Postgres databases. It provides approximately 279 tools, covering a wide range of scenarios including catalog introspection, query intelligence, natural language to SQL, schema diffing, hybrid search, graph queries, data migration, and real-time operations.
Purpose
The core purpose of MCPg is to serve as a secure bridge between AI agents and PostgreSQL databases. It enables agents to access databases in a controlled manner and perform tasks ranging from everyday queries to DBA-level operations without switching between different tools. It is suitable for scenarios that require AI-assisted database management, query optimization, data exploration, and operational monitoring.
Main Capabilities
Catalog Introspection: Supports inspection of objects such as schemas, tables, columns, indexes, constraints, views, functions, triggers, sequences, partitions, policies, roles, grants, enums, domains, composite types, foreign data wrappers, publications, subscriptions, extensions, generated columns, and more.
Query Intelligence: Provides tools such as run_select, run_select_parallel, explain_query, analyze_query_plan, why_is_this_slow, recommend_indexes, analyze_workload, check_database_health, detect_n_plus_one, audit_database, and more.
Search: Supports fuzzy_search (trigram), full_text_search, vector_search, hybrid_search (pgvector + FTS via RRF), geo_search (PostGIS k-NN).
Natural Language to SQL: translate_nl_to_sql supports 22 built-in providers (Anthropic, OpenAI, Gemini, xAI, Groq, Mistral, Hugging Face, etc.), as well as any custom OpenAI-compatible endpoint; the output goes through the same secure SQL kernel as handwritten queries.
Visualization: generate_schema_diagram (ER diagram), generate_fk_cascade_graph (ON DELETE CASCADE impact scope), generate_graph_diagram (Apache AGE property graph).
Schema Diffing and Migration: compare_schemas, validate_migration, and the staged prepare_migration / complete_migration / cancel_migration workflow.
Apache AGE Graphs and Cypher: list_graphs, describe_graph, run_cypher, create_graph, drop_graph, generate_graph_diagram.
Composite and Advisor Tools: summarize_table, find_unused_objects, find_sensitive_columns (PII heuristics), lint_naming_conventions, test_rls_for_role, list_locks, find_blocking_chains, read_pg_stat_io (PG16+), generate_test_data.
Real-Time Operations and Maintenance: list_active_queries, verify_connection_encryption (TLS status of live connections), run_maintenance (VACUUM/ANALYZE), prune_audit_events (audit retention), cancel_query, terminate_backend, run_write, run_ddl, enable_extension.
Data Migration: export_query / export_table (CSV/JSON), dump_database / restore_database, import_csv / import_json (COPY FROM STDIN), copy_table_between_databases.
Server-Side Cursors: open_cursor, fetch_cursor, close_cursor, list_cursors, for paginated reads over millions of rows.
TimescaleDB: introspection and statistics for hypertables / chunks / jobs / continuous aggregates, policy and dimension management, and controlled chunk / job management (drop_chunks, compress_chunk, refresh_continuous_aggregate, run_job, etc.).
ORM schema exporters: Prisma, Drizzle, SQLAlchemy, sqlc, Diesel, jOOQ, Ent, Ecto.
Event streaming: subscribe_channel, poll_notifications, unsubscribe_channel, list_notification_subscriptions, bridging PostgreSQL LISTEN/NOTIFY to the MCP polling model.
Observability: Prometheus /metrics endpoint + get_metrics_exposition tool for stdio; structured audit trail with regex credential redaction.
Usage
Installation: Installing from PyPI is recommended; you can also pull a prebuilt image from the GitHub Container Registry (:latest tracks the latest version, or pin a version such as :0.6.5); or build from source (multi-stage image, with the runtime stage running as uid=10001 / gid=10001 and application files read-only). Developers can use uv sync to create a virtual environment and expose the mcpg console script.
One-click install for Claude Desktop: Download the latest released mcpg-<version>.mcpb and double-click it (or drag it into Claude Desktop's Settings → Extensions), then follow the prompts to enter the PostgreSQL connection URL (stored in the OS keychain) and access mode (read-only by default).
Manual configuration (stdio transport): Write the configuration into claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/claude_desktop_config.json; Windows: %APPDATA%\Claude\claude_desktop_config.json), restart Claude Desktop, and it is ready to use.
HTTP server mode: After running, you can point any MCP-aware client to http://localhost:8000/mcp(或 /sse for SSE transport). The HTTP transport refuses to start without authentication by default, so you need to set MCPG_HTTP_AUTH_TOKEN=... or MCPG_AUTH_MODE=oidc; if you need to run without authentication (not recommended), set MCPG_HTTP_ALLOW_UNAUTHENTICATED=true.
Configuration: Configured entirely through environment variables, with no configuration file and no flags. The only required one is MCPG_DATABASE_URL; all others have safe defaults.
Demo data: A single command can seed a small curated e-commerce dataset (3,000 orders, 900 product reviews, with deliberately planted defects) into the mcpg_demo schema, making it easy to try features such as the index advisor, query plan analysis, full-text search, PII audit, and graph projection for the first time; you can remove it at any time with mcpg --demo-drop.
Online demo: You can point an MCP client or MCP Inspector to the hosted read-only demo endpoint https://devopam-mcpg-demo.hf.space/mcp,针对一次性演示数据提供读取工具。
Use Cases
- Let AI agents inspect database schemas, diagnose slow queries, and recommend indexes.
- Translate natural language questions into SQL and execute them safely.
- Generate ER diagrams, foreign key cascade impact diagrams, and property graphs.
- Audit database health, detect PII columns, and test RLS.
- Perform controlled writes, DDL, and maintenance operations.
- Export/import data, database dumps and restores, and cross-database table replication.
- Perform integration operations for extensions such as TimescaleDB, pgvector, PostGIS, and Apache AGE.
- Read massive amounts of data with pagination via server-side cursors.
- Bridge PostgreSQL LISTEN/NOTIFY events to the MCP polling model.
Limitations
- Read-only access mode by default; capabilities such as DDL, shell, and LISTEN/NOTIFY must be explicitly enabled.
- All user-submitted SQL statements must be parsed through a validated AST allowlist before execution.
- HTTP transport rejects unauthenticated startup by default.
- MCPg is self-hosted: database contents do not leave your infrastructure, with no telemetry or callbacks. The only exception is the optionally enabled translate_nl_to_sql tool, which sends your question and schema context (names, not row data) to your configured LLM provider.
- Test coverage: 2,500+ unit tests, with the integration suite running against real PostgreSQL containers in CI, with a matrix covering PG 14, 15, 16, 17, and 18, and PG 19 (beta) as an experimental non-blocking entry.
- Vulnerability reports use a 90-day coordinated disclosure window.