Skip to main content
Glama
PostgreSQL MCP Server

PostgreSQL MCP Server

by foxter-io

postgresql-mcp-server – MCP Server for PostgreSQL

Node.js TypeScript PostgreSQL Docker MCP License

Full-featured MCP (Model Context Protocol) server that exposes 36 tools for interacting with PostgreSQL databases. Covers schema introspection, query execution, data exploration, performance monitoring, security auditing, and maintenance — all accessible from Claude Code, Claude Desktop, Cursor, and any MCP-compatible client.


Table of Contents


Related MCP server: postgres-mcp

Features

  • 36 tools across 6 domains: schema, queries, data, monitoring, security, maintenance

  • Dual transport: HTTP (Docker/remote) and stdio (local subprocess)

  • Read-only enforcement: pg_query rejects non-SELECT statements at the application level

  • Destructive-op guards: DROP, TRUNCATE, DELETE-without-WHERE require explicit confirm_destructive: true

  • Pagination + truncation: all list tools respect limit/offset; responses capped at 25,000 chars

  • Dual output formats: every tool supports response_format: markdown (default) or json

  • Demo schema: first-run seed with users, products, orders, triggers, views, and indexes


Requirements

  • Docker + Docker Compose (recommended) — or Node.js 20+ for local run

  • PostgreSQL 13+ (16 included in Docker setup)

  • An MCP-compatible client (Claude Code, Claude Desktop, Cursor…)


Quick Start (Docker)

# 1. Clone / enter project
cd mcp-postgresql

# 2. Start PostgreSQL + MCP server
docker compose up -d

# 3. Verify both containers are healthy
docker compose ps

Default ports:

Service

Port

Description

PostgreSQL

5432

Exposed to host for direct psql access

MCP HTTP server

3002

MCP endpoint at http://localhost:3002/mcp

Default credentials

Host:     localhost:5432
Database: mcpdb
User:     mcpuser
Password: mcppassword

Override via .env:

POSTGRES_USER=myuser
POSTGRES_PASSWORD=mysecret
POSTGRES_DB=mydb
PG_PORT=5432
MCP_PORT=3002

Demo schema

On first start, init/01_demo_schema.sql is executed automatically, creating:

  • Tables: users, products, orders, order_items, audit_log

  • Views: active_users, order_summary

  • Function + triggers: update_updated_at()

  • 7 indexes, seed data (5 users, 5 products)

  • Extensions: uuid-ossp, pg_stat_statements


Configuration

Environment variables

Variable

Default

Description

DATABASE_URL

—

Full connection string (overrides all PG_* vars)

PG_HOST

localhost

PostgreSQL host

PG_PORT

5432

PostgreSQL port

PG_DATABASE

postgres

Database name

PG_USER

postgres

PostgreSQL user

PG_PASSWORD

—

PostgreSQL password

TRANSPORT

stdio

stdio or http

PORT

3000

HTTP server port (when TRANSPORT=http)

HOST

127.0.0.1

HTTP bind address (0.0.0.0 in Docker)


Tools Reference

Schema Introspection

Tool

Description

pg_list_databases

All databases with encoding and size

pg_list_schemas

Schemas with owner, table/view counts

pg_list_tables

Tables in schema with size and estimated row count

pg_describe_table

Full table description: columns, FK, indexes, check constraints

pg_list_views

Views and materialized views with optional SQL definitions

pg_list_functions

Functions, procedures, aggregates, window functions

pg_list_indexes

Indexes by schema/table with size and definition

pg_list_extensions

Installed PostgreSQL extensions

pg_list_sequences

Sequences with range, increment, and current value

pg_list_triggers

Triggers per table with timing and event

pg_list_types

Enums, composite types, domains, range types

pg_list_partitions

Partitioned tables and their child partitions

pg_search_objects

Search all DB objects by LIKE pattern across all types

pg_get_ddl

CREATE statement (DDL) for table, view, function, or index

Query Execution

Tool

Description

pg_query

Execute a SELECT query (rejects any non-read-only statement)

pg_explain

EXPLAIN or EXPLAIN ANALYZE with text or JSON output

pg_execute

Execute DML/DDL: INSERT, UPDATE, DELETE, CREATE, ALTER, DROP

pg_transaction

Execute multiple statements atomically in a single transaction

