Skip to main content
Glama

Postgres AIops

Audit availability: Real writes require a committed pending audit row and stop before contacting the platform if storage is unavailable. Reads and previews may continue with a warning; new audit rows store outcome summaries rather than full responses.

Disclaimer: Community-maintained open-source project. Not affiliated with, endorsed by, or sponsored by the PostgreSQL Global Development Group or any vendor. "PostgreSQL" and the elephant logo are trademarks of the PostgreSQL Community Association; all product/trademark names belong to their respective owners. MIT licensed.

Governed AI-ops for PostgreSQL DBA operations — connecting to a server with psycopg 3 and reading the system catalogs and pg_stat_* views — with a built-in governance harness: unified audit log, token/runaway budget guard, undo-token recording, and descriptive risk-tier labels. Beyond the mock test suite, the reads, a governed write, and its undo have been exercised against a live PostgreSQL 16.14 instance — see docs/VERIFICATION.md.

What it does

Three flagship signature analyses, plus the guarded reads and writes around them:

  • Slow-query RCA — take the worst pg_stat_statements entry (plus an optional EXPLAIN plan) and map its numbers — mean time, cache-hit ratio, temp spill, call count, plan node types — to a cited cause and a concrete action. Every finding carries its measured number, not a black-box verdict.

  • Bloat & vacuum analysis — combine per-table dead-tuple ratio and autovacuum recency into a ranked, cited recommendation (VACUUM / tune autovacuum).

  • Blocking lock-chain RCA — build the wait-for tree from pg_blocking_pids, name the root blocker (blocks others, waits on none), and give the action; a cycle is flagged as a likely deadlock.

Related MCP server: pgtriage

What works

  • CLI (postgres-aiops ...): init, overview, server, activity, query, index, table, repl, analyze, remediate, secret, doctor, mcp.

  • MCP server (postgres-aiops mcp or postgres-aiops-mcp): 35 tools (25 read, 10 write), every one wrapped with the bundled @governed_tool harness.

  • Encrypted credentials: the role password lives in an encrypted store ~/.postgres-aiops/secrets.enc (Fernet + scrypt) — never plaintext on disk. Unlock with a master password from POSTGRES_AIOPS_MASTER_PASSWORD (MCP/CI) or an interactive prompt (CLI).

  • Reversibility: mutating writes fetch the real before-state first and record a faithful inverse — create_index↔drop_index; drop_index captures pg_get_indexdef so undo recreates it exactly; update_setting captures the prior value so undo sets it back. Irreversible ops (terminate_backend, cancel_query, run_vacuum, run_analyze, reindex, reset_query_stats) record prior stats for audit but declare no undo.

  • Safety: every state-changing CLI op supports --dry-run and requires double confirmation; every write MCP tool takes a dry_run preview. All identifiers that cannot be parameterised (table/index/GUC names) are validated and quoted; all values are bound query parameters.

Capability matrix (35 MCP tools)

Domain

Tools

Count

R/W

Overview

overview

1

read

Server

server_version, show_settings, list_extensions, list_databases, list_roles

5

read

Activity

list_activity, long_running_queries, list_locks

3

read

Queries

top_queries, explain_query

2

read

Indexes

unused_indexes, missing_index_hints, index_bloat, invalid_indexes

4

read

Tables

table_sizes, table_bloat, autovacuum_status

3

read

Replication

replication_status, replication_slots, wal_status

3

read

Analysis (flagship)

slow_query_rca, bloat_and_vacuum_analysis, blocking_lock_chain_rca

3

read

Writes

terminate_backend, cancel_query, drop_index

3

write (high)

run_vacuum, run_analyze, create_index, reindex, update_setting, reset_query_stats

6

write (medium)

Undo

undo_list

1

read

undo_apply

1

write (medium)

The flagship analyses accept injected records for pure/offline analysis, or pull live from a configured target. top_queries/slow_query_rca require the pg_stat_statements extension; the read role should have pg_monitor.

What this tool does, and does not, decide

