🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@neverinfamous/postgres-mcp

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@neverinfamous/postgres-mcp

PostgreSQL MCP server with connection pooling, tool filtering, and full extension support

Source
npmnpm
Version
2.0.0
Version published
Weekly downloads
108
4.85%
Maintainers
1
Weekly downloads
 
Created
Source

postgres-mcp

Last Updated March 2, 2026

PostgreSQL MCP Server enabling AI assistants (AntiGravity, Claude, Cursor, etc.) to interact with PostgreSQL databases through the Model Context Protocol. Features Code Mode — a revolutionary approach that provides access to all 227 tools through a single, secure JavaScript sandbox, eliminating the massive token overhead of multi-step tool calls. Also includes schema introspection and 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.

227 Specialized Tools · 20 Resources · 19 AI-Powered Prompts

GitHub GitHub Release Docker Pulls License: MIT MCP npm Security Status TypeScript Tests Coverage

Docker Hubnpm PackageMCP RegistryWikiChangelog

🎯 What Sets Us Apart

FeatureDescription
227 Specialized ToolsThe largest PostgreSQL tool collection for MCP — from core CRUD and native JSONB to pgvector, PostGIS, pg_cron, ltree, pgcrypto, introspection analysis, schema version tracking, and 8 extension ecosystems
20 Observability ResourcesReal-time schema, performance metrics, connection pool status, replication lag, vacuum stats, lock contention, and extension diagnostics
19 AI-Powered PromptsGuided workflows for query building, schema design, performance tuning, and extension setup
Code ModeMassive Token Savings: Execute complex, multi-step operations inside a fast, secure JavaScript sandbox. Instead of spending thousands of tokens on back-and-forth tool calls, Code Mode exposes all 227 capabilities locally, reducing token overhead by up to 90% and supercharging AI agent reasoning.
OAuth 2.1 + Access ControlEnterprise-ready security with RFC 9728/8414 compliance, granular scopes (read, write, admin, full, db:*, table:*:*), and Keycloak integration
Smart Tool Filtering21 tool groups + 16 shortcuts let you stay within IDE limits while exposing exactly what you need
HTTP Streaming TransportSSE-based streaming with /mcp, and /health endpoints for remote deployments
High-Performance PoolingBuilt-in connection pooling with health checks for efficient, concurrent database access
8 Extension EcosystemsFirst-class support for pgvector, PostGIS, pg_cron, pg_partman, pg_stat_kcache, citext, ltree, and pgcrypto
Introspection & Migration TrackingSimulate cascade impacts, generate safe DDL ordering, analyze constraint health, and track schema migrations with SHA-256 dedup — 12 agent-optimized tools that let AI assistants reason about schema changes before executing them
Deterministic Error HandlingEvery tool returns structured {success, error} responses — no raw exceptions, no silent failures, no misleading messages. Agents get actionable context instead of cryptic PostgreSQL codes
Production-Ready SecuritySQL injection protection, parameterized queries, input validation, sandboxed code execution, SSL certificate verification by default, and HTTP body size enforcement
Strict TypeScript100% type-safe codebase with 3176 tests and 93.58% coverage
MCP 2025-11-25 CompliantFull protocol support with tool safety hints, resource priorities, and progress notifications

🚀 Quick Start

Prerequisites

  • PostgreSQL 12-18 (tested with PostgreSQL 18.1)
  • Docker (recommended) or Node.js 24+ (LTS)
docker pull writenotenow/postgres-mcp:latest
{
  "mcpServers": {
    "postgres-mcp": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "-e",
        "POSTGRES_HOST",
        "-e",
        "POSTGRES_PORT",
        "-e",
        "POSTGRES_USER",
        "-e",
        "POSTGRES_PASSWORD",
        "-e",
        "POSTGRES_DATABASE",
        "writenotenow/postgres-mcp:latest",
        "--tool-filter",
        "starter"
      ],
      "env": {
        "POSTGRES_HOST": "host.docker.internal",
        "POSTGRES_PORT": "5432",
        "POSTGRES_USER": "your_username",
        "POSTGRES_PASSWORD": "your_password",
        "POSTGRES_DATABASE": "your_database"
      }
    }
  }
}

Note for Docker: Use host.docker.internal to connect to PostgreSQL running on your host machine.

📖 Full Docker guide: DOCKER_README.md · Docker Hub

npm