Data Exploration

Tool

Description

pg_sample_rows

Sample rows from a table with optional WHERE, ORDER BY, column filter

pg_count_rows

Exact COUNT(*) with optional WHERE clause

pg_copy_csv

Export query results as CSV with header row

pg_table_stats

Size, live/dead rows, vacuum dates, scan counts per table

Monitoring & Performance

Tool

Description

pg_active_queries

Currently running queries with duration and wait events

pg_slow_queries

Slow query analysis from pg_stat_statements (mean/total time, cache hit %)

pg_index_usage

Index scan counts — identify unused or underused indexes

pg_bloat_report

Tables with high dead-tuple ratios needing VACUUM

pg_list_locks

Active locks with blocking pair detection

pg_replication_status

Streaming replica status and replay lag

pg_connection_stats

Connection summary grouped by database, user, app, or state

Security & Access Control

Tool

Description

pg_list_roles

All roles with attributes: superuser, login, replication, bypassRLS, memberships

pg_list_grants

Privileges on tables, views, sequences, functions

pg_list_policies

Row Level Security policies and RLS-enabled tables

pg_kill_query

Cancel (SIGINT) or terminate (SIGTERM) a backend by PID

Maintenance & Configuration

Tool

Description

pg_server_info

Server version, uptime, connection counts, key settings

pg_list_settings

pg_settings filtered by name/category; shows source and pending restarts

pg_vacuum

Run VACUUM, VACUUM ANALYZE, or VACUUM FULL on a table


Client Setup

Claude Code

# Register via HTTP (Docker must be running)
claude mcp add --transport http postgresql-mcp-server http://localhost:3002/mcp

Claude Desktop

Claude Desktop requires stdio transport. Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "postgresql": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-postgresql/dist/index.js"],
      "env": {
        "DATABASE_URL": "postgres://mcpuser:mcppassword@localhost:5432/mcpdb"
      }
    }
  }
}

Restart Claude Desktop after editing.

Cursor

Edit ~/.cursor/mcp.json (global) or .cursor/mcp.json (project-level):

{
  "mcpServers": {
    "postgresql": {
      "url": "http://localhost:3002/mcp"
    }
  }
}

Transport Modes

Mode

When to use

How to run

HTTP

Docker, remote servers, multiple clients

TRANSPORT=http docker compose up

stdio

Claude Desktop, local subprocess, single client

node dist/index.js (default)

DNS rebinding note: when running HTTP locally (outside Docker), the server binds to 127.0.0.1 by default. In Docker, set HOST=0.0.0.0 (already set in docker-compose.yml).


Development

# Install dependencies
npm install

# Build TypeScript
npm run build

# Run locally (stdio, connects to DATABASE_URL)
DATABASE_URL=postgres://user:pass@localhost:5432/mydb npm start

# Run as HTTP server
TRANSPORT=http PORT=3000 DATABASE_URL=... npm start

# Watch mode (dev)
DATABASE_URL=... npm run dev

Docker commands

# Start
docker compose up -d

# Stop (keep volumes)
docker compose down

# Stop and wipe database
docker compose down -v

# Rebuild after code changes
docker compose up --build -d

# Follow logs
docker compose logs -f mcp-server

Adding tools

  1. Create or edit a file in src/tools/

  2. Export a register*Tools(server: McpServer) function

  3. Import and call it in src/index.ts

  4. npm run build — TypeScript strict mode catches issues at compile time

  5. docker compose up --build -d to deploy


Project Structure

