Skip to main content

pgtriage

CI PyPI Python License

MCP server for PostgreSQL performance auditing. Connect it to Claude Code (or any MCP client) and say "audit my database" to get actionable performance findings with exact fixes.

Not related to the pgAudit logging extension. pgtriage does performance triage, not compliance logging.

Why I built this

Built after diagnosing implicit type casts and missing indexes on multi-million-row tables in production fintech systems. The fixes were simple (one CREATE INDEX CONCURRENTLY statement each), but finding them required reading query plans most engineers never look at. pgtriage automates that diagnostic process and lets any AI client explain the results.

How it works

Any MCP Client (Claude Code / Cursor / Windsurf / VS Code)
       |  MCP (stdio)
       v
pgtriage (data collection + pattern detection)
       |  psycopg3 (read-only)
       v
PostgreSQL database

pgtriage connects to your PostgreSQL database and exposes performance auditing tools via the Model Context Protocol. It collects metrics from PostgreSQL system views, runs deterministic pattern detection, and returns structured findings. The MCP client provides the AI layer, interpreting results and explaining fixes in plain English.

No API keys required. No AI costs. No vendor lock-in. The intelligence comes from your MCP client.

Example output

{
  "severity": "high",
  "category": "connection_pressure",
  "detail": "Connection utilization at 104% (104/100). Approaching max_connections limit.",
  "suggested_fix": "Consider using a connection pooler (PgBouncer) or increasing max_connections if RAM allows.",
  "evidence": {
    "total_connections": 104,
    "max_connections": 100,
    "utilization_pct": 104.0
  }
}
{
  "severity": "medium",
  "category": "duplicate_index",
  "table": "account",
  "detail": "Duplicate indexes on 'account': 'account_title_reverse_index' (16 kB) and 'account_group_reverse_index' (16 kB). Same column definition. One can be dropped.",
  "suggested_fix": "DROP INDEX CONCURRENTLY account_group_reverse_index;"
}

From a real audit: 118 tables scanned, 88 findings, prioritized by severity.

What it finds

  • Sequential scans on large tables with missing index suggestions
  • Type casts on indexed columns that suppress index usage, verified against PostgreSQL catalog metadata and the observed query plan
  • Dead tuple buildup and autovacuum health issues
  • Unused and duplicate indexes wasting disk and slowing writes
  • N+1 query patterns from pg_stat_statements analysis
  • Stale table statistics causing bad query plans
  • TOAST table bloat from large JSONB/TEXT columns
  • Configuration issues (shared_buffers, work_mem, autovacuum tuning)
  • Connection pressure approaching max_connections
  • Long-running queries holding locks

Quick start

Install

pip install pgtriage

Configure Claude Code

Add to your MCP settings (.claude/settings.json or project settings):

{
  "mcpServers": {
    "pgtriage": {
      "command": "python",
      "args": ["-m", "pgtriage"],
      "env": {
        "PGTRIAGE_CONNECTION_STRING": "postgres://user:pass@localhost:5432/dbname"
      }
    }
  }
}

Recommended: Use a dedicated read-only database role:

CREATE ROLE pgtriage_reader LOGIN PASSWORD 'secure_password';
GRANT pg_read_all_stats TO pgtriage_reader;
GRANT USAGE ON SCHEMA public TO pgtriage_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO pgtriage_reader;

Use

> audit my database

> check table health for the users table

> are there any unused indexes?

> review my PostgreSQL configuration

> find slow queries

> audit only the accounts schema

Tools

full_audit

Run a comprehensive performance audit covering table health, slow queries, index health, and configuration. Pass the optional schema_name argument to scope table, plan, and index findings to one user schema; omit it to audit every non-system schema. Configuration findings remain database-wide. Returns all findings sorted by severity.

check_table_health

Analyze dead tuples, autovacuum stats, sequential scan ratios, and TOAST bloat. Optionally filter to a specific user schema and/or table.

analyze_slow_queries