It delivers PostgreSQL DBA operations — reads and writes — accurately and efficiently, and records every one of them. It does not decide whether a write is allowed to happen. That is the agent's judgement, or the permission of the account you connect it with: connect with a PostgreSQL role that has no write privileges (a read-only role, or one without INSERT/UPDATE/DELETE/DDL), and the writes fail at the server — the place that actually owns the permission.

So there is no read-only switch, no policy file, no approval gate to configure. The one thing the tool guarantees is that nothing is silent: every call, over MCP and over the CLI alike, lands an audit row in ~/.postgres-aiops/audit.db, and destructive writes still capture their before-state and record an inverse where one exists.

Each tool declares a risk_level, carried into the audit row as a descriptive tier (none/confirm/review) — so a reviewer can see at a glance that a row was a high-risk delete. It is a label, not a gate.

Running a smaller / local model? See agent-guardrails.md — it lists the guardrails this tool now enforces for you (so you don't spend prompt budget restating them) and gives a ready-made system prompt for what's left.

Quick start

As a Claude Code plugin

One install gives an agent both the skill and the MCP server:

/plugin marketplace add AIops-tools/marketplace
/plugin install postgres-aiops@aiops-tools

The MCP server is fetched with uv and pinned to the package version this plugin declares, so an audit row can be traced back to the code that wrote it. Credentials are still configured with postgres-aiops init — see below.

As an OpenClaw plugin

The same bundle is published on ClawHub, where one install delivers the skill and its MCP server together:

openclaw plugins install clawhub:@zw008/postgres-aiops
openclaw skills info postgres-aiops          # expect: Visible to model: yes

Restart the OpenClaw gateway afterwards so it loads the plugin. The MCP server is fetched with uv, pinned to this exact release, so uvx has to be on PATH — without it the skill still installs but reports Visible to model: no. Credentials are configured exactly as below.

As a CLI or standalone MCP server

uv tool install postgres-aiops             # or: pipx install postgres-aiops
postgres-aiops init                        # wizard: add a target + store the password (encrypted)
postgres-aiops doctor                      # verify config, secrets, connectivity
postgres-aiops overview                    # one-shot cluster health snapshot
postgres-aiops analyze slow-query          # RCA the worst pg_stat_statements entry
postgres-aiops table bloat                 # dead-tuple bloat proxy per table

Run as an MCP server (stdio):

export POSTGRES_AIOPS_MASTER_PASSWORD=...  # unlock secrets non-interactively
postgres-aiops-mcp

Where that password then lives: an exported variable is readable by every process this shell starts and is recorded by shell history. On a shared or long-lived host, prefer the interactive prompt, or inject it from a secret manager for the life of the one command that needs it.

Governance

Every MCP tool passes through the bundled @governed_tool harness:

  • Audit — every call (params, outcome summary, status, duration, risk tier, and any operator-supplied approver/rationale) is logged to ~/.postgres-aiops/audit.db (relocatable via POSTGRES_AIOPS_HOME). The CLI writes the same row the MCP path does — there is no unaudited entry point.

  • Runaway guard — a safety backstop, not an authorization gate: the same call hammered in a tight loop trips a circuit breaker. Disable with POSTGRES_RUNAWAY_MAX=0; optional hard ceilings via POSTGRES_MAX_TOOL_CALLS / POSTGRES_MAX_TOOL_SECONDS.

  • Undo recording — reversible writes record an inverse descriptor built from the fetched before-state.

  • Risk tier — a descriptive label on the audit row derived from risk_level; it gates nothing.

Scope

This is the PostgreSQL DBA-ops member of the AIops-tools family (governed AI-ops with audit + budget + undo + risk tiers). Do NOT use it for OT / industrial edge (Modbus, OPC-UA, PROFINET) — see the separate industrial-aiops line — nor for application-schema migrations or ORM management.

Missing a capability?

Coverage is intentionally a curated subset of PostgreSQL's catalogs and maintenance surface. Missing a view, a metric, or a maintenance command? Open an issue or PR — contributions welcome.

Status

The mock test suite is complemented by a live run: the catalog / pg_stat_* reads, the bloat_and_vacuum_analysis RCA, and the create_index / drop_index governed write path (audit + undo, with drop_index capturing pg_get_indexdef first) were exercised against a live PostgreSQL 16.14 instance running in Docker. docs/VERIFICATION.md records exactly what was and was not covered. postgres-aiops doctor is the fastest live check.

Available Tools

35 tools
autovacuum_statusB
Read-only

[READ] Per-table dead tuples, mods-since-analyze, and last (auto)vacuum times.

Args:
    limit: Number of tables to inspect (default 50).
    target: Target name from config; omit for the default.

Inputs: limit, target.

bloat_and_vacuum_analysisA
Read-only

[READ] Rank tables needing vacuum from dead-tuple ratio + autovacuum recency.

Pass 'tables' (as from table_bloat) for pure/offline analysis, or omit to
pull the worst dead-tuple tables live. Each recommendation cites its numbers.

Args:
    tables: Injected table-bloat rows; if omitted, pulled live.
    limit: How many tables to pull when not injected (default 50).
    target: Target name from config; omit for the default.

Inputs: limit, tables, target.

blocking_lock_chain_rcaA
Read-only

[READ] Build the wait-for tree from blocking pairs and name the root blocker.

Pass 'pairs' (as from the live blocking-pairs read) for pure/offline analysis,
or omit to pull the current blocking graph live.

Args:
    pairs: Injected blocking pairs {blockedPid, blockingPid, ...}; if omitted,
        pulled live from pg_blocking_pids.
    target: Target name from config; omit for the default.

Inputs: pairs, target.

cancel_queryA
Destructive

[WRITE][risk=high] Cancel a backend's running query (pg_cancel_backend). No inverse.

Captures the backend's pid + query for audit; a cancel has no undo. Pass
dry_run=True to preview.

Refuses this tool's own backend pid — the query it would cancel is this very
call. Enforced under dry_run too.

Args:
    pid: Backend process id (from list_activity).
    dry_run: If True, preview without cancelling.
    target: Target name from config; omit for the default.

Inputs: pid (required), target, dry_run.

create_indexA
Destructive

[WRITE][risk=medium] Create an index. Reversible: undo drops the created name.

Supports CONCURRENTLY (non-blocking build). The created name is returned so
the harness records an undo that drops exactly this index. Pass dry_run=True
to preview. Alternatively pass ``definition`` (a captured pg_get_indexdef
statement — this is how drop_index's undo descriptor replays) INSTEAD of
table/columns.

Args:
    table: Table to index (optionally schema-qualified). Required unless
        ``definition`` is given.
    columns: Column names to index. Required unless ``definition`` is given.
    name: Index name (auto-generated from table+columns when omitted).
    unique: Create a UNIQUE index.
    concurrently: Build with CONCURRENTLY (no table lock).
    method: Index method — btree/hash/gist/gin/brin/spgist (default btree).
    definition: A full CREATE [UNIQUE] INDEX statement to execute verbatim
        (shape-validated). Mutually exclusive with table/columns.
    dry_run: If True, preview without creating.
    target: Target name from config; omit for the default.

Inputs: name, table, method, target, +5 more.

drop_indexA
Destructive

[WRITE][risk=high] Drop an index. Reversible: captures pg_get_indexdef first.

Before dropping, the exact index definition is captured so the harness records
an undo that recreates it. Pass dry_run=True to preview.

Args:
    name: Index name (optionally schema-qualified).
    concurrently: Drop with CONCURRENTLY (no table lock).
    dry_run: If True, preview without dropping.
    target: Target name from config; omit for the default.

Inputs: name (required), target, dry_run, concurrently.

explain_queryA
Read-only

[READ] Return the JSON execution plan for sql (EXPLAIN).

analyze=False (default) plans without executing; analyze=True runs the
statement to collect real timing — only use it for read-only SQL.

Args:
    sql: A single SQL statement to EXPLAIN.
    analyze: If True, execute the statement to gather real row counts/timing.
    target: Target name from config; omit for the default.

Inputs: sql (required), target, analyze.

index_bloatA
Read-only

[READ] Coarse index-bloat estimate (all inputs returned for transparency).

Args:
    limit: Number of indexes to inspect, largest first (default 50).
    target: Target name from config; omit for the default.

Inputs: limit, target.

invalid_indexesA
Read-only

[READ] Invalid indexes (failed CONCURRENTLY builds) and duplicate indexes.

Args:
    target: Target name from config; omit for the default.

Inputs: target.

list_activityA
Read-only

[READ] Current sessions (pg_stat_activity) with per-state counts.

Flags idle-in-transaction backends (open transactions holding resources).

Args:
    state: Optional exact state filter (active, idle, 'idle in transaction').
    include_idle: Include plain idle backends (default True).
    target: Target name from config; omit for the default.

Inputs: state, target, include_idle.

list_databasesA
Read-only

[READ] Databases with owner, encoding and on-disk size (largest first).

Args:
    target: Target name from config; omit for the default.

Inputs: target.

list_extensionsB
Read-only

[READ] Installed extensions and whether a newer version is available.

Args:
    target: Target name from config; omit for the default.

Inputs: target.

list_locksA
Read-only

[READ] Held/awaited locks joined to their owning backend and object.

Args:
    target: Target name from config; omit for the default.

Inputs: target.

list_rolesB
Read-only

[READ] Roles and their attributes (superuser/login/replication/…).

Args:
    target: Target name from config; omit for the default.

Inputs: target.

long_running_queriesB
Read-only

[READ] Active queries running at least min_seconds, oldest first.

Args:
    min_seconds: Minimum age in seconds (default 60).
    target: Target name from config; omit for the default.

Inputs: target, min_seconds.

missing_index_hintsB
Read-only

[READ] Tables with heavy sequential scans and few index scans (index hints).

Args:
    min_seq_scan: Minimum cumulative sequential scans to flag (default 1000).
    min_live_tup: Minimum live tuples for a table to qualify (default 10000).
    target: Target name from config; omit for the default.

Inputs: target, min_live_tup, min_seq_scan.

overviewA
Read-only

[READ] One-shot cluster health snapshot.

Version + uptime, connections by state, idle-in-transaction count, the
longest-running query, the worst dead-tuple table, and standby replay lag —
each section captured defensively so one failing probe does not sink the rest.

Args:
    target: Target name from config; omit for the default.

Inputs: target.

reindexA
Destructive

[WRITE][risk=medium] REINDEX an index/table/schema (rebuild in place, no undo).

Rebuilds physical index storage; there is no inverse. Pass dry_run=True to
preview.

Args:
    target_name: The index/table/schema name to reindex.
    kind: INDEX, TABLE, or SCHEMA (default INDEX).
    concurrently: Rebuild with CONCURRENTLY.
    dry_run: If True, preview without rebuilding.
    target: Target name from config; omit for the default.

Inputs: target_name (required), kind, target, dry_run, +1 more.

replication_slotsA
Read-only

[READ] Replication slots, flagging inactive slots that retain WAL.

Args:
    target: Target name from config; omit for the default.

Inputs: target.

replication_statusA
Read-only

[READ] Connected standbys and their replay lag (pg_stat_replication).

Args:
    target: Target name from config; omit for the default.

Inputs: target.

reset_query_statsA
Destructive

[WRITE][risk=medium] Reset pg_stat_statements accumulators (irreversible).

The counters cannot be restored, so no undo is recorded. Pass dry_run=True
to preview.

Args:
    dry_run: If True, preview without resetting.
    target: Target name from config; omit for the default.

Inputs: target, dry_run.

run_analyzeA
Destructive

[WRITE][risk=medium] ANALYZE a table to refresh planner statistics.

No undo; captures prior stats for audit. Pass dry_run=True to preview.

Args:
    table: Table name (optionally schema-qualified).
    dry_run: If True, preview without running.
    target: Target name from config; omit for the default.

Inputs: table (required), target, dry_run.

run_vacuumA
Destructive

[WRITE][risk=medium] VACUUM a table (optionally FULL/ANALYZE). Records prior stats.

No undo (a vacuum has no inverse); the prior dead-tuple/last-vacuum stats are
captured for the audit trail. VACUUM FULL takes an exclusive lock. Pass
dry_run=True to preview.

Args:
    table: Table name (optionally schema-qualified, e.g. public.orders).
    full: Run VACUUM FULL (rewrites the table, exclusive lock).
    analyze: Also refresh planner statistics (VACUUM ANALYZE).
    dry_run: If True, preview without running.
    target: Target name from config; omit for the default.

Inputs: table (required), full, target, analyze, +1 more.

server_versionB
Read-only

[READ] Server version, uptime, recovery state, and data directory.

Args:
    target: Target name from config; omit for the default.

Inputs: target.

show_settingsB
Read-only

[READ] Configuration parameters from pg_settings.

Args:
    pattern: Optional case-insensitive substring to filter setting names
        (e.g. 'work_mem', 'autovacuum').
    target: Target name from config; omit for the default.

Inputs: target, pattern.

slow_query_rcaA
Read-only

[READ] RCA for the worst pg_stat_statements entry, with cause + action.

Picks the statement with the greatest total execution time and maps its
numbers (mean time, cache-hit ratio, temp spill, calls) — plus an optional
EXPLAIN plan — to cited causes and concrete actions. Pass 'statements' for
pure/offline analysis, or omit to pull the top statements live.

Args:
    statements: Injected pg_stat_statements rows (as from top_queries); if
        omitted, the worst statements are pulled live.
    explain_sql: Optional SQL to EXPLAIN so plan node types feed the RCA.
    limit: How many statements to pull when not injected (default 20).
    target: Target name from config; omit for the default.

Inputs: limit, target, statements, explain_sql.

table_bloatA
Read-only

[READ] Dead-tuple bloat proxy per table (dead / (live + dead)), worst first.

Args:
    limit: Number of tables to inspect (default 50).
    target: Target name from config; omit for the default.

Inputs: limit, target.

table_sizesB
Read-only

[READ] Largest tables by total relation size (table + indexes + TOAST).

Args:
    limit: Number of tables to return, largest first (default 20).
    target: Target name from config; omit for the default.

Inputs: limit, target.

terminate_backendA
Destructive

[WRITE][risk=high] Terminate a backend (pg_terminate_backend). No safe inverse.

Captures the backend's pid + query for the audit trail; a terminate cannot be
undone, so no undo is offered. Pass dry_run=True to preview.

Refuses this tool's own backend pid — including under dry_run, which must
report a refusal rather than preview a call that will be refused.

Args:
    pid: Backend process id (from list_activity).
    dry_run: If True, preview without terminating.
    target: Target name from config; omit for the default.

Inputs: pid (required), target, dry_run.

top_queriesB
Read-only

[READ] Top statements from pg_stat_statements by a whitelisted metric.

Args:
    order_by: One of total_time, mean_time, calls, rows, io.
    limit: Number of statements to return (1..200, default 20).
    target: Target name from config; omit for the default.

Inputs: limit, target, order_by.

undo_applyA
Destructive

[WRITE][risk=medium] Apply a recorded undo by dispatching its inverse tool.

The inverse runs through its own governed tool, so its risk tier and audit
row are recorded there. Pass dry_run=True to preview the inverse call
without executing it. A token can only be applied once.

Args:
    undo_id: The undoId from undo_list (or an ``_undo_id`` in a write result).
    dry_run: If True, preview the inverse tool + params without running it.
    target: Passed through to the inverse tool when it accepts a target.

Inputs: undo_id (required), target, dry_run.

undo_listA
Read-only

[READ] List recorded, not-yet-applied undo tokens (most recent first).

Each entry names the original tool, the inverse tool that ``undo_apply``
would run, and a human note. Use the ``undoId`` with ``undo_apply``.

Each entry carries ``effectVerified``. False means the original write
lost its response, so the change it reverses is PROBABLE, not confirmed —
check the live state before applying, and do not report the result as a
restore of a state that may never have been reached.

Args:
    limit: Max rows to return (default 50).
    target: Unused (undo state is host-local); accepted for CLI uniformity.

Inputs: limit, target.

unused_indexesA
Read-only

[READ] Non-unique, non-primary indexes with zero scans (drop candidates).

Args:
    min_size_bytes: Only report indexes at least this large (default 0).
    target: Target name from config; omit for the default.

Inputs: target, min_size_bytes.

update_settingA
Destructive

[WRITE][risk=medium] ALTER SYSTEM SET (or RESET) a parameter. Reversible.

Writes postgresql.auto.conf; most parameters need SELECT pg_reload_conf() (or
a restart for postmaster-context settings) to take effect — reported but NOT
performed automatically. The prior state is captured so the harness records
an undo. Pass dry_run=True to preview.

reset=True issues ALTER SYSTEM RESET, dropping the parameter's auto.conf
entry so postgresql.conf or the built-in default applies again. That is the
recorded inverse when the parameter had no auto.conf entry to begin with:
writing the prior value back would leave a pin that shadows postgresql.conf.

Refuses the connection-affecting postmaster settings (listen_addresses,
port, max_connections, superuser_reserved_connections, ssl, hba_file):
nothing breaks now, but the operator's next restart applies them and strands
the undo. Enforced under dry_run too.

Args:
    name: The configuration parameter name (e.g. work_mem).
    value: The new value (as a string). Omit when reset=True.
    reset: If True, ALTER SYSTEM RESET the parameter instead of setting it.
    dry_run: If True, preview without changing.
    target: Target name from config; omit for the default.

Inputs: name (required), reset, value, target, +1 more.

wal_statusB
Read-only

[READ] WAL position, level, size settings and archiver health.

Args:
    target: Target name from config; omit for the default.

Inputs: target.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 35 tools

    Disambiguation4/5

    Most tools have clearly distinct resource/action targets: cancel_query vs terminate_backend, top_queries vs slow_query_rca, and the index diagnostics are separable. However, table_bloat, bloat_and_vacuum_analysis, and autovacuum_status overlap heavily around dead-tuple/vacuum diagnostics, and several index tools require careful reading to distinguish.

    Naming Consistency4/5

    All tool names consistently use snake_case, so there is no camelCase/snake_case mixing. The pattern is not uniform verb_noun: some are noun-phrase diagnostics (long_running_queries, index_bloat, table_sizes) while write tools use verbs (run_vacuum, create_index, drop_index, update_setting), making it mostly consistent with minor deviations.

    Tool Count2/5

    35 tools is far above the 3-15 well-scoped range and exceeds the 25+ 'too many' threshold. While Postgres operations is broad, many read-only diagnostic tools (table_bloat, autovacuum_status, index_bloat, etc.) could be consolidated or deferred behind a single analysis tool, so the surface feels heavy.

    Completeness4/5

    The set covers core operational read/write workflows: activity/locks/queries, index maintenance, vacuum/analyze, settings, replication/WAL, and a reversible-write/undo mechanism. Missing pieces like database/role lifecycle DDL, backup/restore, and schema introspection are notable but likely outside a focused AIOps scope, so the surface is mostly complete with minor gaps.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      Governed MySQL + MariaDB DBA operations — slow-query, lock-wait/deadlock, replication, and fragmentation RCA, with unbypassable audit logging (MCP + CLI), budget/runaway guards, dry-run, and undo/rollback.
      35
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Read-only PostgreSQL performance auditing via MCP. Collects metrics from PostgreSQL system views, applies deterministic checks for index, query, vacuum, configuration, and connection issues, and returns structured findings for MCP clients.
      6
      MIT
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables AI assistants to perform read-only PostgreSQL DBA work across versions 12–18, including performance analysis, slow query identification, bloat detection, lock and deadlock monitoring, autovacuum and schema inspection, and replication/WAL checks via natural language. Works with regular user permissions on RDS/Aurora without requiring any extensions, while optionally leveraging pg_stat_statements and pg_stat_monitor for deeper query analytics.
      -
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables natural-language PostgreSQL operations and monitoring across PG 12-18 without requiring extensions, covering performance analysis, slow-query identification, bloat detection, lock and connection monitoring, autovacuum inspection, replication/WAL status, and schema relationship discovery. All operations are read-only and production-safe, working with regular user permissions on RDS/Aurora as well as self-hosted instances.
      -