mcp-postgresql/
├── src/
│   ├── index.ts              # Entry point — registers all tools, starts transport
│   ├── constants.ts          # CHARACTER_LIMIT, defaults, ResponseFormat enum
│   ├── types.ts              # TypeScript interfaces for all DB result rows
│   ├── db.ts                 # pg.Pool, dbQuery, quoteIdentifier, validateIdentifier
│   ├── tools/
│   │   ├── schema.ts         # pg_list_databases/schemas/tables/views/functions/indexes/extensions/sequences/triggers/types/partitions/search/ddl/describe
│   │   ├── query.ts          # pg_query, pg_explain, pg_execute, pg_transaction
│   │   ├── data.ts           # pg_sample_rows, pg_count_rows, pg_table_stats, pg_copy_csv
│   │   ├── advanced.ts       # pg_server_info, pg_list_locks, pg_get_ddl
│   │   ├── monitoring.ts     # pg_active_queries, pg_slow_queries, pg_index_usage, pg_bloat_report, pg_replication_status
│   │   ├── security.ts       # pg_list_types/grants/policies/partitions, pg_copy_csv, pg_kill_query
│   │   └── maintenance.ts    # pg_list_roles, pg_list_settings, pg_vacuum, pg_connection_stats
│   └── utils/
│       ├── errors.ts         # PostgreSQL error formatting, isPgError type guard
│       └── format.ts         # formatMarkdownTable, truncateIfNeeded, formatBytes
├── init/
│   └── 01_demo_schema.sql    # Auto-loaded on first container start
├── dist/                     # Compiled JavaScript (gitignored)
├── Dockerfile                # Multi-stage: builder → runtime (node:20-alpine)
├── docker-compose.yml        # postgres:16-alpine + mcp-server
├── .env                      # Local overrides (not committed)
├── .dockerignore
├── package.json
└── tsconfig.json

Safety Model

Operation

Protection

SELECT via pg_query

Rejects INSERT/UPDATE/DELETE/DDL at app level

DROP / TRUNCATE

Requires confirm_destructive: true

DELETE without WHERE

Requires confirm_destructive: true

VACUUM FULL

Requires confirm_full: true (warns about exclusive lock)

pg_kill_query

Shows target query before acting; requires explicit mode

Identifier injection

validateIdentifier() + quoteIdentifier() on all dynamic table/schema names

Available Tools

36 tools
pg_active_queriesShow Active PostgreSQL QueriesA
Read-only

List all currently running queries in the database (excludes idle connections and the MCP server itself).

Args:

  • min_duration_seconds: Only show queries running longer than N seconds (default: 0 = all active)

  • include_idle_in_transaction: Include connections stuck in idle-in-transaction state (default: true)

  • response_format: Output format

Returns: JSON: { queries: ActiveQuery[], count: number } Markdown: table with PID, user, state, wait event, duration, query text

Useful for finding long-running queries, blocked transactions, and identifying performance bottlenecks.

Inputs: min_duration_seconds, include_idle_in_transaction, response_format.

pg_bloat_reportTable Bloat ReportA
Read-only

Identify tables with high dead-tuple ratios that need VACUUM or AUTOVACUUM attention.

Dead rows accumulate from UPDATE and DELETE operations. High dead% degrades query performance and wastes storage. Tables over ~20% dead tuples should be vacuumed.

Args:

  • schema: Filter to a specific schema (optional)

  • min_dead_pct: Minimum dead tuple % to include (default: 5)

  • min_dead_rows: Minimum absolute dead row count (default: 1000)

  • response_format: Output format

Returns: JSON: { tables: BloatInfo[], count: number } Markdown: table sorted by dead% descending, with last vacuum dates

Inputs: schema, min_dead_pct, min_dead_rows, response_format.

pg_connection_statsPostgreSQL Connection StatisticsA
Read-only

Show a summary of current connections grouped by database, user, application, and state.

Useful for monitoring connection pool utilization, finding idle connections, and detecting connection leaks from specific applications.

Args:

  • group_by: Group connections by 'database', 'user', 'application', or 'state' (default: state)

  • database: Filter to a specific database (optional)

  • response_format: Output format

Returns: JSON: { summary: ConnectionStat[], total_connections: number, max_connections: string, usage_pct: number } Markdown: grouped connection count with waiting and max idle age

Note: Excludes the MCP server's own backend connection from counts.

Inputs: group_by, database, response_format.

pg_copy_csvExport Query Results as CSVA
Read-only

Execute a SELECT query and return the results formatted as CSV with headers.

Args:

  • sql: SELECT statement to export (required — must be read-only)

  • limit: Maximum rows to export, 1-5000 (default: 1000)

  • delimiter: CSV field delimiter character (default: ',')

  • null_value: String to use for NULL values in CSV output (default: '')

Returns: CSV text with header row. Suitable for copy-paste into spreadsheets or piping to files.

Errors:

  • Rejected if non-SELECT statement provided

  • Returns error if query fails

Inputs: sql (required), limit, delimiter, null_value.

