{"id":46190010,"url":"https://github.com/neverinfamous/postgres-mcp","last_synced_at":"2026-04-09T00:07:48.385Z","repository":{"id":329180983,"uuid":"1116037680","full_name":"neverinfamous/postgres-mcp","owner":"neverinfamous","description":"Secure PostgreSQL Administration \u0026 Observability with Code Mode— True V8 Isolate Sandbox Replacing 248 Specialized Tools for up to 90% Token Savings. Includes Tool Filtering, Payload Optimization, HTTP/SSE, OAuth 2.1, Audit \u0026 Token Logging, Deterministic Error Handling, Support for 12 Extensions (pgvector, PostGIS, pg_partman, pg_cron \u0026 more).","archived":false,"fork":false,"pushed_at":"2026-04-05T04:37:24.000Z","size":3868,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-04-05T05:17:11.629Z","etag":null,"topics":["ai-agents","citext","code-mode","data-science","database","database-management","developer-tools","hypopg","kcache","ltree","mcp","npm","oauth2","pg-cron","pg-partman","pgcrypto","pgvector","postgis","postgresql","typescript"],"latest_commit_sha":null,"homepage":"https://adamic.tech/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/neverinfamous.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-14T04:11:46.000Z","updated_at":"2026-04-05T04:37:24.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/neverinfamous/postgres-mcp","commit_stats":null,"previous_names":["neverinfamous/postgresql-mcp","neverinfamous/postgres-mcp"],"tags_count":16,"template":false,"template_full_name":null,"purl":"pkg:github/neverinfamous/postgres-mcp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fpostgres-mcp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fpostgres-mcp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fpostgres-mcp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fpostgres-mcp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/neverinfamous","download_url":"https://codeload.github.com/neverinfamous/postgres-mcp/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fpostgres-mcp/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31426193,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-05T02:22:46.605Z","status":"ssl_error","status_checked_at":"2026-04-05T02:22:33.263Z","response_time":75,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-agents","citext","code-mode","data-science","database","database-management","developer-tools","hypopg","kcache","ltree","mcp","npm","oauth2","pg-cron","pg-partman","pgcrypto","pgvector","postgis","postgresql","typescript"],"created_at":"2026-03-03T00:12:43.073Z","updated_at":"2026-04-09T00:07:48.379Z","avatar_url":"https://github.com/neverinfamous.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# postgres-mcp\n\n\u003c!-- mcp-name: io.github.neverinfamous/postgres-mcp --\u003e\n\n**PostgreSQL MCP Server** binding the Model Context Protocol to a secure PostgreSQL sandbox.\n\nFeatures **Code Mode** — a revolutionary approach that provides access to all 248 tools through a secure, true V8 isolate (`worker_threads`), eliminating the massive token overhead of multi-step tool calls. Also includes schema introspection, migration tracking, smart tool filtering, deterministic error handling, connection pooling, HTTP/SSE Transport, OAuth 2.1 authentication, and extension support for citext, ltree, pgcrypto, pg_cron, pg_stat_kcache, pgvector, PostGIS, and HypoPG.\n\n**248 Specialized Tools** · **23 Resources** · **20 AI-Powered Prompts**\n\n[![GitHub](https://img.shields.io/badge/GitHub-neverinfamous/postgres--mcp-blue?logo=github)](https://github.com/neverinfamous/postgres-mcp)\n![GitHub Release](https://img.shields.io/github/v/release/neverinfamous/postgres-mcp)\n[![Docker Pulls](https://img.shields.io/docker/pulls/writenotenow/postgres-mcp)](https://hub.docker.com/r/writenotenow/postgres-mcp)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n[![MCP](https://img.shields.io/badge/MCP-Registry-green.svg)](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.neverinfamous/postgres-mcp)\n[![npm](https://img.shields.io/npm/v/@neverinfamous/postgres-mcp)](https://www.npmjs.com/package/@neverinfamous/postgres-mcp)\n[![Security](https://img.shields.io/badge/Security-Enhanced-green.svg)](https://github.com/neverinfamous/postgres-mcp/blob/main/SECURITY.md)\n![Status](https://img.shields.io/badge/status-Production%2FStable-brightgreen)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Strict-blue.svg)](https://github.com/neverinfamous/postgres-mcp)\n[![E2E](https://github.com/neverinfamous/postgres-mcp/actions/workflows/e2e.yml/badge.svg)](https://github.com/neverinfamous/postgres-mcp/actions/workflows/e2e.yml)\n[![Tests](https://img.shields.io/badge/Tests-3750_passed-success.svg)](https://github.com/neverinfamous/postgres-mcp)\n[![Coverage](https://img.shields.io/badge/Coverage-96%25-brightgreen.svg)](https://github.com/neverinfamous/postgres-mcp)\n\n**[Docker Hub](https://hub.docker.com/r/writenotenow/postgres-mcp)** • **[npm Package](https://www.npmjs.com/package/@neverinfamous/postgres-mcp)** • **[MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.neverinfamous/postgres-mcp)** • **[Wiki](https://github.com/neverinfamous/postgres-mcp/wiki)** • **[Tool Reference](https://github.com/neverinfamous/postgres-mcp/wiki/Tool-Reference)** • **[Changelog](https://github.com/neverinfamous/postgres-mcp/blob/main/CHANGELOG.md)**\n\n## 🎯 What Sets Us Apart\n\n| Feature                             | Description                                                                                                                                                                                                         |\n| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **Code Mode (V8 Isolate)**          | **Massive Token Savings:** Execute complex, multi-step operations inside a secure, true V8 isolate (`worker_threads`). Stop burning tokens on back-and-forth tool calls and reduce your AI overhead by up to 90%.   |\n| **Deterministic Error Handling**    | No more cryptic database errors causing AI hallucinations. We intercept and translate raw SQL exceptions into clear, actionable advice so your agent knows exactly how to recover without guessing.                 |\n| **248 Token-Optimized Tools**       | The largest PostgreSQL toolset on the MCP registry. Every query uses zero-cost token estimation and smart dataset truncation, ensuring agents always see the big picture without blowing their context windows.     |\n| **OAuth 2.1 + Granular Control**    | Real enterprise security. Authenticate via OAuth 2.1 and control exactly who can read, write, or administer your database with precision scopes mapped down to the specific tool layer.                             |\n| **Audit Trails \u0026 Semantic Diffing** | Total accountability. Track exactly what your AI is doing with detailed JSON logs, automatically snapshot schemas before mutations, and confidently review semantic row-by-row diffs before restoring data.         |\n| **23 Resources \u0026 20 Prompts**       | Instant database meta-awareness. Agents automatically read real-time health, performance, and replication metrics, and can invoke built-in prompt workflows for query tuning and schema design.                     |\n| **Introspection \u0026 Migrations**      | Prevent costly mistakes. Let your AI simulate the cascade impact of schema changes, safely order foreign-key updates, and track migration history automatically.                                                    |\n| **8 Extension Ecosystems**          | Ready for advanced workloads. First-class API support for **pgvector** (AI search), **PostGIS** (geospatial), **pg_cron**, **pgcrypto**, and more—all strictly typed and validated out of the box.                  |\n| **Smart Tool Filtering**            | Give your agent exactly what it needs without overflowing IDE limits. Dynamically compile your server with any combination of our 22 distinct tool groups.                                                          |\n| **Enterprise Infrastructure**       | Built for production. Blazing fast (millions of ops/sec), protected against SQL injection, features high-performance connection pooling, and supports both Streamable HTTP and Legacy SSE protocols simultaneously. |\n\n## Suggested Rule (Add to AGENTS.md, GEMINI.md, etc)\n\n**MCP TOKEN MANAGEMENT**:\n\n- **Token Visibility**: When interacting with `postgres-mcp`, always monitor the `_meta.tokenEstimate` (or `metrics.tokenEstimate` in Code Mode) returned in tool responses.\n- **Audit Resource**: Use the `postgres://audit` resource to review session-level token consumption and identify high-cost operations.\n- **Proactive Efficiency**: If operations are consuming high token counts, prefer code mode and proactively use `limit` parameters.\n\n## 🚀 Quick Start\n\n### Prerequisites\n\n- PostgreSQL 12-18 (tested with PostgreSQL 18.1)\n- **Docker** (recommended) or Node.js 24+ (LTS)\n\n### Docker (Recommended)\n\n```bash\ndocker pull writenotenow/postgres-mcp:latest\n```\n\nAdd to your `~/.cursor/mcp.json` or Claude Desktop config:\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres-mcp\": {\n      \"command\": \"docker\",\n      \"args\": [\n        \"run\",\n        \"--rm\",\n        \"-i\",\n        \"-e\",\n        \"POSTGRES_HOST\",\n        \"-e\",\n        \"POSTGRES_PORT\",\n        \"-e\",\n        \"POSTGRES_USER\",\n        \"-e\",\n        \"POSTGRES_PASSWORD\",\n        \"-e\",\n        \"POSTGRES_DATABASE\",\n        \"writenotenow/postgres-mcp:latest\",\n        \"--tool-filter\",\n        \"codemode\",\n        \"--audit-log\",\n        \"/tmp/postgres-logs/audit.jsonl\"\n      ],\n      \"env\": {\n        \"POSTGRES_HOST\": \"host.docker.internal\",\n        \"POSTGRES_PORT\": \"5432\",\n        \"POSTGRES_USER\": \"your_username\",\n        \"POSTGRES_PASSWORD\": \"your_password\",\n        \"POSTGRES_DATABASE\": \"your_database\"\n      }\n    }\n  }\n}\n```\n\n\u003e **Note for Docker**: Use `host.docker.internal` to connect to PostgreSQL running on your host machine.\n\n📖 **Full Docker guide:** [DOCKER_README.md](DOCKER_README.md) · [Docker Hub](https://hub.docker.com/r/writenotenow/postgres-mcp)\n\n### npm\n\n```bash\nnpm install -g @neverinfamous/postgres-mcp\npostgres-mcp --transport stdio --postgres postgres://user:password@localhost:5432/database\n```\n\n### From Source\n\n```bash\ngit clone https://github.com/neverinfamous/postgres-mcp.git\ncd postgres-mcp\nnpm install\nnpm run build\nnode dist/cli.js --transport stdio --postgres postgres://user:password@localhost:5432/database\n```\n\n## Development\n\nSee **[From Source](#from-source)** above for setup. After cloning:\n\n```bash\nnpm run lint \u0026\u0026 npm run typecheck  # Run checks\nnpm run bench                      # Run performance benchmarks\nnode dist/cli.js info              # Test CLI\nnode dist/cli.js list-tools        # List available tools\n```\n\n### Benchmarks\n\nRun `npm run bench` to execute the performance benchmark suite (10 files, 93+ scenarios) powered by [Vitest Bench](https://vitest.dev/guide/features.html#benchmarking). Use `npm run bench:verbose` for detailed table output.\n\n**Performance Highlights** (Node.js 24, Windows 11):\n\n| Area                        | Benchmark                                | Throughput    |\n| --------------------------- | ---------------------------------------- | ------------- |\n| **Tool Dispatch**           | Map.get() single tool lookup             | ~6.9M ops/sec |\n| **WHERE Validation**        | Simple clause (combined regex fast-path) | ~3.7M ops/sec |\n| **Identifier Sanitization** | validateIdentifier()                     | ~4.4M ops/sec |\n| **Auth — Token Extraction** | extractBearerToken()                     | ~2.7M ops/sec |\n| **Auth — Scope Checking**   | hasScope()                               | ~5.3M ops/sec |\n| **Rate Limiting**           | Single IP check                          | ~2.3M ops/sec |\n| **Logger**                  | Filtered debug (no-op path)              | ~5.4M ops/sec |\n| **Schema Parsing**          | MigrationInitSchema.parse()              | ~2.1M ops/sec |\n| **Metadata Cache**          | Cache hit + miss pattern                 | ~1.7M ops/sec |\n| **Sandbox Creation**        | CodeModeSandbox.create() cold start      | ~863 ops/sec  |\n\n\u003e Full benchmark results and methodology are available on the [Performance wiki page](https://github.com/neverinfamous/postgres-mcp/wiki/Performance).\n\n## 🔗 Database Connection Scenarios\n\n| Scenario                       | Host to Use                           | Example Connection String                         |\n| ------------------------------ | ------------------------------------- | ------------------------------------------------- |\n| **PostgreSQL on host machine** | `localhost` or `host.docker.internal` | `postgres://user:pass@localhost:5432/db`          |\n| **PostgreSQL in Docker**       | Container name or network             | `postgres://user:pass@postgres-container:5432/db` |\n| **Remote/Cloud PostgreSQL**    | Hostname or IP                        | `postgres://user:pass@db.example.com:5432/db`     |\n\n| Provider           | Example Hostname                                 |\n| ------------------ | ------------------------------------------------ |\n| AWS RDS PostgreSQL | `your-instance.xxxx.us-east-1.rds.amazonaws.com` |\n| Google Cloud SQL   | `project:region:instance` (via Cloud SQL Proxy)  |\n| Azure PostgreSQL   | `your-server.postgres.database.azure.com`        |\n| Supabase           | `db.xxxx.supabase.co`                            |\n| Neon               | `ep-xxx.us-east-1.aws.neon.tech`                 |\n\n### 🛠️ Tool Filtering\n\n\u003e [!IMPORTANT]\n\u003e All tool groups include **Code Mode** (`pg_execute_code`) by default. To exclude it, add `-codemode` to your filter: `--tool-filter cron,pgcrypto,-codemode`\n\n\u003e **⭐ Code Mode** (`--tool-filter codemode`) is the recommended configuration — it exposes `pg_execute_code`, a secure, true V8 isolate sandbox providing access to all 248 tools' worth of capability with up to 90% token savings. See [Tool Filtering](#%EF%B8%8F-tool-filtering) for alternatives.\n\n- **Requires `admin` OAuth scope** — execution is logged for audit\n\n**📖 [See Full Installation Guide →](https://github.com/neverinfamous/postgres-mcp#readme)**\n\n### What Can You Filter?\n\nThe `--tool-filter` argument accepts **groups** or **tool names** — mix and match freely:\n\n| Filter Pattern | Example                    | Description               |\n| -------------- | -------------------------- | ------------------------- |\n| Groups only    | `core,jsonb,transactions`  | Combine individual groups |\n| Tool names     | `pg_read_query,pg_explain` | Custom tool selection     |\n| Group + Tool   | `core,+pg_stat_statements` | Extend a group            |\n| Group - Tool   | `core,-pg_drop_table`      | Remove specific tools     |\n\n### Tool Groups (22 Available)\n\n| Group           | Tools | Description                                                           |\n| --------------- | ----- | --------------------------------------------------------------------- |\n| `codemode`      | 1     | Code Mode (sandboxed code execution) 🌟 **Recommended**               |\n| `core`          | 21    | Read/write queries, tables, indexes, convenience/drop tools           |\n| `transactions`  | 9     | BEGIN, COMMIT, ROLLBACK, savepoints, status                           |\n| `jsonb`         | 21    | JSONB manipulation, queries, and pretty-print                         |\n| `text`          | 14    | Full-text search, fuzzy matching                                      |\n| `performance`   | 25    | EXPLAIN, query analysis, optimization, diagnostics, anomaly detection |\n| `admin`         | 12    | VACUUM, ANALYZE, REINDEX, insights                                    |\n| `monitoring`    | 12    | Database sizes, connections, status                                   |\n| `backup`        | 13    | pg_dump, COPY, restore, audit backups                                 |\n| `schema`        | 13    | Schemas, views, sequences, functions, triggers                        |\n| `introspection` | 7     | Dependency graphs, cascade simulation, schema analysis                |\n| `migration`     | 7     | Schema migration tracking and management                              |\n| `partitioning`  | 7     | Native partition management                                           |\n| `stats`         | 20    | Statistical analysis, window functions, outlier detection             |\n| `vector`        | 17    | pgvector (AI/ML similarity search)                                    |\n| `postgis`       | 16    | PostGIS (geospatial)                                                  |\n| `cron`          | 9     | pg_cron (job scheduling)                                              |\n| `partman`       | 11    | pg_partman (auto-partitioning)                                        |\n| `kcache`        | 8     | pg_stat_kcache (OS-level stats)                                       |\n| `citext`        | 7     | citext (case-insensitive text)                                        |\n| `ltree`         | 9     | ltree (hierarchical data)                                             |\n| `pgcrypto`      | 10    | pgcrypto (encryption, UUIDs)                                          |\n\n### Syntax Reference\n\n| Prefix   | Target | Example          | Effect                                      |\n| -------- | ------ | ---------------- | ------------------------------------------- |\n| _(none)_ | Group  | `core`           | **Whitelist Mode:** Enable ONLY this group  |\n| _(none)_ | Tool   | `pg_read_query`  | **Whitelist Mode:** Enable ONLY this tool   |\n| `+`      | Group  | `+vector`        | Add tools from this group to current set    |\n| `-`      | Group  | `-admin`         | Remove tools in this group from current set |\n| `+`      | Tool   | `+pg_explain`    | Add one specific tool                       |\n| `-`      | Tool   | `-pg_drop_table` | Remove one specific tool                    |\n\n## 🌐 HTTP/SSE Transport (Remote Access)\n\nFor remote access, web-based clients, or HTTP-compatible MCP hosts, use the HTTP transport:\n\n```bash\nnode dist/cli.js \\\n  --transport http \\\n  --port 3000 \\\n  --postgres \"postgres://user:pass@localhost:5432/db\"\n```\n\n**Docker:**\n\n```bash\ndocker run --rm -p 3000:3000 \\\n  -e POSTGRES_URL=postgres://user:pass@host:5432/db \\\n  writenotenow/postgres-mcp:latest \\\n  --transport http --port 3000\n```\n\nThe server supports **two MCP transport protocols simultaneously**, enabling both modern and legacy clients to connect:\n\n### Streamable HTTP (Recommended)\n\nModern protocol (MCP 2025-03-26) — single endpoint, session-based:\n\n| Method   | Endpoint | Purpose                                          |\n| -------- | -------- | ------------------------------------------------ |\n| `POST`   | `/mcp`   | JSON-RPC requests (initialize, tools/list, etc.) |\n| `GET`    | `/mcp`   | SSE stream for server notifications              |\n| `DELETE` | `/mcp`   | Session termination                              |\n\nSessions are managed via the `Mcp-Session-Id` header.\n\n### Stateless Mode\n\nFor serverless/stateless deployments where sessions are not needed:\n\n```bash\nnode dist/cli.js --transport http --port 3000 --stateless --postgres \"postgres://...\"\n```\n\nIn stateless mode: `GET /mcp` returns 405, `DELETE /mcp` returns 204, `/sse` and `/messages` return 404. Each `POST /mcp` creates a fresh transport.\n\n### Legacy SSE (Backward Compatibility)\n\nLegacy protocol (MCP 2024-11-05) — for clients like Python `mcp.client.sse`:\n\n| Method | Endpoint                   | Purpose                                                       |\n| ------ | -------------------------- | ------------------------------------------------------------- |\n| `GET`  | `/sse`                     | Opens SSE stream, returns `/messages?sessionId=\u003cid\u003e` endpoint |\n| `POST` | `/messages?sessionId=\u003cid\u003e` | Send JSON-RPC messages to the session                         |\n\n### Utility Endpoints\n\n| Method | Endpoint  | Purpose                                                                |\n| ------ | --------- | ---------------------------------------------------------------------- |\n| `GET`  | `/health` | Health check (bypasses rate limiting, always available for monitoring) |\n\n## 🔐 Authentication\n\npostgres-mcp supports two authentication mechanisms for HTTP transport:\n\n### Simple Bearer Token (`--auth-token`)\n\nLightweight authentication for development or single-tenant deployments:\n\n```bash\nnode dist/cli.js --transport http --port 3000 --auth-token my-secret --postgres \"postgres://...\"\n\n# Or via environment variable\nexport MCP_AUTH_TOKEN=my-secret\nnode dist/cli.js --transport http --port 3000 --postgres \"postgres://...\"\n```\n\nClients must include `Authorization: Bearer my-secret` on all requests. `/health` and `/` are exempt. Unauthenticated requests receive `401` with `WWW-Authenticate: Bearer` headers per RFC 6750.\n\n### OAuth 2.1 (Enterprise)\n\nFull OAuth 2.1 with RFC 9728/8414 compliance for production multi-tenant deployments:\n\n```bash\nnode dist/cli.js \\\n  --transport http \\\n  --port 3000 \\\n  --postgres \"postgres://user:pass@localhost:5432/db\" \\\n  --oauth-enabled \\\n  --oauth-issuer http://localhost:8080/realms/postgres-mcp \\\n  --oauth-audience postgres-mcp-client\n```\n\n\u003e **Additional flags:** `--oauth-jwks-uri \u003curl\u003e` (auto-discovered if omitted), `--oauth-clock-tolerance \u003cseconds\u003e` (default: 60).\n\n### OAuth Scopes\n\nAccess control is managed through OAuth scopes:\n\n| Scope                    | Access Level                        |\n| ------------------------ | ----------------------------------- |\n| `read`                   | Read-only queries (SELECT, EXPLAIN) |\n| `write`                  | Read + write operations             |\n| `admin`                  | Full administrative access          |\n| `full`                   | Grants all access                   |\n| `db:{name}`              | Access to specific database         |\n| `schema:{name}`          | Access to specific schema           |\n| `table:{schema}:{table}` | Access to specific table            |\n\n### RFC Compliance\n\nThis implementation follows:\n\n- **RFC 9728** — OAuth 2.1 Protected Resource Metadata\n- **RFC 8414** — OAuth 2.1 Authorization Server Metadata\n- **RFC 7591** — OAuth 2.1 Dynamic Client Registration\n\nThe server exposes metadata at `/.well-known/oauth-protected-resource`.\n\n\u003e **Note for Keycloak users:** Add an **Audience mapper** to your client (Client → Client scopes → dedicated scope → Add mapper → Audience) to include the correct `aud` claim in tokens.\n\n\u003e [!NOTE]\n\u003e **Per-tool scope enforcement:** Scopes are enforced at the tool level — each tool group maps to a required scope (`read`, `write`, or `admin`). When OAuth is enabled, every tool invocation checks the calling token's scopes before execution. When OAuth is not configured, scope checks are skipped entirely.\n\n\u003e [!WARNING]\n\u003e **HTTP without authentication:** When using `--transport http` without enabling OAuth or `--auth-token`, all clients have full unrestricted access. Always enable authentication for production HTTP deployments. See [SECURITY.md](SECURITY.md) for details.\n\n\u003e **Priority:** When both `--auth-token` and `--oauth-enabled` are set, OAuth 2.1 takes precedence. If neither is configured, the server warns and runs without authentication.\n\n## 🔧 Configuration\n\n### Environment Variables\n\n| Variable                     | Default     | Description                                                     | CLI Flag                       |\n| ---------------------------- | ----------- | --------------------------------------------------------------- | ------------------------------ |\n| `POSTGRES_HOST`              | `localhost` | Database host                                                   | `--host`                       |\n| `POSTGRES_PORT`              | `5432`      | Database port                                                   | `--pg-port`                    |\n| `POSTGRES_USER`              | `postgres`  | Database username                                               | `--user`                       |\n| `POSTGRES_PASSWORD`          | _(empty)_   | Database password                                               | `--password`                   |\n| `POSTGRES_DATABASE`          | `postgres`  | Database name                                                   | `--database`                   |\n| `POSTGRES_URL`               | —           | Connection string (overrides individual vars)                   | `--postgres`                   |\n| `MCP_HOST`                   | `localhost` | Server bind host (`0.0.0.0` for containers)                     | `--server-host`                |\n| `MCP_TRANSPORT`              | `stdio`     | Transport type: `stdio`, `http`, `sse`                          | `--transport`                  |\n| `PORT`                       | `3000`      | HTTP port for http/sse transports                               | `--port`                       |\n| `MCP_AUTH_TOKEN`             | —           | Simple bearer token for HTTP auth                               | `--auth-token`                 |\n| `LOG_LEVEL`                  | `info`      | Log level: `debug`, `info`, `warning`, `error`                  | `--log-level`                  |\n| `METADATA_CACHE_TTL_MS`      | `30000`     | Schema cache TTL (ms)                                           | —                              |\n| `POSTGRES_TOOL_FILTER`       | —           | Tool filter string (also `MCP_TOOL_FILTER`)                     | `--tool-filter`                |\n| `MCP_RATE_LIMIT_MAX`         | `100`       | Rate limit per IP per 15min window                              | —                              |\n| `MCP_REQUEST_TIMEOUT`        | `300000`    | HTTP request timeout (ms) for Slowloris protection              | —                              |\n| `MCP_HEADERS_TIMEOUT`        | `60000`     | HTTP headers timeout (ms)                                       | —                              |\n| `TRUST_PROXY`                | `false`     | Trust X-Forwarded-For for client IP                             | `--trust-proxy`                |\n| `OAUTH_ENABLED`              | `false`     | Enable OAuth 2.1 authentication                                 | `--oauth-enabled`              |\n| `OAUTH_ISSUER`               | —           | Authorization server URL                                        | `--oauth-issuer`               |\n| `OAUTH_AUDIENCE`             | —           | Expected token audience                                         | `--oauth-audience`             |\n| `OAUTH_JWKS_URI`             | _(auto)_    | JWKS URI (auto-discovered from issuer)                          | `--oauth-jwks-uri`             |\n| `OAUTH_CLOCK_TOLERANCE`      | `60`        | Clock tolerance in seconds                                      | `--oauth-clock-tolerance`      |\n| `AUDIT_LOG_PATH`             | —           | Audit log file path (`stderr` for container logs)               | `--audit-log`                  |\n| `AUDIT_REDACT`               | `false`     | Omit tool arguments from audit entries                          | `--audit-redact`               |\n| `AUDIT_BACKUP`               | `false`     | Enable pre-mutation DDL snapshots                               | `--audit-backup`               |\n| `AUDIT_BACKUP_DATA`          | `false`     | Include sample data rows in snapshots                           | `--audit-backup-data`          |\n| `AUDIT_BACKUP_MAX_AGE`       | `30`        | Maximum snapshot age in days                                    | `--audit-backup-max-age`       |\n| `AUDIT_BACKUP_MAX_COUNT`     | `1000`      | Maximum number of snapshots to retain                           | `--audit-backup-max-count`     |\n| `AUDIT_BACKUP_MAX_DATA_SIZE` | `52428800`  | Maximum table size for data capture (bytes)                     | `--audit-backup-max-data-size` |\n| `AUDIT_READS`                | `false`     | Log read-scoped tool calls (compact entries)                    | `--audit-reads`                |\n| `AUDIT_LOG_MAX_SIZE`         | `10485760`  | Max log file size before rotation (bytes). Keeps up to 5 files. | `--audit-log-max-size`         |\n\n\u003e **Aliases:** `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` are also supported (standard PostgreSQL client env vars).\n\n\u003e **Pool Tuning for IAM Auth:** For cloud-managed databases with IAM authentication (e.g., AWS RDS, Google Cloud SQL), use `--pool-max` to control pool size.\n\n### CLI Reference\n\n| Flag                                   | Description                                                                                                                                       |\n| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `--postgres \u003curl\u003e`                     | Connection string                                                                                                                                 |\n| `--host \u003chost\u003e`                        | PostgreSQL host                                                                                                                                   |\n| `--pg-port \u003cport\u003e`                     | PostgreSQL port                                                                                                                                   |\n| `--user \u003cuser\u003e`                        | Username                                                                                                                                          |\n| `--password \u003cpw\u003e`                      | Password (prefer `PGPASSWORD`)                                                                                                                    |\n| `--database \u003cdb\u003e`                      | Database name                                                                                                                                     |\n| `--ssl`                                | Enable SSL                                                                                                                                        |\n| `--pool-max \u003cn\u003e`                       | Max pool connections (default: 10)                                                                                                                |\n| `--transport \u003ctype\u003e`                   | `stdio` \\| `http` \\| `sse`                                                                                                                        |\n| `--port \u003cn\u003e`                           | HTTP port                                                                                                                                         |\n| `--server-host \u003chost\u003e`                 | Server bind host                                                                                                                                  |\n| `--auth-token \u003ctoken\u003e`                 | Simple bearer token for HTTP auth                                                                                                                 |\n| `--stateless`                          | Stateless HTTP mode (no sessions, no SSE)                                                                                                         |\n| `--tool-filter \u003cfilter\u003e`               | Tool filter string                                                                                                                                |\n| `--log-level \u003clevel\u003e`                  | Log verbosity                                                                                                                                     |\n| `--oauth-enabled`                      | Enable OAuth 2.1                                                                                                                                  |\n| `--trust-proxy`                        | Trust reverse proxy headers                                                                                                                       |\n| `--audit-log \u003cpath\u003e`                   | Enable JSONL audit trail (`stderr` for container logs)                                                                                            |\n| `--audit-redact`                       | Omit tool arguments from audit entries                                                                                                            |\n| `--audit-backup`                       | Enable pre-mutation DDL snapshots                                                                                                                 |\n| `--audit-backup-data`                  | Include sample data rows in snapshots                                                                                                             |\n| `--audit-backup-max-age \u003cdays\u003e`        | Maximum snapshot age in days (default: 30)                                                                                                        |\n| `--audit-backup-max-count \u003ccount\u003e`     | Maximum number of snapshots to retain (default: 1000)                                                                                             |\n| `--audit-backup-max-data-size \u003cbytes\u003e` | Maximum table size for data capture (default: 52428800)                                                                                           |\n| `--audit-reads`                        | Log read-scoped tool calls (compact entries)                                                                                                      |\n| `--audit-log-max-size \u003cbytes\u003e`         | Max log file size before rotation (default: 10MB). System retains up to 5 rotated historical archives before oldest deletion (`.1` through `.5`). |\n\n## 🤖 AI-Powered Prompts\n\nPrompts provide step-by-step guidance for complex database tasks. Instead of figuring out which tools to use and in what order, simply invoke a prompt and follow its workflow — great for learning PostgreSQL best practices or automating repetitive DBA tasks.\n\nThis server includes **20 intelligent prompts** for guided workflows:\n\n| Prompt                     | Description                                        | Required Groups               |\n| -------------------------- | -------------------------------------------------- | ----------------------------- |\n| `pg_query_builder`         | Construct queries with CTEs and window functions   | core                          |\n| `pg_schema_design`         | Design schemas with constraints and indexes        | core                          |\n| `pg_performance_analysis`  | Analyze queries with EXPLAIN and optimization      | core, performance             |\n| `pg_migration`             | Generate migration scripts with rollback support   | core                          |\n| `pg_tool_index`            | Lazy hydration - compact index of all tools        | —                             |\n| `pg_quick_query`           | Quick SQL query guidance for common operations     | core                          |\n| `pg_quick_schema`          | Quick reference for exploring database schema      | core                          |\n| `pg_database_health_check` | Comprehensive database health assessment           | core, performance, monitoring |\n| `pg_backup_strategy`       | Enterprise backup planning with RTO/RPO            | core, monitoring, backup      |\n| `pg_index_tuning`          | Index analysis and optimization workflow           | core, performance             |\n| `pg_extension_setup`       | Extension installation and configuration guide     | core                          |\n| `pg_setup_pgvector`        | Complete pgvector setup for semantic search        | core, vector                  |\n| `pg_setup_postgis`         | Complete PostGIS setup for geospatial operations   | core, postgis                 |\n| `pg_setup_pgcron`          | Complete pg_cron setup for job scheduling          | core                          |\n| `pg_setup_partman`         | Complete pg_partman setup for partition management | core, partman                 |\n| `pg_setup_kcache`          | Complete pg_stat_kcache setup for OS monitoring    | core, kcache                  |\n| `pg_setup_citext`          | Complete citext setup for case-insensitive text    | core, citext                  |\n| `pg_setup_ltree`           | Complete ltree setup for hierarchical data         | core, ltree                   |\n| `pg_setup_pgcrypto`        | Complete pgcrypto setup for cryptographic funcs    | core, pgcrypto                |\n| `pg_safe_restore_workflow` | 6-step safe restore playbook with `restoreAs`      | backup                        |\n\n## 📦 Resources\n\nResources give you instant snapshots of database state without writing queries. Perfect for quickly checking schema, health, or performance metrics — the AI can read these to understand your database context before suggesting changes.\n\nThis server provides **23 resources** for structured data access:\n\n| Resource     | URI                       | Description                                        |\n| ------------ | ------------------------- | -------------------------------------------------- |\n| Schema       | `postgres://schema`       | Full database schema                               |\n| Tables       | `postgres://tables`       | Table listing with sizes                           |\n| Settings     | `postgres://settings`     | PostgreSQL configuration                           |\n| Statistics   | `postgres://stats`        | Database statistics with stale detection           |\n| Activity     | `postgres://activity`     | Current connections                                |\n| Pool         | `postgres://pool`         | Connection pool status                             |\n| Capabilities | `postgres://capabilities` | Server version, extensions, tool categories        |\n| Performance  | `postgres://performance`  | pg_stat_statements query metrics                   |\n| Health       | `postgres://health`       | Comprehensive database health status               |\n| Extensions   | `postgres://extensions`   | Extension inventory with recommendations           |\n| Indexes      | `postgres://indexes`      | Index usage with unused detection                  |\n| Replication  | `postgres://replication`  | Replication status and lag monitoring              |\n| Vacuum       | `postgres://vacuum`       | Vacuum stats and wraparound warnings               |\n| Locks        | `postgres://locks`        | Lock contention detection                          |\n| Cron         | `postgres://cron`         | pg_cron job status and execution history           |\n| Partman      | `postgres://partman`      | pg_partman partition configuration and health      |\n| Kcache       | `postgres://kcache`       | pg_stat_kcache CPU/I/O metrics summary             |\n| Vector       | `postgres://vector`       | pgvector columns, indexes, and recommendations     |\n| PostGIS      | `postgres://postgis`      | PostGIS spatial columns and index status           |\n| Crypto       | `postgres://crypto`       | pgcrypto availability and security recommendations |\n| Insights     | `postgres://insights`     | AI-appended business insights and observations     |\n| Audit        | `postgres://audit`        | Audit trail with token summary and top tools       |\n| Help         | `postgres://help/{group}` | Group-specific help and workflow documentation     |\n\n## 🔧 Extension Support\n\n| Extension            | Purpose                        | Tools                      |\n| -------------------- | ------------------------------ | -------------------------- |\n| `pg_stat_statements` | Query performance tracking     | `pg_stat_statements`       |\n| `pg_trgm`            | Text similarity                | `pg_trigram_similarity`    |\n| `fuzzystrmatch`      | Fuzzy matching                 | `pg_fuzzy_match`           |\n| `hypopg`             | Hypothetical indexes           | `pg_index_recommendations` |\n| `pgvector`           | Vector similarity search       | 16 vector tools            |\n| `PostGIS`            | Geospatial operations          | 15 postgis tools           |\n| `pg_cron`            | Job scheduling                 | 8 cron tools               |\n| `pg_partman`         | Automated partition management | 10 partman tools           |\n| `pg_stat_kcache`     | OS-level CPU/memory/I/O stats  | 7 kcache tools             |\n| `citext`             | Case-insensitive text          | 6 citext tools             |\n| `ltree`              | Hierarchical tree labels       | 8 ltree tools              |\n| `pgcrypto`           | Hashing, encryption, UUIDs     | 9 pgcrypto tools           |\n\n\u003e Extension tools gracefully handle cases where extensions are not installed. Extension tool counts include `create_extension` helpers but exclude Code Mode; the [Tool Groups](#-tool-filtering) table above adds +1 per group for Code Mode.\n\n## Contributing\n\nContributions are welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a pull request.\n\n## Security\n\nFor security concerns, please see our [Security Policy](SECURITY.md).\n\n\u003e **⚠️ Never commit credentials** - Store secrets in environment variables\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Code of Conduct\n\nPlease read our [Code of Conduct](CODE_OF_CONDUCT.md) before participating in this project.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneverinfamous%2Fpostgres-mcp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fneverinfamous%2Fpostgres-mcp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneverinfamous%2Fpostgres-mcp/lists"}