npm install -g @neverinfamous/postgres-mcp
postgres-mcp --transport stdio --postgres postgres://user:password@localhost:5432/database

From Source

git clone https://github.com/neverinfamous/postgres-mcp.git
cd postgres-mcp
npm install
npm run build
node dist/cli.js --transport stdio --postgres postgres://user:password@localhost:5432/database

Code Mode: Maximum Efficiency

Code Mode (pg_execute_code) dramatically reduces token usage (70–90%) and is included by default in all presets.

Code executes in a sandboxed VM context with multiple layers of security. All pg.* API calls execute against the database within the sandbox, providing:

  • Static code validation — blocked patterns include require(), process, eval(), and filesystem access
  • Rate limiting — 60 executions per minute per client
  • Hard timeouts — configurable execution limit (default 30s)
  • Full API access — all 20 tool groups are available via pg.* (e.g., pg.core.readQuery(), pg.jsonb.extract(), pg.introspection.dependencyGraph())
  • Requires admin OAuth scope — execution is logged for audit

⚡ Code Mode Only (Maximum Token Savings)

If you control your own setup, you can run with only Code Mode enabled — a single tool that provides access to all 227 tools' worth of capability through the pg.* API:

{
  "mcpServers": {
    "postgres-mcp": {
      "command": "node",
      "args": [
        "/path/to/postgres-mcp/dist/cli.js",
        "--transport",
        "stdio",
        "--tool-filter",
        "codemode"
      ],
      "env": {
        "POSTGRES_HOST": "localhost",
        "POSTGRES_PORT": "5432",
        "POSTGRES_USER": "your_user",
        "POSTGRES_PASSWORD": "your_password",
        "POSTGRES_DATABASE": "your_database"
      }
    }
  }
}

This exposes just pg_execute_code. The agent writes JavaScript against the typed pg.* SDK — composing queries, chaining operations across all 20 tool groups, and returning exactly the data it needs — in one execution. This mirrors the Code Mode pattern pioneered by Cloudflare for their entire API: fixed token cost regardless of how many capabilities exist.

[!TIP] Maximize Token Savings: Instruct your AI agent to prefer Code Mode over individual tool calls:

"When using postgres-mcp, prefer pg_execute_code (Code Mode) for multi-step database operations to minimize token usage."

For maximum savings, use --tool-filter codemode to run with Code Mode as your only tool. See the Code Mode wiki for full API documentation.

[!NOTE] AntiGravity Users: Server instructions are automatically sent to MCP clients during initialization. However, AntiGravity does not currently support MCP server instructions. For optimal Code Mode usage in AntiGravity, manually provide the contents of src/constants/ServerInstructions.ts to the agent in your prompt or user rules.

Disabling Code Mode (Non-Admin Users)

If you don't have admin access or prefer individual tool calls, exclude codemode:

{
  "args": ["--tool-filter", "starter,-codemode"]
}

📖 Full documentation: docs/CODE_MODE.md

Development

See From Source above for setup. After cloning:

npm run lint && npm run typecheck  # Run checks
npm run bench                      # Run performance benchmarks
node dist/cli.js info              # Test CLI
node dist/cli.js list-tools        # List available tools

Benchmarks

Run npm run bench to execute the performance benchmark suite (9 files, 75+ scenarios) powered by Vitest Bench. Benchmarks cover schema parsing, handler dispatch, identifier sanitization, auth middleware, connection pooling, Code Mode, logging, and more. Use npm run bench:verbose for detailed table output.

⚡ MCP Client Configuration

Cursor IDE / Claude Desktop

{
  "mcpServers": {
    "postgres-mcp": {
      "command": "node",
      "args": [
        "C:/path/to/postgres-mcp/dist/cli.js",
        "--postgres",
        "postgres://user:password@localhost:5432/database",
        "--tool-filter",
        "starter"
      ]
    }
  }
}

[!TIP] The starter shortcut provides 59 tools including Code Mode for token-efficient operations. All presets include Code Mode by default. See Tool Filtering to customize.

{
  "mcpServers": {
    "postgres-mcp": {
      "command": "node",
      "args": [
        "C:/path/to/postgres-mcp/dist/cli.js",
        "--tool-filter",
        "starter"
      ],
      "env": {
        "POSTGRES_HOST": "localhost",
        "POSTGRES_PORT": "5432",
        "POSTGRES_USER": "your_user",
        "POSTGRES_PASSWORD": "your_password",
        "POSTGRES_DATABASE": "your_database"
      }
    }
  }
}