pg_count_rowsCount Rows in TableA
Read-only

Get exact row count for a table, optionally with a filter condition.

Args:

  • table: Table name (required)

  • schema: Schema name (default: public)

  • where_clause: Optional WHERE condition (without the WHERE keyword)

Returns: JSON: { table, schema, count, where_clause } Markdown: formatted count with filter info

Note: For large tables (>10M rows), pg_table_stats provides a faster estimated count.

Inputs: table (required), schema, where_clause.

pg_describe_tableDescribe PostgreSQL TableA
Read-onlyIdempotent

Full description of a table: columns, data types, constraints, indexes, and foreign keys.

Args:

  • table: Table name (required)

  • schema: Schema name (default: public)

  • response_format: Output format

Returns: JSON: { table, schema, columns: ColumnInfo[], foreign_keys: ForeignKeyInfo[], check_constraints, indexes: IndexInfo[] } Markdown: multi-section formatted description

Errors:

  • "Table not found" if table/schema doesn't exist

Inputs: table (required), schema, response_format.

pg_executeExecute SQL Statement (Write Operations)A
Destructive

Execute a non-SELECT SQL statement: INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, TRUNCATE, etc.

For DROP, TRUNCATE, or DELETE without a WHERE clause, you must set confirm_destructive: true to confirm you understand these operations are irreversible.

Args:

  • sql: SQL statement to execute (required)

  • confirm_destructive: Required for DROP/TRUNCATE/DELETE without WHERE (default: false)

  • timeout_ms: Statement timeout in milliseconds (default: 30000)

Returns: JSON: { command, rows_affected, duration_ms } Markdown: summary of executed statement

Examples:

  • INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')

  • UPDATE orders SET status = 'shipped' WHERE id = 42

  • CREATE INDEX idx_users_email ON users(email)

  • DROP TABLE temp_data (requires confirm_destructive: true)

Warning: Mutations are not automatically wrapped in a transaction. Use BEGIN/COMMIT explicitly for multi-statement transactions.

Inputs: sql (required), confirm_destructive, timeout_ms.

pg_explainExplain SQL Query PlanA
Read-only

Show the execution plan for a SQL query using EXPLAIN or EXPLAIN ANALYZE.

Use EXPLAIN to see the planned query strategy. Use EXPLAIN ANALYZE to actually execute the query and see real timing and row count statistics (costs real I/O).

Args:

  • sql: SQL query to explain (required, should be a SELECT)

  • analyze: Run EXPLAIN ANALYZE (executes the query, default: false)

  • buffers: Include buffer usage statistics — only with analyze:true (default: false)

  • format: Output format for the plan, 'text' or 'json' (default: text)

  • response_format: Response format

Returns: The query plan as text or JSON. Use 'json' format for programmatic parsing.

Warning: EXPLAIN ANALYZE actually executes the query, including any side effects.

Inputs: sql (required), analyze, buffers, format, +1 more.

pg_get_ddlGet DDL (CREATE statement) for a Database ObjectA
Read-onlyIdempotent

Get the CREATE statement (DDL) for a table, view, materialized view, function, or index.

Args:

  • object_name: Name of the object (required)

  • schema: Schema name (default: public)

  • object_type: Type of object: 'table', 'view', 'matview', 'function', 'index' (default: 'table')

Returns: JSON: { schema, object_name, object_type, ddl: string } Markdown: formatted SQL code block

Useful for understanding table structure, reproducing objects in other environments, or code review.

Inputs: object_name (required), schema, object_type.

pg_index_usageAnalyze Index Usage StatisticsA
Read-only

Show index scan counts and tuple statistics to identify unused or underused indexes.

Indexes with 0 scans that are not primary keys waste storage and slow writes — candidates for removal.

Args:

  • schema: Filter to a specific schema (optional)

  • min_table_size_mb: Only show indexes on tables larger than N MB (default: 0)

  • show_unused_only: Only show indexes with 0 scans (default: false)

  • response_format: Output format

Returns: JSON: { indexes: IndexUsage[], count: number } Markdown: table sorted by scan count ascending (least used first)

Note: Statistics reset on pg_stat_reset() or server restart. Low scans on a new server may not mean unused.

Inputs: schema, min_table_size_mb, show_unused_only, response_format.

