Install
$ agentstack add mcp-corporatepiyush-mcp-pg-rust Open-source listing — not yet scanned by AgentStack. Follow the source repository for install instructions.
Security review
⚠ Flagged1 finding(s); flagged for manual review. · v0.1.0 How review works →
- • Prompt-injection patterns
- • Secret / credential exfiltration
- • Dangerous shell & filesystem operations
- • Untrusted network calls
- • Known-malicious package signatures
- high Destructive filesystem operation.
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
About
mcp-postgres
[](https://crates.io/crates/mcp-postgres) [](LICENSE) [](https://github.com/corporatepiyush/mcp-pg-rust)
mcp-postgres is a high-performance MCP server that brings PostgreSQL into Claude Desktop and any MCP-compatible AI tool. 133 PostgreSQL tools, lock-free connection pooling, sub-10ms latency.
> Tools are opt-in (5.2.0+). No tools are exposed by default. You enable > them one category at a time with --enable- flags (or > --enable-all). A server started with no enable flags advertises an empty > tool list and rejects every tools/call. See > [Tool Exposure](#tool-exposure-opt-in-by-category).
> MCP suite. One of four high-performance MCP servers written in Rust — > mcp-postgres · > mcp-filesystem · > mcp-memory · > mcp-web-search. > All implement MCP protocol revision 2025-11-25.
Quick Start
Install
# From crates.io
cargo install mcp-postgres
# Or from Homebrew (macOS)
brew tap corporatepiyush/mcp-postgres
brew install mcp-postgres
Run
Tools are opt-in — pass one or more --enable- flags (or --enable-all). Without them the server exposes no tools.
# Stdio mode (for Claude Desktop) — expose read-only query + schema tools
mcp-postgres --database-url "postgres://user:pass@localhost:5432/mydb" --stdio \
--enable-query --enable-schema
# TCP server (port 3000) — expose everything
mcp-postgres --database-url "postgres://user:pass@localhost:5432/mydb" --enable-all
# HTTP/2 server (port 3001) — query + monitoring only
mcp-postgres --database-url "postgres://user:pass@localhost:5432/mydb" --http-port 3001 \
--enable-query --enable-monitoring
Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"postgres": {
"command": "mcp-postgres",
"args": ["--database-url", "postgres://user:pass@localhost:5432/mydb", "--stdio", "--enable-all"]
}
}
}
[Complete setup guide →](./guides/INSTALLATION.md)
Why mcp-postgres?
| Feature | mcp-postgres | DIY / psql | |---------|-------------|------------| | 133 purpose-built tools | Schema inspection, DDL, monitoring, replication, batch ops, security audit, text search, extensions, maintenance, and more | You build every query from scratch | | Lock-free connection pool | Zero-mutex crossbeam::ArrayQueue — pure CAS loops, no kernel overhead | Deadpool or manual Mutex | | Dual-protocol | TCP (3000) + HTTP/2 (3001) + stdio — one binary, three transports | Multiple servers to wire up | | Sub-10ms latency | Allocated for AI interactivity — hot path is allocation-free | Unpredictable | | SQL injection prevention | Every identifier validated, quote_ident sanitization, structured predicates | Manual parameterization | | PG version-aware | Queries verified against PG 16–18 docs, graceful fallbacks for version differences | Version-specific failures |
Command-Line Options
Usage: mcp-postgres [OPTIONS]
Options:
-d, --database-url PostgreSQL connection string
-H, --host TCP server host [127.0.0.1]
-p, --port TCP server port [3000]
--http-port HTTP/2 server port [3001]
--min-connections Min pool connections [5]
--max-connections Max pool connections [20]
--log-level Log level [info]
--enable-metrics Prometheus /metrics endpoint
--metrics-port Metrics port [9090]
--stdio Stdio mode (Claude Desktop)
--access-mode unrestricted, restricted [unrestricted]
--tls-cert PEM cert chain to serve HTTP over TLS (HTTPS)
--tls-key PEM private key matching --tls-cert
Tool exposure (none enabled by default — see "Tool Exposure"):
--enable-all Expose every category (overrides the flags below)
--enable-query Query: execute/explain/async-execute + sampling
--enable-batch Batch: bulk insert/update/delete + COPY
--enable-schema Schema: read-only inspection + DDL generation
--enable-ddl DDL: create/drop/alter/rename objects
--enable-admin Admin: vacuum/reindex/analyze/truncate + sessions
--enable-monitoring Monitoring: stats, conns, txns, replication, config
--enable-security Security: roles, users, privileges, audits
--enable-data-io Data I/O: CSV export + URL/file import
--enable-extensions Extensions: pgvector, TimescaleDB, BM25, ext mgmt
-h, --help Print help
-V, --version Print version
TLS (HTTPS)
The HTTP/2 transport can be served over TLS (rustls, ring provider — the same provider used for sslmode-gated PostgreSQL connections, no OpenSSL/aws-lc). Provide a PEM certificate chain and private key via --tls-cert/--tls-key or the MCP_TLS_CERT/MCP_TLS_KEY environment variables and the HTTP server speaks HTTPS instead of plaintext. The two must be supplied together or startup is refused; when neither is set the HTTP transport stays plaintext (the default). The raw TCP transport is unaffected.
mcp-postgres --http-port 3001 --tls-cert ./cert.pem --tls-key ./key.pem
MCP Compliance
Implements the Model Context Protocol revision 2025-11-25 over JSON-RPC 2.0, via TCP, HTTP/2, or stdio.
| Area | Support | |---|---| | Transports | stdio, TCP (3000), HTTP/2 (3001) | | Protocol version | 2025-11-25, negotiates down to 2025-06-18 / 2025-03-26 / 2024-11-05 | | initialize | ✅ version negotiation + instructions | | tools/list, tools/call | ✅ (133 tools) | | CallToolResult | ✅ content[] + structuredContent + isError | | Capabilities advertised | tools only — nothing is advertised that isn't implemented | | resources · prompts · logging · completion | ❌ roadmap — see [MIGRATION.md](./MIGRATION.md) |
Request:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": { "name": "list_tables", "arguments": {} },
"id": 1
}
Result — a spec-compliant CallToolResult. The payload is available as a machine-readable structuredContent object and as serialized text; tool failures come back with isError: true (not as JSON-RPC protocol errors) so the model can self-correct:
{
"content": [{ "type": "text", "text": "{\"tables\":[\"users\",\"orders\"]}" }],
"structuredContent": { "tables": ["users", "orders"] },
"isError": false
}
Upgrading from 4.x? The result shape changed — see [MIGRATION.md](./MIGRATION.md).
Tool Exposure (opt-in by category)
Every tool belongs to exactly one of 9 categories. Nothing is exposed until you enable its category at startup — disabled tools are hidden from tools/list and rejected from tools/call as if they did not exist. This lets you hand an agent precisely the surface area it needs (e.g. read-only query + monitoring) and nothing more.
| Flag | Category | What it exposes | |------|----------|-----------------| | --enable-query | Query | execute_query, execute_insert/update/delete, async_execute_*, explain_query, sample_data | | --enable-batch | Batch | async_batch_insert/update/delete, async_batch_insert_copy | | --enable-schema | Schema (read) | list_tables, describe_table, list_indexes/schemas/triggers/partitions, show_constraints, get_object_details, list_databases, table_dependencies, generate_create_*_ddl | | --enable-ddl | DDL (write) | create/drop/alter table·view·schema·sequence·index·partition, backup_table, add/drop/rename_column, alter_column_type, rename_table/index/schema, FK & constraint ops, clone_table_schema, create_database | | --enable-admin | Admin | vacuum, vacuum_full, vacuum_analyze, analyze_table, reindex_table/database, reset_statistics, truncate_table, cancel_query, terminate_connection | | --enable-monitoring | Monitoring (read) | table/index stats, sizes, cache ratio, pg_stat_statements, connections, running/blocked queries, transactions, locks, deadlocks, replication, WAL, settings, health checks, suggest_indexes, bloat | | --enable-security | Security | list/create/alter/drop_user, role ops, grant/revoke_privileges, privilege listings | | --enable-data-io | Data I/O | export_csv, import_from_url (also gated behind --allow-url-import) | | --enable-extensions | Extensions | pgvector (vector_search, create_vector_index, list_vector_columns), TimescaleDB (create_hypertable, show_chunks, retention/compression policies, continuous aggregates), BM25 full-text, and generic create/drop/list_extension | | --enable-all | (all of the above) | Every category. Overrides the individual flags. |
# Read-only analyst: inspect schema and run SELECTs, nothing else
mcp-postgres -d "$DATABASE_URL" --stdio --enable-query --enable-schema --enable-monitoring
# Full access
mcp-postgres -d "$DATABASE_URL" --stdio --enable-all
Category gating composes with the existing --access-mode restricted (which additionally blocks all write tools) and --allow-url-import controls.
Tools (133 Total)
The headings below are the human-readable groupings. To map each one to the --enable- flag that exposes it, see the [Tool Exposure](#tool-exposure-opt-in-by-category) table above.
⚡ Query Execution (8) · --enable-query — executequery, executeinsert, executeupdate, executedelete, explainquery, asyncexecuteinsert, asyncexecuteupdate, asyncexecutedelete Fire off raw SQL, run parameterized inserts/updates/deletes with automatic type coercion, and peek under the hood with EXPLAIN ANALYZE plans. Async variants let you fire-and-forget long-running operations without blocking your AI workflow. 🪄 Key moves: executequery for ad-hoc SQL, explainquery to spot missing indexes or seq-scans, asyncexecute_* for bulk writes that outlive the request.
🔍 Schema Inspection (8) — listtables, describetable, listschemas, listindexes, listtriggers, showconstraints, listpartitions, getobjectdetails Peel back the layers of your database: list every table across schemas, drill into column types and nullability, inspect index definitions, trigger functions, check constraints, and navigate partitioned table hierarchies. 🪄 Key moves: describetable is your go-to for column metadata, getobjectdetails shows DDL + stats in one shot, list_partitions maps your partitioning tree.
🏗️ DDL Operations (15) — create/drop table, view, schema, sequence, index, partition, alterview, backuptable Full DDL surface for schema evolution. Spin up tables with typed columns, create views to simplify complex queries, generate sequences for auto-increment IDs, build indexes for performance, and partition large tables for manageability. 🪄 Key moves: backuptable snapshots a table before risky DDL, alterview redefines without dropping, create_partition attaches new ranges to existing partition trees.
📦 Batch Operations (4) — asyncbatchinsert, asyncbatchupdate, asyncbatchdelete, asyncbatchinsertcopy Move mountains of data in a single call. Insert thousands of rows with structured arrays, run bulk updates and deletes with filtered predicates, or use asyncbatchinsertcopy leveraging PostgreSQL's COPY protocol for wire-speed ingestion. 🪄 Key moves: asyncbatchinsertcopy is 2-3x faster than row-by-row INSERT for 10K+ rows, asyncbatch_update handles conditional multi-row updates atomically.
📊 Database Monitoring (10) — table/index stats, database/table size, cache hit ratio, vacuum, analyze, pgstatstatements, resetstatistics See how your database is really doing. Track table and index usage stats, measure disk consumption per database or table, calculate cache hit ratios, kick off VACUUM and ANALYZE, and query pgstatstatements to find your top CPU-hungry queries. 🪄 Key moves: getcachehitratio tells you if your sharedbuffers are sized right, getpgstatstatements surfaces slow queries by total time, analyze_table refreshes planner stats on-demand.
🔌 Connection Management (4) — listconnections, showcurrentuser, showrunningqueries, showconnectionsummary See who's connected, what they're running, and how connections are distributed. Diagnose connection bloat, find runaway queries, and identify which application is hogging the pool. 🪄 Key moves: showrunningqueries catches long-running queries in-flight, showconnection_summary groups by state/application for a bird's-eye view.
🔐 Security & Users (5) — listusers, user/role privileges, database privileges, sessioninfo Audit your security posture: enumerate database roles and their login capabilities, inspect table-level and schema-level GRANTs, check role membership chains, and review database-level ACLs. 🪄 Key moves: listuserprivileges surfaces exactly what each user can SELECT/INSERT/UPDATE/DELETE, listrolememberships reveals privilege escalation paths through role inheritance.
⚙️ Configuration (5) — allsettings, getsetting, memory/performance/logsettings Navigate the sprawling world of postgresql.conf without grepping. View every GUC parameter, look up specific settings by name, and filter by category to zero in on memory tuning, performance knobs, or logging config. 🪄 Key moves: showmemorysettings pulls sharedbuffers, workmem, maintenanceworkmem in one shot, getsetting for a quick SHOW of any parameter.
🔄 Transaction Monitoring (7) — activetransactions, locks, waitinglocks, isolation, deadlocks, autocommit, transactiontimeout Dive into the transaction machinery: detect long-running idle-in-transaction sessions, map lock contention chains with pgblockingpids, identify deadlocks, check isolation levels, and monitor transaction age to prevent bloat. 🪄 Key moves: showwaitinglocks shows who's blocked by whom, showdeadlocks queries pgstatactivity for blocked processes, showtransactiontimeout checks idleintransactionsessiontimeout.
📋 Replication (5) — replicationstatus, replicationslots, standbyservers, walinfo, basebackupprogress Keep your replicas healthy. Monitor streaming replication lag in bytes and time, inspect replication slots for WAL accumulation, list standby servers with their flush/replay positions, and track pgstatprogressbasebackup for ongoing backups. 🪄 Key moves: showreplicationstatus shows sender/receiver pairs with lag, listreplication_slots helps you spot slots that are consuming too much WAL.
🏥 Database Health (4) — analyzedbhealth, unused/duplicate indexes, vacuumprogress Get a comprehensive wellness check: scan for unused indexes that waste write IO, detect duplicate indexes that bloat storage, monitor VACUUM progress across all databases, and get a health score with actionable recommendations. 🪄 Key moves: listunusedindexes finds indexes with zero scans since stats reset, showvacuum_progress tracks autovacuum workers in real-time.
🗑️ Maintenance (1) — truncate_table Safely and quickly remove all rows from a table while preserving the table structure. Performs privilege validation before executing, and supports RESTART IDENTITY for serial column reset. 🪄 Key moves: Blows away table data faster than DELETE — ideal for staging tables and temp data cleanup.
🧠 Index Advisor (1) — suggestindexes Analyzes your query workload from pgstat_statements and suggests index candidates based on WHERE clauses, JOIN conditions, and ORDER BY patterns. Each suggestion includes the estimat
…
Source & license
This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: corporatepiyush
- Source: corporatepiyush/mcp-pg-rust
- License: Apache-2.0
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet — be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.