Pull the slowest queries from pg_stat_statements, inspect their execution plans, and detect patterns like indexed-column type casts, sequential scans, stale statistics, and N+1 queries. An optional schema_name filter uses verbose execution-plan metadata rather than parsing SQL text. Literal queries use bounded EXPLAIN ANALYZE; normalized queries containing placeholders use a non-executing generic plan.

check_index_health

Find unused indexes (zero scans), duplicate indexes (same column definition), and tables that likely need indexes based on scan patterns. Optionally scope the analysis to one user schema.

check_config

Review PostgreSQL settings (shared_buffers, work_mem, autovacuum_vacuum_scale_factor, random_page_cost, etc.) and flag suboptimal values. Checks connection utilization and long-running queries.

Agent runtime integration

pgtriage publishes MCP safety annotations for every tool. All tools are marked read-only and non-destructive; tools that can run bounded EXPLAIN ANALYZE are deliberately not marked idempotent. Agent runtimes must still allowlist, authorize, and validate every call because MCP annotations are descriptive hints, not permissions. See Agent Runtime Integration for the complete contract, schema-scoped audit behavior, and retry guidance.

Resources

Resource Description
pgtriage://status Connection status, PostgreSQL version, loaded extensions
pgtriage://tables All tables with sizes and approximate row counts

Requirements

  • Python 3.11+
  • PostgreSQL 12+
  • pg_stat_statements extension (recommended for slow query analysis, not required for other tools)
  • Database user with read access to pg_stat_* views

Safety

pgtriage is designed for read-only production use and does not issue write SQL. Three independent layers protect database state:

  1. Session-level read-only: SET default_transaction_read_only = true on every connection. PostgreSQL rejects any write attempt at the server level.
  2. Query validation: EXPLAIN ANALYZE only runs on SELECT statements. INSERT, UPDATE, DELETE, DROP, SELECT INTO, SELECT FOR UPDATE, and stacked queries are all rejected before execution.
  3. Transaction rollback: Every EXPLAIN ANALYZE runs inside an explicit BEGIN/ROLLBACK block with a 10-second statement_timeout. Transactional database changes are rolled back and long-running queries are canceled. Rollback cannot undo external side effects triggered by database extensions or functions, so the dedicated read-only role and session-level read-only enforcement remain essential.

Additionally:

  • Connection strings are never exposed in tool outputs
  • Suggested fixes are advisory and are never executed by pgtriage; findings default to safe_to_apply: false
  • All database access is single-connection, no pooling

Development

git clone https://github.com/pgtriage/pgtriage.git
cd pgtriage
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
pytest

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pgtriage-0.1.3.tar.gz (37.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pgtriage-0.1.3-py3-none-any.whl (28.7 kB view details)

Uploaded Python 3

File details

Details for the file pgtriage-0.1.3.tar.gz.

File metadata

  • Download URL: pgtriage-0.1.3.tar.gz
  • Upload date:
  • Size: 37.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for pgtriage-0.1.3.tar.gz
Algorithm Hash digest
SHA256 4b7aba53a136ffbdc1ff1de88563d7f68725b5bab62b39fe0ebfc591b3348bbb
MD5 d470bc8afbcc5cea0b8f83ce422e85be
BLAKE2b-256 2bfd741f1851439444f4247de1a702f7120efdd402ad46fbe6245bfbb90b6a51

See more details on using hashes here.

Provenance

The following attestation bundles were made for pgtriage-0.1.3.tar.gz:

Publisher: publish-pypi.yml on pgtriage/pgtriage

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pgtriage-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: pgtriage-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 28.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for pgtriage-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 26f9426259cb7db6e0b4724b9de26cb667d621c93cf47f69ca64ecdd5ea89c10
MD5 5b4746f582bc8b582f1f7a5bbc47a8fd
BLAKE2b-256 ecf9e7f2dcdae75a9885566a104dfa7bcedecf24267c3c7e1cb05048e518d0a1

See more details on using hashes here.

Provenance

The following attestation bundles were made for pgtriage-0.1.3-py3-none-any.whl:

Publisher: publish-pypi.yml on pgtriage/pgtriage

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page