pg_kill_queryCancel or Terminate a PostgreSQL BackendA
Destructive

Cancel or terminate a PostgreSQL backend process by PID.

Two modes:

  • cancel (safe): Sends SIGINT — cancels the current query but leaves the connection alive. The client can reconnect and retry.

  • terminate (forceful): Sends SIGTERM — kills the connection entirely. Use when cancel doesn't work.

Args:

  • pid: Process ID of the backend to cancel/terminate (from pg_active_queries or pg_list_locks)

  • mode: 'cancel' to cancel current query, 'terminate' to kill connection (default: cancel)

Returns: Whether the signal was successfully sent.

Note: You cannot cancel/terminate your own backend or superuser backends without superuser privileges.

Inputs: pid (required), mode.

pg_list_databasesList PostgreSQL DatabasesA
Read-onlyIdempotent

List all non-template databases accessible on the connected PostgreSQL server.

Returns database name, encoding, collation, size, and connection limit.

Returns: JSON: { databases: DatabaseInfo[], count: number } Markdown: formatted table

Errors:

  • "Cannot connect" if DATABASE_URL/PG_* env vars are wrong

Inputs: response_format.

pg_list_extensionsList Installed PostgreSQL ExtensionsA
Read-onlyIdempotent

List all extensions currently installed in the PostgreSQL database.

Returns extension name, installed version, default version, and description.

Returns: JSON: { extensions: ExtensionInfo[], count: number } Markdown: formatted table

Inputs: response_format.

pg_list_functionsList Functions and ProceduresA
Read-onlyIdempotent

List all user-defined functions, procedures, aggregates, and window functions in a schema.

Args:

  • schema: Schema name (default: public)

  • response_format: Output format

Returns: JSON: { functions: FunctionInfo[], count: number, schema: string } Markdown: formatted table with name, type, return type, arguments, language

Inputs: schema, response_format.

pg_list_grantsList Grants and PrivilegesA
Read-onlyIdempotent

Show all privileges granted on tables, views, sequences, and functions in a schema.

Args:

  • schema: Schema name (default: public)

  • object_name: Filter to a specific object (optional)

  • grantee: Filter by role/user name (optional)

  • response_format: Output format

Returns: JSON: { grants: GrantInfo[], count: number } Markdown: table with grantor, grantee, object, privilege type, and grantable flag

Useful for security audits and understanding who has access to what.

Inputs: schema, object_name, grantee, response_format.

pg_list_indexesList PostgreSQL IndexesA
Read-onlyIdempotent

List indexes in a schema, optionally filtered to a specific table.

Args:

  • schema: Schema name (default: public)

  • table: Filter to a specific table (optional)

  • response_format: Output format

Returns: JSON: { indexes: IndexInfo[], count: number } Markdown: formatted table with name, table, type, uniqueness, size, definition

Inputs: schema, table, response_format.

pg_list_locksList Current PostgreSQL LocksA
Read-only

Show currently active locks in the database, including waiting queries.

Useful for debugging lock contention, deadlocks, and long-running transactions.

Args:

  • include_granted: Include granted locks (not just waiting) — default: true

  • response_format: Output format

Returns: JSON: { locks: LockInfo[], blocking_pairs: [{blocker_pid, blocked_pid}] } Markdown: lock table with PID, query, lock type, relation, and wait status

Note: Requires sufficient privileges to view pg_stat_activity.

Inputs: include_granted, response_format.

pg_list_partitionsList Table PartitionsA
Read-onlyIdempotent

List all partitioned tables and their child partitions with bounds, size, and row estimates.

Args:

  • schema: Filter to a specific schema (optional)

  • parent_table: Filter to a specific partitioned table (optional)

  • response_format: Output format

Returns: JSON: { partitions: PartitionInfo[], parent_tables: string[] } Markdown: grouped by parent table, showing each partition's bounds and size

Inputs: schema, parent_table, response_format.

pg_list_policiesList Row Level Security PoliciesA
Read-onlyIdempotent

List all Row Level Security (RLS) policies in a schema, including USING and WITH CHECK expressions.

Args:

  • schema: Schema name (default: public)

  • table: Filter to a specific table (optional)

  • response_format: Output format

Returns: JSON: { policies: PolicyInfo[], count: number, rls_enabled_tables: string[] } Markdown: policy table with name, command, roles, permissive flag, and filter expressions

