MCP Hub
Back to servers

postgresql-mcp

A comprehensive PostgreSQL MCP server featuring 202 tools including a token-efficient Code Mode, supporting advanced extensions like pgvector, PostGIS, and pg_cron with enterprise-grade OAuth 2.1 security.

Stars
1
Tools
7
Updated
Jan 7, 2026
Validated
Jan 9, 2026

postgres-mcp

Last updated December 23, 2025

A PostgreSQL MCP Server that enables AI assistants (Claude, Cursor, etc.) to interact with PostgreSQL databases through the Model Context Protocol. Provides 202 specialized tools, 20 resources, and 19 AI-powered prompts and includes OAuth 2.1 authentication, code mode, connection pooling, tool filtering, plus support for citext, ltree, pgcrypto, pg_cron, pg_stat_kcache, pgvector, PostGIS, HypoPG, and advanced PostgreSQL features.

✅ Under Development - 202 tools, 20 resources, and 19 prompts.

GitHub License: MIT TypeScript MCP Tests Coverage


🚀 Quick Start

Prerequisites

  • Node.js 18+
  • PostgreSQL 12-18 (tested with PostgreSQL 18.1)
  • npm or yarn

Installation

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

Development

# Clone and install
git clone https://github.com/neverinfamous/postgres-mcp.git
cd postgres-mcp
npm install

# Build
npm run build

# Run checks
npm run lint && npm run typecheck

# Test CLI
node dist/cli.js info
node dist/cli.js list-tools

⚡ 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 58 tools including Code Mode for token-efficient operations. All presets include Code Mode by default. See Tool Filtering to customize.

Using Environment Variables (Recommended)

{
  "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

Code Mode: Maximum Efficiency

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

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"]
}

Isolation Modes

ModeIsolationWhen to Use
vmSame processDefault, recommended
workerSeparate V8 threadNot recommended (incomplete)

The vm mode is fully functional and is the default. No configuration needed.

Security

  • Requires admin OAuth scope
  • Blocked: require(), process, eval(), filesystem
  • Rate limited: 60 executions/minute

📖 Full documentation: docs/CODE_MODE.md


🛠️ Tool Filtering

[!IMPORTANT] AI IDEs like Cursor have tool limits. With 203 tools available, you MUST use tool filtering to stay within your IDE's limits. We recommend starter (58 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 onlystarter58Use a predefined bundle
Groups onlycore,jsonb,transactions45Combine individual groups
Shortcut + Groupstarter,+text69Extend a shortcut
Shortcut - Toolstarter,-pg_drop_table57Remove 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)

ShortcutToolsUse CaseWhat's Included
starter58🌟 RecommendedCore, trans, JSONB, schema, codemode
essential46Minimal footprintCore, trans, JSONB, codemode
dev-power53Power DeveloperCore, trans, schema, stats, part, codemode
ai-data59AI Data AnalystCore, JSONB, text, trans, codemode
ai-vector47AI/ML with pgvectorCore, vector, trans, part, codemode
dba-monitor58DBA MonitoringCore, monitoring, perf, trans, codemode
dba-manage57DBA ManagementCore, admin, backup, part, schema, codemode
dba-stats56DBA Stats/SecurityCore, admin, monitoring, trans, stats, codemode
geo42Geospatial WorkloadsCore, PostGIS, trans, codemode
base-core58Base Building BlockCore, JSONB, trans, schema, codemode
base-ops51Operations BlockAdmin, monitoring, backup, part, stats, citext, codemode
ext-ai24Extension: 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 (20 Available)

GroupToolsDescription
core20Read/write queries, tables, indexes, convenience/drop tools
transactions8BEGIN, COMMIT, ROLLBACK, savepoints
jsonb20JSONB manipulation and queries
text13Full-text search, fuzzy matching
performance20EXPLAIN, query analysis, optimization
admin11VACUUM, ANALYZE, REINDEX
monitoring12Database sizes, connections, status
backup10pg_dump, COPY, restore
schema13Schemas, views, sequences, functions, triggers
partitioning7Native partition management
stats9Statistical analysis
vector15pgvector (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)
codemode1Code Mode (sandboxed code execution)

