MCPg - Production-grade PostgreSQL MCP Server

by devopam

257 downloads
Not rated
GitHub

About

Safe-by-default PostgreSQL Model Context Protocol server for AI agents.

Details

Author
devopam
Downloads
257
Categories
Developer Tools, Other, Database, Search

- Safety-first design: read-only by default, AST validation, strict sanitization
- Broad PostgreSQL support: pgvector, TimescaleDB, PostGIS, Apache AGE
- Production ready: connection pooling, SET ROLE multi-tenancy, read-replica routing
- Prometheus metrics and structured audit logging with redaction
- Multiple transports: stdio, HTTP, SSE, Streamable HTTP
- Easy install: pip or Docker with OIDC + static auth and rate limiting

Install via pip install mcpg or Docker. Configure connection settings and choose a transport: stdio for Claude Desktop, or HTTP/SSE/Streamable HTTP. Connect any MCP client to start using the tools.

MCPg - Production-grade PostgreSQL MCP Server

Safe-by-default PostgreSQL Model Context Protocol server for AI agents.

A production-gradeModel Context Protocolserver for PostgreSQL.It lets AI agents safely inspect, query, operate, and tune a Postgres database — 254 tools spanning catalog introspection, query intelligence, natural-language SQL, structural diffs, hybrid search, graph queries, data movement, live ops, and more.

Try it live:point an MCP client — or theMCP Inspector— at the hosted, read-only demo endpointhttps://devopam-mcpg-demo.hf.space/mcp. It serves read tools against throwaway demo data; for real use, run MCPg next to your own database (seeQuick start).

- Official MCP Registry
-
mcp.so
-
mcpservers.org
-
Smithery
-
Glama

- Safe by default.Read-only access mode. Every user-supplied SQL statement parses through a validated AST allowlist before execution. Identifier interpolation flows through a strict[A-Za-z_][A-Za-z0-9_]regex — a design constraint that means user input never reaches the database through string concatenation. Capabilities like DDL, shell, andLISTEN/NOTIFYare off until you opt in. Every tool publishes MCPToolAnnotations(readOnlyHint,openWorldHint) derived from those same gates, so clients can auto-approve reads and gate writes without guessing.
- One server, broad surface.Application data access (queries, search, cursors, NL→SQL)
andDBA-grade operations (health checks, index tuning, EXPLAIN analysis, locks, vacuum, dumps, replicas, migrations) in a single MCP server. Agents don't have to switch tools to switch tasks.
- PostgreSQL-native everything.No ORM, no abstraction tax — usespsycopg3directly, speaks everypg_
system view, integrates with TimescaleDB, pgvector, PostGIS, Apache AGE, andpg_stat_statementswhere they're available, and degrades gracefully when they aren't.
- Production-shaped, not demo-shaped.Connection pooling, per-requestSET ROLEmulti-tenancy, read-replica routing with degraded-host detection, server-side cursors with dedicated connections, rate-limiting, audit trail with regex redaction, PG TLS enforcement on startup, OIDC JWT bearer auth, per-session statement / lock timeouts.
- Observability built in.Prometheus/metricsendpoint on the HTTP transport surfacesmcpg_tool_calls_total{tool,status}+mcpg_tool_duration_seconds. Every tool call records a structured audit event with credential-redacted arguments.
- Test-driven, multi-version.2,500+ unit tests plus an integration suite that runs against a real PostgreSQL container in CI — matrix covers PG14, 15, 16, 17, 18on every push, plus PG19 (beta)as an experimental (non-blocking) entry tracked under issue #120.

pip install mcpg # or, in an isolated venv exposed globally: uv tool install mcpg

Pull the pre-built image from the GitHub Container Registry (published on every tagged release —:latesttracks the newest, or pin a version like:0.6.5):

docker pull ghcr.io/devopam/mcpg:latest docker run --rm --name mcpg -p 8000:8000 \ -e MCPG_DATABASE_URL=postgresql://user:pass@host:5432/db \ -e MCPG_ACCESS_MODE=read-only \ ghcr.io/devopam/mcpg:latest

OnWindows PowerShellreplace the trailing\with a backtick``(or put the command on one line); theinstallation guidehas ready-to-copy Linux/macOS, PowerShell, and Command Prompt blocks.