Note: Also shows which tables have RLS enabled even if no policies are defined.

Inputs: schema, table, response_format.

pg_list_rolesList PostgreSQL Roles and UsersA
Read-onlyIdempotent

List all PostgreSQL roles with their attributes, privileges, and group memberships.

Returns both login roles (users) and group roles. Shows superuser status, replication, login capability, connection limits, password expiry, and role membership graph.

Args:

  • login_only: Only show roles that can log in (actual users, not groups) (default: false)

  • response_format: Output format

Returns: JSON: { roles: RoleInfo[], count: number } Markdown: table with all role attributes + membership info

Useful for access audits, permission reviews, and understanding role hierarchy.

Inputs: login_only, response_format.

pg_list_schemasList PostgreSQL SchemasA
Read-onlyIdempotent

List all user-defined schemas in the current database (excludes pg_catalog, information_schema, pg_toast).

Returns schema name, owner, description, table count, and view count.

Returns: JSON: { schemas: SchemaInfo[], count: number } Markdown: formatted table

Inputs: response_format.

pg_list_sequencesList PostgreSQL SequencesA
Read-only

List all sequences in a schema with their configuration and current state.

Args:

  • schema: Schema name (default: public)

  • response_format: Output format

Returns: JSON: { sequences: SequenceInfo[], count: number } Markdown: table with name, type, range, increment, current value, and owning column

Note: last_value reflects the last allocated value, not necessarily the next one to be issued.

Inputs: schema, response_format.

pg_list_settingsQuery PostgreSQL Configuration SettingsA
Read-onlyIdempotent

Search and inspect PostgreSQL runtime settings from pg_settings.

Args:

  • name_pattern: ILIKE filter on setting name, e.g. "work_mem" or "%memory%" (optional)

  • category: Filter by category name, e.g. "Memory", "Connections and Authentication", "WAL" (optional)

  • modified_only: Only show settings that differ from their compiled default (default: false)

  • response_format: Output format

Returns: JSON: { settings: SettingInfo[], count: number } Markdown: table with name, current value, unit, source, context, description

Common categories: Memory, Connections and Authentication, WAL, Query Tuning, Autovacuum, Logging, Lock Management, Replication, Resource Usage.

Note: 'context' shows where the setting can be changed:

  • internal: read-only, compiled in

  • postmaster: requires server restart

  • sighup: reload only (pg_reload_conf())

  • user: changeable per-session

Inputs: name_pattern, category, modified_only, response_format.

pg_list_tablesList Tables in SchemaA
Read-onlyIdempotent

List all tables (and optionally views) in a PostgreSQL schema with size and row estimates.

Args:

  • schema: Schema name (default: public)

  • include_views: Also list views and materialized views (default: false)

  • response_format: Output format

Returns: JSON: { tables: TableInfo[], count: number, schema: string } Markdown: formatted table with size and row estimates

Note: estimated_rows is approximate (pg_class.reltuples) — use pg_count_rows for exact count.

Inputs: schema, include_views, response_format.

pg_list_triggersList PostgreSQL TriggersA
Read-onlyIdempotent

List all triggers in a schema, optionally filtered by table.

Args:

  • schema: Schema name (default: public)

  • table: Filter to a specific table (optional)

  • response_format: Output format

Returns: JSON: { triggers: TriggerInfo[], count: number } Markdown: table with trigger name, table, event, timing, orientation, and statement

Inputs: schema, table, response_format.

pg_list_typesList Custom PostgreSQL TypesA
Read-onlyIdempotent

List all user-defined types in a schema: enums, composite types, domains, and range types.

Args:

  • schema: Schema name (default: public)

  • type_category: Filter by 'enum', 'composite', 'domain', 'range', or 'all' (default: all)

  • response_format: Output format

Returns: JSON: { types: TypeInfo[], count: number } Markdown: table with type name, category, enum values (for enums), base type (for domains)

Examples:

  • Enum "order_status" → values: pending, confirmed, shipped, delivered, cancelled

  • Domain "positive_int" → base type: integer CHECK (VALUE > 0)

Inputs: schema, type_category, response_format.

pg_list_viewsList Views in SchemaA
Read-onlyIdempotent