🔗 Database Connection Scenarios

ScenarioHost to UseExample Connection String
PostgreSQL on host machinelocalhost or host.docker.internalpostgres://user:pass@localhost:5432/db
PostgreSQL in DockerContainer name or networkpostgres://user:pass@postgres-container:5432/db
Remote/Cloud PostgreSQLHostname or IPpostgres://user:pass@db.example.com:5432/db
ProviderExample Hostname
AWS RDS PostgreSQLyour-instance.xxxx.us-east-1.rds.amazonaws.com
Google Cloud SQLproject:region:instance (via Cloud SQL Proxy)
Azure PostgreSQLyour-server.postgres.database.azure.com
Supabasedb.xxxx.supabase.co
Neonep-xxx.us-east-1.aws.neon.tech

🛠️ Tool Filtering

[!IMPORTANT] AI IDEs like Cursor have tool limits. With 227 tools available, you MUST use tool filtering to stay within your IDE's limits. We recommend starter (59 tools) as a starting point. Code Mode is included in all presets by default for 70-90% token savings on multi-step operations.

What Can You Filter?

The --tool-filter argument accepts shortcuts, groups, or tool names — mix and match freely:

Filter PatternExampleToolsDescription
Shortcut onlystarter59Use a predefined bundle
Groups onlycore,jsonb,transactions47Combine individual groups
Shortcut + Groupstarter,+text72Extend a shortcut
Shortcut - Toolstarter,-pg_drop_table58Remove specific tools

All shortcuts and tool groups include Code Mode (pg_execute_code) by default for token-efficient operations. To exclude it, add -codemode to your filter: --tool-filter cron,pgcrypto,-codemode

Shortcuts (Predefined Bundles)

Tool counts include Code Mode (pg_execute_code) which is included in all presets by default.

ShortcutToolsUse CaseWhat's Included
starter59🌟 RecommendedCore, trans, JSONB, schema, codemode
essential47Minimal footprintCore, trans, JSONB, codemode
dev-schema52Dev Schema & MigrationsCore, trans, schema, introspection, codemode
dev-analytics42Dev AnalyticsCore, trans, stats, partitioning, codemode
ai-data60AI Data AnalystCore, JSONB, text, trans, codemode
ai-vector50AI/ML with pgvectorCore, vector, trans, part, codemode
dba-monitor59DBA MonitoringCore, monitoring, perf, trans, codemode
dba-schema45DBA Schema & MigrationsCore, schema, introspection, codemode
dba-infra46DBA InfrastructureCore, admin, backup, partitioning, codemode
dba-stats57DBA StatsCore, admin, monitoring, trans, stats, codemode
geo43Geospatial WorkloadsCore, PostGIS, trans, codemode
base-ops51Operations BlockAdmin, monitoring, backup, part, stats, citext, codemode
ext-ai26Extension: AI/Securitypgvector, pgcrypto, codemode
ext-geo24Extension: SpatialPostGIS, ltree, codemode
ext-schedule19Extension: Schedulingpg_cron, pg_partman, codemode
ext-perf28Extension: Perf/Analysispg_stat_kcache, performance, codemode

Tool Groups (21 Available)

Tool counts include Code Mode (pg_execute_code) which is added to all groups by default.

GroupToolsDescription
codemode1Code Mode (sandboxed code execution)
core21Read/write queries, tables, indexes, convenience/drop tools
transactions8BEGIN, COMMIT, ROLLBACK, savepoints
jsonb20JSONB manipulation and queries
text14Full-text search, fuzzy matching
performance21EXPLAIN, query analysis, optimization
admin11VACUUM, ANALYZE, REINDEX
monitoring12Database sizes, connections, status
backup10pg_dump, COPY, restore
schema13Schemas, views, sequences, functions, triggers
introspection13Dependency graphs, cascade simulation, migration tracking
partitioning7Native partition management
stats9Statistical analysis
vector17pgvector (AI/ML similarity search)
postgis16PostGIS (geospatial)
cron9pg_cron (job scheduling)
partman11pg_partman (auto-partitioning)
kcache8pg_stat_kcache (OS-level stats)
citext7citext (case-insensitive text)
ltree9ltree (hierarchical data)
pgcrypto10pgcrypto (encryption, UUIDs)

Add one of these configurations to your IDE's MCP settings file:

Option 1: Starter (59 Essential Tools)

Best for: General PostgreSQL database work - CRUD operations, JSONB, schema management.

{
  "mcpServers": {
    "postgres-mcp": {
      "command": "node",
      "args": [
        "/path/to/postgres-mcp/dist/cli.js",
        "--transport",
        "stdio",
        "--tool-filter",
        "starter"
      ],
      "env": {
        "POSTGRES_HOST": "localhost",
        "POSTGRES_PORT": "5432",
        "POSTGRES_USER": "your_username",
        "POSTGRES_PASSWORD": "your_password",
        "POSTGRES_DATABASE": "your_database"
      }
    }
  }
}

Option 2: AI Vector (50 Tools + pgvector)

Best for: AI/ML workloads with semantic search and vector similarity.

⚠️ Prerequisites: Requires pgvector extension installed in your PostgreSQL database.

{
  "mcpServers": {
    "postgres-mcp-ai": {
      "command": "node",
      "args": [
        "/path/to/postgres-mcp/dist/cli.js",
        "--transport",
        "stdio",
        "--tool-filter",
        "ai-vector"
      ],
      "env": {
        "POSTGRES_HOST": "localhost",
        "POSTGRES_PORT": "5432",
        "POSTGRES_USER": "your_username",
        "POSTGRES_PASSWORD": "your_password",
        "POSTGRES_DATABASE": "your_database"
      }
    }
  }
}

Customization Notes:

  • Replace /path/to/postgres-mcp/ with your actual installation path
  • Update credentials (your_username, your_password, etc.) with your PostgreSQL credentials
  • For Windows: Use forward slashes in paths (e.g., C:/postgres-mcp/dist/cli.js) or escape backslashes (C:\\postgres-mcp\\dist\\cli.js)
  • Extension tools gracefully handle cases where extensions are not installed

Syntax Reference

PrefixTargetExampleEffect
(none)ShortcutstarterWhitelist Mode: Enable ONLY this shortcut
(none)GroupcoreWhitelist Mode: Enable ONLY this group
+Group+vectorAdd tools from this group to current set
-Group-adminRemove tools in this group from current set
+Tool+pg_explainAdd one specific tool
-Tool-pg_drop_tableRemove one specific tool

Legacy Syntax (still supported): If you start with a negative filter (e.g., -base,-extensions), it assumes you want to start with all tools enabled and then subtract.

🔐 OAuth 2.1 Authentication

When using HTTP/SSE transport, oauth 2.1 authentication can protect your MCP endpoints.

Configuration

CLI Options:

node dist/cli.js \
  --transport http \
  --port 3000 \
  --postgres "postgres://user:pass@localhost:5432/db" \
  --oauth-enabled \
  --oauth-issuer http://localhost:8080/realms/postgres-mcp \
  --oauth-audience postgres-mcp-client

Environment Variables (Required):

OAUTH_ENABLED=true
OAUTH_ISSUER=http://localhost:8080/realms/postgres-mcp
OAUTH_AUDIENCE=postgres-mcp-client

Environment Variables (Optional — auto-discovered from issuer):

OAUTH_JWKS_URI=http://localhost:8080/realms/postgres-mcp/protocol/openid-connect/certs
OAUTH_CLOCK_TOLERANCE=60

OAuth Scopes

Access control is managed through OAuth scopes:

ScopeAccess Level
readRead-only queries (SELECT, EXPLAIN)
writeRead + write operations
adminFull administrative access
fullGrants all access
db:{name}Access to specific database
schema:{name}Access to specific schema
table:{schema}:{table}Access to specific table

RFC Compliance

This implementation follows:

  • RFC 9728 — OAuth 2.0 Protected Resource Metadata
  • RFC 8414 — OAuth 2.0 Authorization Server Metadata
  • RFC 7591 — OAuth 2.0 Dynamic Client Registration

The server exposes metadata at /.well-known/oauth-protected-resource.

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.

[!NOTE] 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.

⚡ Performance Tuning

VariableDefaultDescription
MCP_HOSTlocalhostServer bind host (0.0.0.0 for containers)
METADATA_CACHE_TTL_MS30000Cache TTL for schema metadata (milliseconds)
LOG_LEVELinfoLog verbosity: debug, info, warning, error

Tip: Lower METADATA_CACHE_TTL_MS for development (e.g., 5000), or increase it for production with stable schemas (e.g., 300000 = 5 min).

