MCPg - Production-grade PostgreSQL MCP Server
Server Configuration
Describes the environment variables required to run the server.
| Name | Required | Description | Default |
|---|---|---|---|
| MCPG_DATABASE_URL | Yes | Primary PostgreSQL DSN. Supports URI (postgresql://...) and keyword (host=... user=...) forms. Remote hosts require sslmode=require (or stronger). |
Capabilities
Features and capabilities supported by this server
| Capability | Details |
|---|---|
| tools | {
"listChanged": false
} |
| prompts | {
"listChanged": false
} |
| resources | {
"subscribe": false,
"listChanged": false
} |
| experimental | {} |
Tools
Functions exposed to the LLM to take actions
| Name | Description |
|---|---|
| get_server_infoA | Return the MCPg server version, access mode, transport, database connection status, and PostgreSQL |
| describe_selfA | Return a high-level summary of what mcpg can do, organised into capability buckets (schema introspection, query execution, vector search, RAG telemetry, audit trail, migrations, time-series, etc.). Call this first when discovering mcpg's surface — it's much more compact than walking the full tool catalogue. Returns an object with |
| describe_toolA | Return the full registered schema for one MCP tool by name — |
| get_metrics_expositionA | Return the in-process Prometheus-format metrics for this MCPg server. Three series: mcpg_tool_calls_total (counter by tool / status), mcpg_tool_duration_seconds (histogram by tool with sum and count). Useful when the HTTP transport's /metrics endpoint is unreachable (e.g. running over stdio) or to fetch via the MCP protocol itself. |
| list_schemasA | List database schemas, excluding PostgreSQL's own schemas unless include_system is true. Returns a list of objects with Example: |
| list_tablesA | List the tables and views in a schema, flagging partitioned tables and partitions. Returns a list of objects with Example: |
| describe_tableA | Describe the columns of a table, in ordinal order. Returns a list of objects with Example: |
| list_indexesA | List the indexes defined on a table. Returns a list of objects with Example: |
| list_constraintsA | List a table's constraints — primary/foreign keys, unique, check, exclusion. Returns a list of objects with Example: |
| list_foreign_keysA | List foreign keys in a schema, resolved to columns and referenced table. Returns a list of objects with Example: |
| list_viewsA | List the views and materialized views in a schema, with their definitions. Returns a list of objects with |
| list_functionsA | List the functions and procedures defined in a schema. Returns a list of objects with |
| list_triggersA | List the user-defined triggers on a table. Returns a list of objects with |
| list_partitionsA | Describe how a table is partitioned (strategy and bounds) and list its partitions. Returns an object with |
| list_rolesA | List the database roles and their attributes, excluding PostgreSQL's own roles unless include_system is true. Returns a list of objects with |
| list_grantsA | List the privileges granted on a table — who may do what to it. Returns a list of objects with |
| list_policiesA | List the Row-Level-Security policies on a table, and whether row security is enabled. Returns an object with |
| list_sequencesA | List the sequences defined in a schema, with their range, increment, and last value. Returns a list of objects with |
| list_enumsA | List the enum types in a schema, with their labels in sort order. Returns a list of objects with |
| list_domainsA | List the domain types in a schema, with base type, default, and check constraints. Returns a list of objects with |
| list_composite_typesA | List the standalone composite types in a schema with their attributes. Returns a list of objects with |
| list_foreign_data_wrappersA | List the foreign-data wrappers installed in the database. Returns a list of objects with |
| list_foreign_serversA | List the foreign servers defined in the database, with their FDW and options. Returns a list of objects with |
| list_foreign_tablesA | List the foreign tables in a schema, with their server and options. Returns a list of objects with |
| list_user_mappingsA | List role-to-foreign-server mappings; the catch-all appears as user='public'. Returns a list of objects with |
| list_publicationsA | List logical-replication publications with the tables and operations they include. Returns a list of objects with |
| list_subscriptionsA | List logical-replication subscriptions; requires superuser to see any rows. |
| list_extensionsA | List the extensions installed in the database. Returns a list of objects with |
| list_available_extensionsA | List every extension available to the database, with whether it is installed. Returns a list of objects with |
| list_generated_columnsA | List every GENERATED ALWAYS AS (...) STORED column in a schema, with its data type, the underlying expression, and whether it's stored or virtual. PostgreSQL today supports only the stored form; the kind field is reported anyway so the response shape is forward-compatible when PG adds virtual columns. Returns a list of objects with |
| list_locksB | List currently-held and waiting locks, joined with backend state from pg_stat_activity. Ordered by (granted ASC, pid) so waiting locks float to the top. Returns lock type, mode, qualified relation name when applicable, transaction / virtualxid, the application_name + state + wait event of the owning backend, and the first 200 chars of its query. Read-only. |
| find_blocking_chainsA | Return (blocked, blocking) backend pairs via pg_blocking_pids. Each row pairs a backend waiting on a Lock with one PID holding the lock that's preventing progress. Cycles are possible (A blocks B, B blocks A); render with care. Read-only. |
| walk_blocking_chainsA | Walk and reconstruct the lock-wait graph of the database. Detects deadlock cycles, traces linear blocking paths to their root blockers, and renders a Mermaid flowchart representing the lock dependency graph. Read-only. Returns an object with |
| read_pg_stat_ioA | Read the pg_stat_io view (PostgreSQL 16+). Reports per (backend_type, object, context) cumulative I/O activity — reads, writes, extends, evictions, hits, fsyncs. Useful for spotting buffer-cache misses and write amplification. On PostgreSQL 14 / 15 the view doesn't exist, so the tool returns available=false and an empty list. |
| read_pg_buffercache_summaryA | Read a high-level summary of the PostgreSQL shared buffer cache usage. Reports total buffers, free/used buffers, dirty buffers, and average usage count. Requires the pg_buffercache extension. If not installed, returns available=false. |
| read_pg_buffercache_relationsA | Read the list of database relations taking up the most space in the PostgreSQL shared buffer cache. Reports buffered size, percentage of shared buffers, percent of relation buffered, average usage count, and dirty pages. Allows filtering by schema. Requires the pg_buffercache extension. If not installed, returns available=false. |
| read_pg_wal_recordsA | Read Write-Ahead Log (WAL) records information over a specified LSN range. Requires the pg_walinspect extension. If not installed, returns available=false. |
| read_pg_wal_statsA | Read Write-Ahead Log (WAL) record statistics over a specified LSN range, grouped by resource manager or record type. Requires the pg_walinspect extension. If not installed, returns available=false. |
| get_wal_archive_statusA | Report WAL-archiving health from Example: |
| check_pitr_readinessA | Assess whether the cluster is ready for point-in-time recovery (PITR) — the one-call 'could I actually recover to an arbitrary point right now, and if not what's missing?' check. Composes Example: |
| get_compact_schemaA | Return a highly condensed, token-efficient text summary of a schema's tables, columns, primary keys, nullability, and relations to save context window tokens. |
| read_migration_historyA | Query and summarize historical migrations applied to the database by popular migration frameworks (Alembic, Flyway, Diesel, Django, Prisma, Golang Migrate, Goose, Sequelize). Allows filtering by schema. Returns an object with one optional list per detected framework: |
| generate_schema_diagramA | Render a Mermaid ER diagram for a schema. Views and foreign tables are excluded; partitions are excluded by default — pass include_partitions=true to draw each partition as its own entity. Returns the Mermaid Example: |
| generate_fk_cascade_graphA | Build a Mermaid graph LR of foreign-key cascade chains in a schema. Each edge runs from the referencing table to the referenced table, labelled with the cascade action(s) on DELETE / UPDATE. By default only FKs with at least one CASCADE / SET NULL / SET DEFAULT action are included — those are the ones that produce a write blast radius. Pass include_all=true to include NO ACTION / RESTRICT FKs too (full FK topology view). Cross-schema FK targets are rendered as separate nodes prefixed with their schema. Returns the Mermaid |
| generate_schema_docsA | Generate a detailed Markdown reference of a schema's tables, columns, constraints, indexes, views, foreign tables, and custom enums along with comments / descriptions. Optional include_samples fetches a few distinct, non-null values for each column. Returns a single Markdown document as a string. Example: |
| compare_schemasA | Return the structural diff between two schemas — tables/columns/indexes/constraints/foreign-keys added, removed, or changed. Base tables only; views and custom types are not compared. Renames surface as a paired add + remove. Example: |
| tune_vector_indexA | Recommend an ivfflat or hnsw configuration for a pgvector column. Reads the live row count and column dimension, applies the standard pgvector heuristics, and returns the parameters plus a ready-to-run CREATE INDEX statement. Requires the vector extension. |
| vector_recall_at_kC | Measure recall@k of an existing pgvector index against a brute-force ground truth (function-form distance, which pgvector documents as non-indexed). Returns the mean overlap over a sample of rows from the table. Requires the vector extension. |
| migrate_vector_to_halfvecA | Generate a DDL plan that converts a pgvector vector(N) column to halfvec(N) — halving per-element storage (4 → 2 bytes) with typically negligible recall impact at d ≥ 768. Reads the column's current type + dimension from the catalog, finds every index on the column, and emits an ordered |
| analyze_hnsw_recallA | Sweeps ef_search values to measure the latency and recall trade-off curve for a given pgvector query vector against exact brute-force ground truth. Requires the vector extension. Returns a list of objects with |
| recommend_hnsw_ef_searchA | Recommend an Example: |
| recommend_ivfflat_probesA | Recommend an Example: |
| analyze_distance_metricA | Recommend a pgvector distance metric (cosine | l2 | inner_product) from the embedding-magnitude distribution. Samples up to |
| cross_table_similarityA | Find the k rows in target_schema.target_table most similar to a specific row in source_schema.source_table. Locates the source row via source_id_column = source_id_value, reads its embedding from source_embedding_column, then issues a pgvector k-NN query against target_embedding_column. Both columns must be vector(N) of the same N — verified from the catalog up front so a mismatch fails with a clear error rather than a cast error. Useful for entity-resolution / linking across tables whose embeddings come from different models but share a dimension. Returns source_embedding_found=false when no row matches the id value. Reports available=false if pgvector is not installed. |
| retrieve_with_contextA | Context-packed k-NN retrieval (a one-shot RAG building block). Runs a pgvector k-NN against schema.table.embedding_column for a caller-supplied Example: |
| cluster_vectorsA | k-means cluster a pgvector column. Samples up to Example: |
| detect_vector_outliersA | Flag pgvector rows whose embedding sits far from any cluster centroid. Samples up to |
| monitor_embedding_driftA | Compare two time windows of a pgvector column and flag distributional drift. Samples up to Example: |
| analyze_vector_search_efficiencyA | Cross-backend retrieval-quality report for a pgvector or pg_turboquant ANN index. Detects the backend (HNSW / IVFFlat / turboquant), sweeps the matching per-backend knob (ef_search / probes / candidate_limit) across a multiplier curve, computes recall@k vs a brute-force exact baseline, Spearman + Kendall rank correlation, per-query p50/p95 wall-clock latency, and (for turboquant) the page-pruning ratio from tq_last_scan_stats. Emits findings: |
| analyze_reranker_liftA | Per-query Spearman + Kendall correlation between bi-encoder and cross-encoder ranks, aggregated across queries in the window. Low correlation = the reranker is actively reordering (doing real work); high correlation = the reranker mostly confirms the bi-encoder order. Optional |
| analyze_topk_stabilityA | Jaccard overlap between top-K-by-bi-rank and top-K-by-cross-rank per query, aggregated. High mean Jaccard means the reranker isn't actually changing the top-K membership. Surfaces |
| analyze_rerank_score_distributionA | Equal-width histogram of cross_encoder_score values over the window plus the top-decile share. Surfaces |
| analyze_rerank_ndcgA | NDCG@k under bi-encoder ordering vs cross-encoder ordering, averaged across labeled queries ( |
| recommend_rerank_strategyC | Roll-up advisor over the four analytics for one window. Returns a single headline |
| recommend_efficiency_thresholdsA | Compute corpus-percentile thresholds from accumulated |
| generate_prisma_schemaA | Read a PostgreSQL schema and emit a valid Prisma |
| generate_drizzle_schemaA | Read a PostgreSQL schema and emit a Drizzle ORM TypeScript schema string (drizzle-orm/pg-core). Covers tables, columns with PG-native types, primary/foreign keys, unique constraints, indexes, defaults, and enums. Single-column FKs emit column-level .references(); composite FKs are a documented v1 gap. Views, foreign tables, partitions, triggers, and functions are out of scope. Returns the rendered TypeScript |
| generate_diesel_schemaA | Read a PostgreSQL schema and emit a Diesel ORM (Rust) schema.rs. One |
| generate_jooq_configA | Read a PostgreSQL schema and emit a jooq-codegen configuration XML pointing at it. Unlike the other exporters, jOOQ generates Java code itself from a live database — the artefact here is the configuration file the user feeds to mvn jooq-codegen:generate (or the Gradle task). The XML lists every base table explicitly via an regex, excludes MCPg's bookkeeping tables, and emits a for every json / jsonb column so they map to org.jooq.JSON / org.jooq.JSONB out of the box. Default Java package is com.example.jooq; override via the target_package arg. |
| generate_ent_schemasA | Read a PostgreSQL schema and emit Ent (Go) Schema struct files — one .go file per table. Each file exports a struct that lists field.X(...) calls for every column, edge.To(...) for single-column intra-schema FKs, and field.Enum().Values() for enum-typed columns. Composite FKs are a documented v1 gap. Returns a JSON object {filename: source} so the agent can write each file. |
| generate_ecto_schemasA | Read a PostgreSQL schema and emit Ecto (Elixir) schema modules — one .ex file per table, named after the singularised table. Each module uses Ecto.Schema with field declarations, belongs_to for single-column intra-schema FKs, and timestamps() when both inserted_at and updated_at exist. The Elixir top-level module is configurable via app_module (default MyApp). Returns a JSON object {filename: source} so the agent can write each file. |
| generate_sqlalchemy_modelsA | Read a PostgreSQL schema and emit a SQLAlchemy 2.0 declarative models file (DeclarativeBase + Mapped[T] + mapped_column). Covers tables, columns with PG-native types (incl. jsonb via sqlalchemy.dialects.postgresql.JSONB), primary keys, single-column FKs via ForeignKey(), unique constraints (column-level + composite via table_args), defaults, and enums (emitted as Python enum.Enum classes). Composite FKs are a documented v1 gap. Returns the rendered Python |
| generate_sqlc_schemaA | Read a PostgreSQL schema and emit a sqlc-friendly schema.sql (plain DDL). Order: CREATE SCHEMA, CREATE TYPE for each enum, CREATE TABLE statements (columns only), ALTER TABLE ADD CONSTRAINT (PK / unique / check / foreign key in that order), then CREATE INDEX for non-constraint indexes. The file replays cleanly against an empty database so FKs land after all referenced tables exist. In-process — no MCPG_ALLOW_SHELL needed. Returns the rendered |
| run_advisorsA | Run a set of catalog-driven advisor rules against a schema and return the aggregated findings. Rules cover missing primary keys, unindexed foreign keys, duplicate indexes, and nullable timestamps without time zone. Advisory only — no writes. |
| find_unused_objectsA | Find tables and indexes with zero scans since pg_stat was last reset — a strong signal of dead code, but NOT a verdict. Tables report seq+idx scan counts, write counts, and estimated row count; indexes report size and definition. Excludes PRIMARY KEY and UNIQUE indexes (PG needs those regardless of scans). Run this after the database has been hot for a meaningful period — fresh stats produce false positives. Returns an object with |
| find_sensitive_columnsA | Flag columns whose names or types look like they hold sensitive data (passwords, tokens, PII, financial info, health records). Pure heuristic — no row sampling, no value introspection. Categories: credential, financial, contact, identifier, health, government_id, location. Each finding carries a confidence (high / medium / low) so an agent can filter for a first review pass. Treat as a SIGNAL, not a verdict — a column named email_template_id matches the email pattern but isn't itself an email address. Returns an object with |
| lint_naming_conventionsA | Lint table / column / index naming in a schema. Detects the majority case style (snake_case / camelCase / PascalCase / SCREAMING_SNAKE) per schema and per table, then flags outliers. Also flags indexes whose names do not start with a conventional prefix (idx_, ix_, pk_, uq_, fk_ by default). Findings carry the offender's style and the detected majority — agents can use the style field to filter for renames vs accept-as-is. Pure read. Returns an object with |
| test_rls_for_roleA | Test what an RLS-bound role can read from a table. Reports whether RLS is enabled on the table, lists the policies that apply to the given role, counts the rows the role can read, and returns up to sample_size rows so the agent can inspect them. Runs as the target role inside a READ ONLY transaction — no writes can leak. Pure read. |
| generate_test_dataA | Generate synthetic INSERT statements for a table — typed values respecting column type, NOT NULL, and DEFAULT. Returns the SQL as strings; does NOT execute it. Useful for seeding dev / staging environments. The generator is deterministic when a seed is provided. Foreign keys are NOT resolved — the caller must pre-seed referenced rows or drop the FK before applying. Hard cap of 10000 rows per call. Pure read (the actual writes go through run_write under unrestricted mode). |
| generate_graph_projectionA | Generate openCypher CREATE/MERGE statements that project a relational schema into an Apache AGE property graph — rows become vertices (one label per table), foreign keys become edges. EMITS the Cypher for review; NEVER executes it (like Example: |
| generate_test_row_forA | Generate ONE realistic test row for a table — catalogue-aware. Skips identity / generated columns (server fills them in), samples one existing row from each referenced table for FK columns (so the row inserts cleanly), and uses column-name heuristics ( Example: |
| analyze_session_costA | Surface hot-path inefficiencies from the audit log. Reads Example: |
| recommend_headline_toolsA | Empirically curate Example: |
| audit_sequencesA | Flag sequences nearing their ceiling — serial / identity / explicit sequences whose Example: |
| audit_settingsA | Sanity-sweep Example: |
| recommend_postgres_confA | Compute pgtune-style Example: |
| optimize_queryA | Analyze a SQL query for syntax anti-patterns and performance issues using EXPLAIN plan costs and index scans, returning an optimized version. |
| summarize_tableA | Return a one-stop snapshot of a table: columns, primary key, foreign keys, every other constraint, indexes, storage + row-count + last-vacuum/analyze stats, and (optionally) a short sample of rows. Replaces what would otherwise be 4-5 individual tool calls. Set sample_rows=0 on wide / jsonb-heavy tables where the sample isn't useful. Example: |
| why_is_this_slowA | Diagnose why a SQL query might be slow, in one call. Runs EXPLAIN (FORMAT JSON) — does NOT execute the query — walks the plan tree, snapshots concurrent active queries + blocking lock pairs, reads the cluster-wide cache hit ratio, and produces categorised suggestions (plan / contention / cache / maintenance). Read-only; safe to run on a statement the agent doesn't want to materialise yet. Example: |
| export_queryA | Run a read-only SQL query and serialise its rows to CSV or JSON. Reuses the SQL-safety checks of run_select. Truncates at Example: |
| export_tableA | Serialise every row in schema.table (up to |
| list_audit_eventsA | List recent rows from mcpg_audit.events (newest first). Returns an empty list when MCPG_AUDIT_PERSIST has never been turned on (no audit table yet). Optionally filter by tool name. |
| verify_audit_chainA | Verify the HMAC-SHA256 signature chain of persisted audit events in mcpg_audit.events. Returns an object with |
| run_selectA | Validate and run a read-only SQL query. Writes, DDL, and other unsafe statements are rejected before execution. Example: |
| run_select_tunedA | Run a read-only SELECT with an elevated, bounded Example: |
| run_select_parallelA | Run up to parallel_limit read-only SELECTs concurrently. Each statement is validated by the same safety allowlist as run_select; one bad query does not abort the others — its error is captured in its own outcome slot. Useful for dashboard-style fan-out where round-trip latency dominates (e.g. fetching counters / aggregates from several tables at once). Each outcome includes an index so the caller can correlate results without relying on ordering. |
| open_cursorA | Open a server-side cursor for a SELECT query. The cursor holds the result set on the server side so an agent can page through millions of rows without loading them all. SQL is validated by the same safety allowlist as run_select. Returns the cursor_id; fetch the rows with fetch_cursor and close with close_cursor (or let the 5-minute TTL clean up). Hard cap of 16 concurrent cursors. |
| fetch_cursorA | Fetch the next batch from an open server-side cursor. exhausted=true means the FETCH returned fewer rows than requested — stop polling. batch_size defaults to 100; hard cap is 10000 per call. |
| close_cursorB | Close a server-side cursor and release its dedicated connection. Idempotent — returns closed=false when the cursor was not open (already closed, expired, or never existed). |
| list_cursorsA | List every currently-open server-side cursor with its SQL, rows_returned so far, age in seconds, and the TTL after which it'll be auto-closed. |
Prompts
Interactive templates invoked by user choice
| Name | Description |
|---|---|
| diagnose_slow_query | Deterministic investigation plan for a single slow SQL statement. Walks the agent through `explain_query`, `analyze_query_plan`, `recommend_indexes`, and `analyze_workload` in order, with a structured reporting checklist at the end. |
| bisect_slow_migration | Investigation plan for a performance regression introduced by a migration. Confirms the migration ran, scopes what changed via `compare_schemas`, validates the suspects with per-query `analyze_query_plan`, and ends with a remediation decision tree. |
| review_rls_policy | RLS coverage audit for a single table — inventories columns, reads current policies, identifies gaps against identity-bearing columns, and cross-checks the cluster security posture. Diagnosis only — proposes `CREATE POLICY` statements but does not apply them. |
Resources
Contextual data attached and managed by the client
| Name | Description |
|---|---|
| MCPg self-description | Full capability summary — the same JSON payload `describe_self` returns, exposed as a resource so an agent can preload it once at session start without burning a tool call. Includes per-bucket tool lists + headlines. Drill into a single bucket via `mcpg://capabilities/{bucket_id}`. |
| MCPg capability buckets (compact) | Compact list of MCPg's capability buckets — just `id`, `name`, `summary` per bucket. Cheap enough to pull on every session start. Drill into a bucket with `mcpg://capabilities/{bucket_id}`. |
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/devopam/MCPg'
If you have feedback or need assistance with the MCP directory API, please join our Discord server