List all views and materialized views in a PostgreSQL schema, including their definitions.

Args:

  • schema: Schema name (default: public)

  • include_definition: Include the SQL definition of each view (default: false)

  • response_format: Output format

Returns: JSON: { views: ViewInfo[], count: number, schema: string } Markdown: formatted table

Inputs: schema, include_definition, response_format.

pg_queryExecute Read-Only SQL QueryA
Read-only

Execute a read-only SQL SELECT query against the PostgreSQL database.

Only SELECT, WITH (CTE), TABLE, and EXPLAIN statements are allowed. Any attempt to execute INSERT, UPDATE, DELETE, DDL, or other mutating statements will be rejected.

Args:

  • sql: The SQL SELECT statement to execute (required)

  • limit: Maximum rows to return, 1-1000 (default: 100)

  • timeout_ms: Query timeout in milliseconds (default: 30000)

  • response_format: Output format

Returns: JSON: { rows: object[], row_count: number, column_names: string[] } Markdown: formatted table of results

Examples:

  • "SELECT * FROM users WHERE active = true" → rows with limit applied

  • "WITH stats AS (SELECT ...) SELECT * FROM stats" → CTE supported

  • "EXPLAIN SELECT * FROM orders" → query plan

Errors:

  • "Only read-only queries allowed" if non-SELECT statement attempted

  • PostgreSQL syntax/permission errors returned as-is

Inputs: sql (required), limit, timeout_ms, response_format.

pg_replication_statusShow Replication StatusA
Read-only

Show the status of all streaming replication standbys connected to this primary, including replay lag.

Only meaningful on a primary server with active streaming replication.

Returns: JSON: { replicas: ReplicaInfo[], is_standby: boolean, lsn: string } Markdown: replica table with address, state, lag size, sync state

Useful for monitoring replication health and identifying lagging standbys.

Inputs: response_format.

pg_sample_rowsGet Sample Rows from TableA
Read-only

Retrieve a sample of rows from a PostgreSQL table, with optional filtering and column selection.

Args:

  • table: Table name (required)

  • schema: Schema name (default: public)

  • limit: Number of rows to return, 1-500 (default: 10)

  • where_clause: Optional WHERE clause (without the WHERE keyword), e.g. "status = 'active'"

  • columns: Comma-separated column names to select (optional, default: all columns)

  • order_by: ORDER BY clause (without ORDER BY), e.g. "created_at DESC"

  • response_format: Output format

Returns: JSON: { table, schema, row_count, columns: string[], rows: object[] } Markdown: formatted table of results

Security: table and schema names are validated against actual database objects before use.

Inputs: table (required), schema, limit, where_clause, +3 more.

pg_search_objectsSearch Database Objects by NameA
Read-onlyIdempotent

Search across all database objects (tables, views, functions, indexes, sequences, constraints) by name pattern.

Args:

  • pattern: Case-insensitive name pattern, supports SQL LIKE wildcards: % (any chars), _ (one char) (required)

  • object_types: Filter by object type — 'table', 'view', 'function', 'index', 'sequence', 'constraint', 'trigger' (optional, searches all types by default)

  • schema: Limit search to a specific schema (optional)

  • response_format: Output format

Returns: JSON: { matches: SearchResult[], count: number } Markdown: grouped results by type

Examples:

  • pattern: "user%" → all objects starting with "user"

  • pattern: "%order%" → all objects containing "order"

  • pattern: "idx_%" with object_types: ["index"] → all indexes

Inputs: pattern (required), object_types, schema, response_format.

pg_server_infoGet PostgreSQL Server InformationA
Read-onlyIdempotent

Get detailed PostgreSQL server information: version, connection details, memory settings, WAL configuration, and runtime parameters.

Returns: JSON: { version, current_database, current_user, settings: {...}, uptime } Markdown: formatted multi-section report

Useful for understanding the server environment, verifying connection details, and checking key configuration values.

Inputs: response_format.

pg_slow_queriesShow Slow Queries from pg_stat_statementsA
Read-only

Analyze slow queries using the pg_stat_statements extension. Shows queries ranked by mean execution time.

Requires the pg_stat_statements extension to be installed and enabled.