docker build -t mcpg https://github.com/devopam/MCPg.git

Multi-stage image: runtime stage drops the build toolchain, runs asuid=10001 / gid=10001withnologinshell, application files root-owned and read-only to the runtime user.

git clone https://github.com/devopam/MCPg && cd MCPg uv sync

uv synccreates a venv with all runtime + dev dependencies and exposes themcpgconsole script.

One-click installs:[](https://cursor.com/install-mcp?name=mcpg&amp;config=eyJjb21tYW5kIjoidXZ4IiwiYXJncyI6WyJtY3BnIl0sImVudiI6eyJNQ1BHX0RBVEFCQVNFX1VSTCI6InBvc3RncmVzcWw6Ly91c2VyOnBhc3NAbG9jYWxob3N0OjU0MzIvbXlkYiJ9fQ%3D%3D)<<<[](https://vscode.dev/redirect?url=vscode%3Amcp%2Finstall%3F%257B%2522name%2522%253A%2522mcpg%2522%252C%2522command%2522%253A%2522uvx%2522%252C%2522args%2522%253A%255B%2522mcpg%2522%255D%252C%2522env%2522%253A%257B%2522MCPG_DATABASE_URL%2522%253A%2522%2524%257Binput%253Adatabase_url%257D%2522%257D%252C%2522inputs%2522%253A%255B%257B%2522type%2522%253A%2522promptString%2522%252C%2522id%2522%253A%2522database_url%2522%252C%2522description%2522%253A%2522PostgreSQL%2520connection%2520URL%2520%2528postgresql%253A%252F%252Fuser%253Apass%2540host%253A5432%252Fdb%2529%2522%252C%2522password%2522%253Atrue%257D%255D%257D)<<<— setup for Windsurf, JetBrains, Zed, Cline, Antigravity, Qwen Code, Perplexity, ChatGPT, Copilot Studio, Continue, and HTTP clients in theintegrations guide.

One-click install in Claude Desktop (.mcpb)

Downloadmcpg-<version>.mcpbfrom thelatest releaseand double-click it (or drag it into Claude Desktop's Settings → Extensions). You'll be prompted for your PostgreSQL connection URL — stored in the OS keychain — and an access mode (defaults to read-only). That's the whole install: the bundle is ~2 kB and the host resolves the pinnedmcpgrelease from PyPI for your platform.

Or wire it up manually (stdio transport)

Drop this into yourclaude_desktop_config.json(macOS:~/Library/Application Support/Claude/claude_desktop_config.json; Windows:%APPDATA%\Claude\claude_desktop_config.json):

{ "mcpServers": { "mcpg": { "command": "uvx", "args": ["mcpg"], "env": { "MCPG_DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb" } } } }

Restart Claude Desktop. The MCPg toolset is now available to the model. You can ask Claude things like:

"What schemas exist in this database? For each one, summarise the three biggest tables."

"Why is this query slow?SELECT FROM orders WHERE customer_id = 42 ORDER BY created_at DESC"

No interesting data yet? Seed the demo dataset

MCPG_DATABASE_URL=postgresql://... mcpg --demo

One command seeds a small, curated e-commerce dataset (3,000 orders, 900 product reviews, deliberately planted flaws) into anmcpg_demoschema — engineered so the index advisor, query-plan analysis, full-text search, PII audit, and graph projection all have something real to find on your first try. See theguided tourfor a captured walkthrough, and remove it any time withmcpg --demo-drop.

Run as an HTTP server (for IDE integrations, web apps, etc.)

MCPG_DATABASE_URL=postgresql://user:pass@localhost:5432/mydb \ MCPG_TRANSPORT=streamable-http \ MCPG_HTTP_PORT=8000 \ mcpg

Then point any MCP-aware client athttp://localhost:8000/mcp(or/ssefor the SSE transport). SetMCPG_HTTP_AUTH_TOKEN=...for a static bearer, orMCPG_AUTH_MODE=oidcfor full JWT validation against an OIDC issuer.

MCPg is configuredentirely through environment variables— no config file, no flags (the CLI's--version/--demo/--demo-dropare one-shot commands, not configuration). The only required one isMCPG_DATABASE_URL; everything else has a safe default.

Capability gates (opt-in for higher-blast-radius tools)

Multiple databases (read-only secondaries)

Subprocess tools (MCPG_ALLOW_SHELL=trueonly)

LISTEN/NOTIFY (MCPG_ALLOW_LISTEN=trueonly)

By default every secret is read straight from the environment. SetMCPG_SECRETS_BACKEND=fileto instead load API keys / bearer token / HMAC key from a mounted file — a name in the file wins; anything absent falls back to the env var, so partial files work.

MCPg auto-discovers every configured provider from the environment at startup — set as many vendor keys as you have and each becomes callable.Nineteen providers ship built in.Three are first-party (Anthropic, OpenAI, Gemini); the other sixteen speak the OpenAI-compatible API with vendor-preset endpoints:DeepSeek, Qwen, OpenRouter, Perplexity, xAI (Grok), Groq, Mistral, Together, Fireworks, DeepInfra, Cerebras, Nebius, Hugging Face, GitHub Models, SambaNova, and Moonshot (Kimi). Every built-in is plug-and-play — set the vendor's conventional API-key env var and it's auto-discovered — andanyotherOpenAI-compatible vendor or local model server (Ollama, vLLM, LM Studio) is still pluggable through configuration aloneviaMCPG_NL2SQL_CUSTOM_PROVIDERS. The whole built-in list is one declarative registry innl2sql.py, so adding a vendor or refreshing a retired default model is a one-line data change.

WhenMCPG_NL2SQL_PROVIDERis unset, MCPg auto-picks the default in registry order —anthropic → openai → geministay first so existing deployments are unaffected.translate_nl_to_sqlaccepts an optionalprovider="…"argument to route per call;get_server_inforeports which are configured.

The MCP tools are invoked by the agent (Claude, Cursor, Continue, …) in response to your natural-language instructions. A handful of illustrative round-trips:

You:What tables live in thepublicschema, and which ones are the biggest by row count?

Agent (usinglist_tables+summarize_table× N):Six tables:customers(1.2M rows),orders(4.7M),line_items(18.3M),products(340),addresses(1.4M),audit_log(45.8M — the largest, accumulates without retention).

You:Why doesSELECT FROM orders o JOIN line_items l ON o.id = l.order_id WHERE o.created_at > now() - interval '7 days'take 8 seconds?

Agent (usingwhy_is_this_slow+recommend_indexes):EXPLAIN ANALYZEshows a sequential scan overorders(4.7M rows) filtered bycreated_at. There's no index onorders.created_at. Recommended:CREATE INDEX CONCURRENTLY orders_created_at_idx ON orders (created_at DESC);Expected improvement: ~95% reduction (index scan touches ~33K rows instead of full table). Runvalidate_migrationon it before applying to confirm there's no locking surprise.

You:Find customers who placed an order this month but never in the previous three months — show me their email and current lifetime spend.

SELECT c.email, SUM(l.price  l.quantity) AS lifetime_spend FROM customers c JOIN orders o ON o.customer_id = c.id JOIN line_items l ON l.order_id = o.id WHERE EXISTS ( SELECT 1 FROM orders o2 WHERE o2.customer_id = c.id AND o2.created_at >= date_trunc('month', now())) AND NOT EXISTS ( SELECT 1 FROM orders o3 WHERE o3.customer_id = c.id AND o3.created_at >= date_trunc('month', now()) - interval '3 months' AND o3.created_at < date_trunc('month', now())) GROUP BY c.email;

You:Draw me an ER diagram of thepublicschema.

Agent (usinggenerate_schema_diagram):Returns a Mermaid diagram you can paste straight into GitHub / Notion / Obsidian.

You:How healthy is this database right now?

Agent (usingaudit_database):Returns a graded report:Memory & I/O score 92 (GOOD), Transaction & Connection 78 (WARNING: rollback rate 0.4%, look at app logs), Concurrency & Locks 60 (CRITICAL: 14 backends waiting), Cleanliness & Bloat 88 (GOOD), Slow queries 70 (WARNING: top query template runs 5000×, mean 90 ms — seeoptimize_query).

You:Soft-delete every order older than 5 years.

Agent (usingrun_writewithMCPG_AUDIT_PERSIST=true):Validates the statement through the safe-SQL kernel, runs it inside a transaction, returns affected row count, persists the call (sql + arguments — with secrets regex-redacted — + status) tomcpg_audit.eventsfor after-the-fact review.

For dozens more recipes — multi-tenant routing, RLS testing, NL→SQL, hybrid vector + FTS search, Apache AGE Cypher, TimescaleDB, ORM schema exports, server-side cursors — seedocs/cookbook.md.

Compact category list. For the full, current tool reference seedocs/tools.md; for a guided walkthrough seedocs/tour.md.

- docs/installation.md— install + configure
-
docs/tour.md— guided tool tour
-
docs/cookbook.md— practical agent recipes
-
docs/tools.md— complete tool reference
-
docs/architecture.md— how the pieces fit together
-
docs/scaling.md— pool sizing, replicas, performance
-
docs/security-hardening.md— security feature roadmap
-
docs/release-process.md— how releases ship to PyPI
-
docs/adr/— architecture decision records
- Browse at
https://devopam.github.io/MCPg/

- Vulnerability reporting: seeSECURITY.md. 90-day coordinated-disclosure window; reports todevopam@gmail.com.
- Defence-in-depth: capability gates, SafeSQL kernel, identifier allowlist, audit redaction, PG TLS enforcement at startup, rate-limiting, OIDC JWT validation, per-session timeouts.
- See
docs/security-hardening.mdfor the living roadmap of shipped (✅) and queued (⬜) hardening items.

MCPg is self-hosted: your database contents never leave your infrastructure, and there is no telemetry or phone-home of any kind. The one documented exception is the opt-intranslate_nl_to_sqltool, which sends your question plus schema context (names, not row data) to the LLM provideryou*configure. Full policy — data collection, usage, storage, third-party sharing, retention, and contact — is inPRIVACY.md.

SeeCHANGELOG.mdfor the full version history,docs/release-process.mdfor how releases are cut, and theGitHub Releasespage for downloadable artifacts.

Pull requests welcome — seeCONTRIBUTING.mdfor the dev-loop setup, test conventions, and the per-PR review checklist.

MIT — seeLICENSE. The SQL-safety kernel (src/mcpg/sql/) is first-party, re-authored from the MIT-licensedcrystaldba/postgres-mcp; seeNOTICE`for the lineage.

Wrapped extensions — licenses you should know about

MCPg's source is MIT, but the PostgreSQL extensions it wraps each carry their own license. The wrappers themselves are at arm's length (SQL-level calls, no static or dynamic linking into MCPg's Python process), so MCPg-the-project is not a derivative work of any of them.Operators deploying a service built on MCPg + a given extension take on whatever obligations that extension's license imposes— same as installing the extension directly. The matrix below names the license per wrapped extension so you can make an informed choice.

This matrix is a starting point — for the binding answer on your specific deployment, consult the extension's upstream LICENSE file and (if it matters legally) your own counsel.

Disclaimer.Best efforts have been made to bring MCPg to production grade, but it remains an actively developed project and may contain issues. See the License terms for indemnity details.

This is a web browser that enables your coding agent, such as Claude Code, to visit websites on your behalf and assist you in identifying bugs or creating UI test cases.

An example of a remote, authentication-free MCP server deployable on Cloudflare Workers.

Multi-database agent access (PostgreSQL, SQLite, MySQL, Oracle, SQL Server) with batch queries, pre-configured connections, and SQLGlot-enforced read-only safety

MCP servers that give AI clients safe, structured access to SQL databases. One installable package per database engine. Every package exposes the same minimal two-tool surface, execute_sql and search_objects, with guardrails on by default: read-only mode, row caps, and statement timeouts.

MCP server that gives AI agents deep understanding of contemporary or legacy relational databases.

PostgreSQL MCP server for connecting AI agents to Postgres databases, inspecting schema, and executing SQL queries through MCP tools.

An MCP server for exploring and querying PostgreSQL databases.

Provides read-only access to PostgreSQL databases with multi-schema support, allowing LLMs to inspect schemas and execute queries across different namespaces.

connect a read-only replica, analytics database, or staging database. Keep credentials on your machine while the tool discovers schema, generates safe SQL, previews it for approval, runs the query, and summarizes the result.

A FastAPI microservice for health-related operations, featuring JWT authentication and a PostgreSQL database with Alembic migrations.

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.