Quick Start: Recommended IDE Configuration

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

Option 1: Starter (49 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 (46 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 \
  --oauth-enabled \
  --oauth-issuer http://localhost:8080/realms/db-mcp \
  --oauth-audience postgres-mcp

Environment Variables:

# Required
OAUTH_ENABLED=true
OAUTH_ISSUER=http://localhost:8080/realms/db-mcp
OAUTH_AUDIENCE=postgres-mcp

# Optional (auto-discovered from issuer)
OAUTH_JWKS_URI=http://localhost:8080/realms/db-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.


⚡ Performance Tuning

VariableDefaultDescription
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:

PromptDescription
pg_query_builderConstruct PostgreSQL queries with CTEs and window functions
pg_schema_designDesign normalized schemas with constraints and indexes
pg_performance_analysisAnalyze queries with EXPLAIN and optimization tips
pg_migrationGenerate migration scripts with rollback support
pg_tool_indexLazy hydration - compact index of all tools
pg_quick_queryQuick SQL query guidance for common operations
pg_quick_schemaQuick reference for exploring database schema
pg_database_health_checkComprehensive database health assessment
pg_backup_strategyEnterprise backup planning with RTO/RPO
pg_index_tuningIndex analysis and optimization workflow
pg_extension_setupExtension installation and configuration guide
pg_setup_pgvectorComplete pgvector setup for semantic search
pg_setup_postgisComplete PostGIS setup for geospatial operations
pg_setup_pgcronComplete pg_cron setup for job scheduling
pg_setup_partmanComplete pg_partman setup for partition management
pg_setup_kcacheComplete pg_stat_kcache setup for OS-level monitoring
pg_setup_citextComplete citext setup for case-insensitive text
pg_setup_ltreeComplete ltree setup for hierarchical data
pg_setup_pgcryptoComplete pgcrypto setup for cryptographic functions

📦 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 search14 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.


🏷️ Tool Annotations

All 199 tools include Tool Annotations (MCP SDK 1.25+), providing UX hints to MCP clients about tool behavior:

AnnotationDescriptionExample
titleHuman-readable tool name"Execute Query", "Create Index"
readOnlyHintTool doesn't modify datatrue for SELECT queries
destructiveHintTool may delete/modify datatrue for DROP, DELETE
idempotentHintSafe to retry without side effectstrue for IF NOT EXISTS
openWorldHintTool interacts with external systemsfalse for all tools

🔥 Core Capabilities

  • 📊 Full SQL Support - Execute any PostgreSQL query with parameter binding
  • 🔍 JSONB Operations - Native JSONB functions and path queries
  • 🔐 Connection Pooling - Efficient connection management with health checks
  • 🎛️ Tool Filtering - Control which operations are exposed
  • Performance Tools - EXPLAIN ANALYZE, buffer analysis, index hints
  • 🗺️ PostGIS Support - Geospatial queries and spatial indexes
  • 🧠 pgvector Support - AI/ML vector similarity search

🏢 Enterprise Features

  • 🔐 OAuth 2.1 Authentication - RFC 9728/8414 compliant
  • 🛡️ Tool Filtering - Control which database operations are exposed
  • 📈 Monitoring - Process lists, replication lag, cache hit ratios

🏆 Why Choose postgres-mcp?

TypeScript Native - Full type safety with strict mode
199 Specialized Tools - Comprehensive PostgreSQL coverage
Tool Annotations - UX hints for read-only, destructive, and idempotent operations
Connection Pooling - Efficient PostgreSQL connection management
Extension Support - pgvector, PostGIS, pg_stat_statements, pg_cron
Tool Filtering - Stay within AI IDE tool limits
Modern Architecture - Built on MCP SDK 1.25+


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.

Reviews

No reviews yet

Sign in to write a review