Args:

  • limit: Number of queries to return (default: 20, max: 100)

  • min_calls: Only show queries called at least N times (default: 5)

  • order_by: Sort by 'mean_ms', 'total_ms', or 'calls' (default: mean_ms)

  • response_format: Output format

Returns: JSON: { queries: SlowQuery[], count: number } Markdown: table with calls, mean/total time, % of total, cache hit %, query text

Errors:

  • "pg_stat_statements extension not installed" if extension is missing

Inputs: limit, min_calls, order_by, response_format.

pg_table_statsGet Table StatisticsA
Read-onlyIdempotent

Get detailed statistics for tables: size, live/dead rows, vacuum/analyze info, scan counts.

Useful for identifying bloated tables, missing vacuums, or underused indexes.

Args:

  • schema: Filter to a specific schema (optional, shows all user schemas if omitted)

  • table: Filter to a specific table name (optional)

  • response_format: Output format

Returns: JSON: { stats: TableStats[], count: number } Markdown: formatted table with size, rows, vacuum dates, scan counts

Note: Requires pg_stat_user_tables access. Row counts are from pg_stat_user_tables (updated by autovacuum/analyze) — use pg_count_rows for exact counts.

Inputs: schema, table, response_format.

pg_transactionExecute Multiple Statements in a TransactionA
Destructive

Execute multiple SQL statements atomically in a single transaction.

All statements succeed or all are rolled back. Ideal for multi-step operations that must be atomic (e.g., insert + update, schema migrations).

Args:

  • statements: Array of SQL statements to execute in order (required)

  • confirm_destructive: Required if any statement is DROP/TRUNCATE/DELETE-without-WHERE

Returns: JSON: { results: [{command, rows_affected}], total_duration_ms, rolled_back: false } On error: { error, rolled_back: true, failed_at_index: number }

Examples: statements: ["INSERT INTO orders ...", "UPDATE inventory SET qty = qty - 1 WHERE ..."]

Inputs: statements (required), confirm_destructive, timeout_ms.

pg_vacuumRun VACUUM on a TableA
Idempotent

Execute VACUUM, VACUUM ANALYZE, or VACUUM FULL on a table to reclaim dead-tuple storage.

Modes:

  • standard: Reclaims dead-tuple space for reuse within the table (non-blocking)

  • analyze: VACUUM + updates query planner statistics (recommended for most cases)

  • full: Rewrites the table to reclaim disk space to OS — requires exclusive lock, very slow on large tables

Args:

  • table: Table name (required)

  • schema: Schema name (default: public)

  • mode: 'standard', 'analyze', or 'full' (default: analyze)

  • confirm_full: Required when mode is 'full' — acknowledges table will be locked

Returns: Duration and confirmation of completion.

Warning: VACUUM FULL acquires an exclusive lock — all queries on the table will block until it completes. Use during maintenance windows only.

Inputs: table (required), schema, mode, confirm_full.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 36 tools

    Disambiguation4/5

    Most tools have distinct purposes, but there is some overlap between pg_bloat_report and pg_table_stats, and between several list* tools. However, descriptions are clear enough to disambiguate.

    Naming Consistency5/5

    All tools use the 'pg_' prefix and follow a consistent snake_case pattern, with most using verb_noun or noun_noun, which is predictable and clear.

    Tool Count4/5

    36 tools is high, but each serves a specific purpose in database management, from querying to schema inspection and performance monitoring. The count is slightly over typical but well-scoped for the domain.

    Completeness5/5

    The tool set covers the full lifecycle of database interaction: read/write queries, schema exploration, performance analysis, maintenance tasks, and transaction management. No obvious gaps for a general-purpose PostgreSQL server.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Enables secure querying of PostgreSQL databases through MCP-compatible clients. Supports read-only SQL execution, table exploration, and connection management with built-in security validation.
      3
      49 npm
      9
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      MCP server with 14 tools for PostgreSQL database operations. Query databases, explore schemas, analyze tables, with SQL injection prevention and read-only mode by default.
      14
      12
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      A Python-based MCP server for interactive PostgreSQL data exploration, schema discovery, and safe SQL execution with support for stored procedures. It also enables automation through external HTTP API requests and local bash script execution on Fedora and Linux systems.
      19
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Provides PostgreSQL database management and analysis via MCP, enabling schema exploration, query execution, performance monitoring, and database health checks.
      36
      56 npm
      MIT