🤖 AI-Powered Prompts

Prompts 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.

This server includes 19 intelligent prompts for guided workflows:

PromptDescriptionRequired GroupsShortcut
pg_query_builderConstruct queries with CTEs and window functionscorestarter
pg_schema_designDesign schemas with constraints and indexescorestarter
pg_performance_analysisAnalyze queries with EXPLAIN and optimizationcore, performancedba-monitor
pg_migrationGenerate migration scripts with rollback supportcorestarter
pg_tool_indexLazy hydration - compact index of all toolsany
pg_quick_queryQuick SQL query guidance for common operationscorestarter
pg_quick_schemaQuick reference for exploring database schemacorestarter
pg_database_health_checkComprehensive database health assessmentcore, performance, monitoringdba-monitor
pg_backup_strategyEnterprise backup planning with RTO/RPOcore, monitoring, backupdba-infra
pg_index_tuningIndex analysis and optimization workflowcore, performancedba-monitor
pg_extension_setupExtension installation and configuration guidecorestarter
pg_setup_pgvectorComplete pgvector setup for semantic searchcore, vectorai-vector
pg_setup_postgisComplete PostGIS setup for geospatial operationscore, postgisgeo
pg_setup_pgcronComplete pg_cron setup for job schedulingcoreext-schedule
pg_setup_partmanComplete pg_partman setup for partition managementcore, partmanext-schedule
pg_setup_kcacheComplete pg_stat_kcache setup for OS monitoringcore, kcacheext-perf
pg_setup_citextComplete citext setup for case-insensitive textcore, citextbase-ops
pg_setup_ltreeComplete ltree setup for hierarchical datacore, ltreeext-geo
pg_setup_pgcryptoComplete pgcrypto setup for cryptographic funcscore, pgcryptoext-ai

📦 Resources

Resources 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.

This server provides 20 resources for structured data access:

ResourceURIDescription
Schemapostgres://schemaFull database schema
Tablespostgres://tablesTable listing with sizes
Settingspostgres://settingsPostgreSQL configuration
Statisticspostgres://statsDatabase statistics with stale detection
Activitypostgres://activityCurrent connections
Poolpostgres://poolConnection pool status
Capabilitiespostgres://capabilitiesServer version, extensions, tool categories
Performancepostgres://performancepg_stat_statements query metrics
Healthpostgres://healthComprehensive database health status
Extensionspostgres://extensionsExtension inventory with recommendations
Indexespostgres://indexesIndex usage with unused detection
Replicationpostgres://replicationReplication status and lag monitoring
Vacuumpostgres://vacuumVacuum stats and wraparound warnings
Lockspostgres://locksLock contention detection
Cronpostgres://cronpg_cron job status and execution history
Partmanpostgres://partmanpg_partman partition configuration and health
Kcachepostgres://kcachepg_stat_kcache CPU/I/O metrics summary
Vectorpostgres://vectorpgvector columns, indexes, and recommendations
PostGISpostgres://postgisPostGIS spatial columns and index status
Cryptopostgres://cryptopgcrypto availability and security recommendations

🔧 Extension Support

ExtensionPurposeTools
pg_stat_statementsQuery performance trackingpg_stat_statements
pg_trgmText similaritypg_trigram_similarity
fuzzystrmatchFuzzy matchingpg_fuzzy_match
hypopgHypothetical indexespg_index_recommendations
pgvectorVector similarity search16 vector tools
PostGISGeospatial operations15 postgis tools
pg_cronJob scheduling8 cron tools
pg_partmanAutomated partition management10 partman tools
pg_stat_kcacheOS-level CPU/memory/I/O stats7 kcache tools
citextCase-insensitive text6 citext tools
ltreeHierarchical tree labels8 ltree tools
pgcryptoHashing, encryption, UUIDs9 pgcrypto tools

Extension tools gracefully handle cases where extensions are not installed. Extension tool counts include create_extension helpers but exclude Code Mode; the Tool Groups table above adds +1 per group for Code Mode.

Contributing

Contributions are welcome! Please read our Contributing Guidelines before submitting a pull request.

Security

For security concerns, please see our Security Policy.

⚠️ Never commit credentials - Store secrets in environment variables

License

This project is licensed under the MIT License - see the LICENSE file for details.

Code of Conduct

Please read our Code of Conduct before participating in this project.

Keywords

postgresql

FAQs

Package last updated on 02 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts