Skip to main content
Glama
postgresai

postgresai

Official
README.md
<div align="center">

<img src="assets/postgresai.png" alt="PostgresAI Monitoring v4" width="460">

# PostgresAI

### Open-source PostgreSQL Monitoring v4 — built for humans and AI agents

[![npm](https://img.shields.io/npm/v/postgresai?style=flat-square&logo=npm)](https://www.npmjs.com/package/postgresai)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](LICENSE)
[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-14--19-336791?style=flat-square&logo=postgresql&logoColor=white)](https://postgresql.org)
[![CLI Coverage](https://img.shields.io/gitlab/pipeline-coverage/postgres-ai%2Fpostgresai?branch=main&job_name=cli%3Anode%3Atests&label=CLI%20coverage&style=flat-square)](https://gitlab.com/postgres-ai/postgresai/-/pipelines)
[![Reporter Coverage](https://img.shields.io/gitlab/pipeline-coverage/postgres-ai%2Fpostgresai?branch=main&job_name=reporter%3Atests&label=Reporter%20coverage&style=flat-square)](https://gitlab.com/postgres-ai/postgresai/-/pipelines)

**One Rust binary (`pgai-mon`). Parquet on disk or S3. Plain SQL queries via DuckDB. Active Session History (ASH) and continuous Database Health.**

Works with **Supabase** · **AWS RDS (incl. PrivateLink) / Aurora (direct)** · **ClickHouse Managed Postgres** · **Self-hosted PostgreSQL**

[PostgresAI Console](https://console.postgres.ai/addorg) ·
[Docs](https://postgres.ai/docs) ·
[Quick start](#quick-start) ·
[Query in SQL](#query-monitoring-in-plain-sql) ·
[Pricing](https://postgres.ai/pricing)

</div>

---

The commands below target Monitoring v4; see [installation versions](#installation-versions) for release-channel requirements.

Give your AI coding agent (Claude Code, Codex, Cursor) one command and let it connect, monitor, and diagnose your Postgres:

```bash
npx skills add postgres-ai/postgresai --skill postgresai
```

Or start a local demo with sample Postgres traffic (requires Docker):

```bash
npx pgai mon local-install --demo
```

Battle-tested in the PostgresAI team's work with companies including [GitLab, Miro, Chewy, Suno, Supabase, Gadget, and more](https://postgres.ai).

---

## Why Monitoring v4?

Monitoring v4 combines collection, Parquet storage, and SQL querying in one Rust binary designed for Postgres engineers and AI agents. The legacy v3 stack used 10 containers; the full v4 Compose deployment adds supporting services for dashboards, Database Health, jobs, and host metrics.

| | Legacy stacks (v3 / pgwatch + TSDB) | PostgresAI Monitoring v4 (`pgai-mon`) |
|---|---|---|
| **Footprint** | 10 containers (pgwatch, VictoriaMetrics, sink DB, Flask, vmalert, exporters) | **1 Rust binary** (`pgai-mon`) for collection, storage, and SQL; supporting services in Compose |
| **Storage** | Stateful time-series database + separate Postgres sink | **Parquet files** on local disk or **S3** |
| **Query language** | PromQL | **Plain SQL** via embedded DuckDB (`pgai mon sql`) |
| **AI agents** | MCP server for Issues and reports; metrics via PromQL | **1-liner agent skill** (`npx skills add`), **17-tool MCP server**, and SQL over metrics |

## Architecture

```mermaid
flowchart LR
  PG["PostgreSQL 14+<br/>Supabase · AWS RDS · ClickHouse · Self-Hosted"] -->|read-only least-privilege| MON["pgai-mon<br/>(single Rust binary)"]
  MON -->|Parquet| STORE["Local volume or S3"]
  STORE --> DUCK["Embedded DuckDB<br/>Read-only SQL engine"]
  DUCK --> AGENT["AI Agents<br/>Skill · MCP · pgai mon sql"]
  DUCK --> CONSOLE["PostgresAI Console<br/>Database Health & Issues"]
  DUCK --> GRAF["Grafana (optional)<br/>ASH & Four Golden Signals"]
```

## Quick start

### Installation versions

The unversioned `npx pgai` commands, global MCP installation, agent-guided deployment, and `postgresai@latest` upgrade below require a Monitoring v4 release on npm's `latest` tag. Check `npm view pgai dist-tags` and `npm view postgresai dist-tags` before installing. For v4 release-candidate testing, substitute `npx pgai@rc` for `npx pgai` and install MCP with `npm install -g postgresai@rc`. For the upgrade path, also replace `postgresai@latest` with `postgresai@rc`. Installing the agent skill does not select a CLI channel: its deployment commands use `postgresai@latest`, so explicitly instruct the agent to use the v4 RC when testing a release candidate.

### 1. With your AI coding agent (fastest)

```bash
npx skills add postgres-ai/postgresai --skill postgresai
```

Requires Node.js 22.20+ for `npx skills`. Your agent loads [`.claude/skills/postgresai/SKILL.md`](.claude/skills/postgresai/SKILL.md) and guides authentication, read-only database setup (`postgres_ai_mon`), Cloud or self-hosted deployment, and root-cause analysis.

Prefer starting in the browser? Open [PostgresAI Console](https://console.postgres.ai/addorg) and choose **Set up with your AI agent**.

### 2. Directly from your terminal

```bash
# Preview the setup SQL (creates a role, grants, and supported extensions)
npx pgai prepare-db --print-sql postgresql://admin@host:5432/dbname

# Create the least-privilege postgres_ai_mon role (idempotent)
npx pgai prepare-db postgresql://admin@host:5432/dbname

# Deploy to PostgresAI Cloud (or self-host with: npx pgai mon local-install)
npx pgai auth login
npx pgai mon deploy postgresql://admin@host:5432/dbname
```

### 3. MCP server (Claude Code, Cursor, Codex)

Install globally so your MCP client points to a stable binary rather than a temporary `npx` cache:

```bash
npm install -g postgresai
postgresai auth login
postgresai mcp install claude-code   # or: postgresai mcp install cursor
# Codex: codex mcp add postgresai -- postgresai mcp start
```

Manual stdio clients use `postgresai mcp start`. Both `postgresai` and the shorter `pgai` command alias are included.

## Query monitoring in plain SQL

No PromQL required. Query live or historical metrics, wait events, and normalized `pg_stat_statements` text straight from your terminal or agent with `npx pgai mon sql` (pass `--project <name>` for Cloud or `--local` for self-hosted):

**Top 10 collected queries by execution time over the last hour:**

```bash
npx pgai mon sql --local "
select
  s.labels['datname'] as datname,
  s.labels['queryid'] as queryid,
  coalesce(q.query, s.labels['queryid']) as query,
  round(sum(s.value) / 1000.0, 2) as exec_sec
from prom_increase_pure(
  'pgwatch_pg_stat_statements_exec_time_total', [],
  epoch_ms(now()), epoch_ms(now()), 60000, 3600000
) s
left join query_text_names q
  on q.dbname = s.labels['datname']
 and cast(q.queryid as varchar) = s.labels['queryid']
where isfinite(s.value)
group by 1, 2, 3
order by exec_sec desc
limit 10
"
```

A series with no sample before the one-hour window is counted from zero by `prom_increase_pure`; during the first hour of collection, that can include execution time accumulated before monitoring started.

**Active Session History (top wait events over the last hour):**

```bash
npx pgai mon sql --local "
select
  labels['wait_event_type'] as wait_type,
  labels['wait_event'] as wait_event,
  round(sum(value), 2) as sum_observed_series_avg
from prom_avg_over_time(
  'pgwatch_wait_events_total', [],
  epoch_ms(now()), epoch_ms(now()), 60000, 3600000
)
where isfinite(value)
group by 1, 2
order by sum_observed_series_avg desc
limit 15
"
```

The ASH example sums per-series averages over recorded samples. Missing wait-event series are not zero-filled, so this is not a wall-clock average active-session count; use the ASH dashboards for that view. Both examples aggregate across the selected monitoring instance and need collected data.

## Supported platforms

| Platform | Connection | Host CPU / RAM / Disk metrics |
|---|---|---|
| **Supabase** | OAuth consent via Supabase Management API (no DB password needed) | Supabase metrics endpoint; self-hosted installs need the [host-metrics relay](docs/host-metrics.md) enabled |
| **AWS RDS & Aurora** | Direct URL; private **AWS PrivateLink** for RDS instances (not Aurora or RDS Proxy endpoints) | CloudWatch / Enhanced Monitoring with AWS permissions configured |
| **ClickHouse Managed Postgres** | Standard URL + `--ip-first` allowlist flow | Built-in via ClickHouse Cloud API (`--clickhouse-key`) |
| **Self-hosted / Bare metal / Docker** | Direct URL or self-hosted `mon local-install` | Bundled exporters cover the monitoring host only. [Custom scrapes](mon/README.md#scrape) expose raw `node_*` metrics for SQL; remote self-hosted database nodes have no normalized `host_*` panels |

## Cloud vs. Self-Hosted

- **Self-Hosted (Apache 2.0):** Run the full `pgai-mon` + Grafana + reporter stack on your own Linux/Docker host with zero account required (`npx pgai mon local-install`). Store Parquet history on local disk or in your own S3 bucket (`PGAI_MON_STORE=s3://bucket/prefix`).
- **PostgresAI Cloud:** Fully managed monitoring boxes, continuous Database Health analysis, prioritized Issues workflow, and team Console — **Starter at $16/cluster/month** and **Scale at $512/cluster/month** ([pricing](https://postgres.ai/pricing)). Confirm your exact quote before any billed deployment.

## Repository map

| Path | What lives here |
|---|---|
| [`mon/`](mon/) | `pgai-mon` Rust binary: Postgres collector (`mon/metrics.yml`), Parquet/S3 store, DuckDB SQL engine, and v4 Grafana dashboards |
| [`cli/`](cli/) | `pgai` / `postgresai` CLI and 17-tool stdio MCP server ([CLI reference](cli/README.md)) |
| [`reporter/`](reporter/) | Continuous Database Health insight generator reading from `pgai-mon` |
| [`.claude/skills/postgresai/`](.claude/skills/postgresai/SKILL.md) | Official AI agent skill for setup and Postgres diagnostics |
| [`docs/COLOR_SCHEME.md`](docs/COLOR_SCHEME.md) | Wait-event visualization color standard |

<details>
<summary><strong>Upgrading from Monitoring v3 (pgwatch + VictoriaMetrics) &amp; self-hosted configuration</strong></summary>

- **Upgrading from v3 starts metric history fresh.** `postgresai mon update` switches an existing v3 compose stack to `pgai-mon`, keeps a backup of your old compose file, and leaves old volumes untouched so you can roll back if needed. Legacy v3 maintenance lives on [`GEN3_STABLE`](https://gitlab.com/postgres-ai/postgresai/-/tree/GEN3_STABLE).
  ```bash
  npm install -g postgresai@latest
  postgresai mon update
  ```
- **Key `.env` knobs for self-hosted installs:** `PGAI_MON_STORE=s3://bucket/prefix` (S3 Parquet storage), `GRAFANA_PORT` / `PGAI_MON_PORT` (default bound to `127.0.0.1:3000` and `127.0.0.1:8765`), `GRAFANA_BIND_HOST=0.0.0.0:` (expose behind TLS), `PGAI_MON_TOKEN` (bearer token for the local API), `GRAFANA_SCALE=0` (headless mode, also set by `mon local-install --no-grafana`). See [`.env.example`](.env.example).
- **Kubernetes:** The archived Helm chart targets v3, not `pgai-mon`; it is retained in [`old/postgres_ai_helm`](old/postgres_ai_helm) for reference.
- `mon update` prints the backup-specific rollback commands. Full CLI commands and storage options: [`cli/README.md`](cli/README.md) and [`mon/README.md`](mon/README.md).

</details>

## Links & community

[PostgresAI Console](https://console.postgres.ai/addorg) ·
[Documentation](https://postgres.ai/docs) ·
[llms.txt](https://postgres.ai/llms.txt) ·
[Pricing](https://postgres.ai/pricing) ·
[GitLab (source & issues)](https://gitlab.com/postgres-ai/postgresai) ·
[Postgres.FM](https://postgres.fm) ·
[Postgres.TV](https://postgres.tv) ·
[Contact](https://postgres.ai/contact)

---

Apache License 2.0 — see [LICENSE](LICENSE). Built by [PostgresAI](https://postgres.ai) as part of [Self-Driving Postgres](https://postgres.ai/blog/20250725-self-driving-postgres).

TDQS

B3.4/5.0

Scored across 16 tools

Disambiguation4/5

Most tools target a distinct resource+action (issues, action items, reports, files, monitoring), and descriptions explicitly cross-reference each other (e.g. list_reports points to get_report_data, report tools point to issues tools). Minor overlap remains between view_action_item (accepts multiple IDs) and list_action_items, and between post_issue_comment/create_issue attachment handling versus upload_file, but the descriptions make the intended boundaries clear.

Naming Consistency4/5

Nearly all tools follow a consistent verb_noun snake_case pattern (list_issues, create_issue, update_issue_comment, list_report_files, deploy_monitoring). Deviations are small: 'post_issue_comment' rather than create_*, and 'get_report_data' vs 'view_issue'/'view_action_item' mixing get/view verbs, but nothing confusing.

Tool Count4/5

16 tools cover four coherent sub-areas (issues, action items, checkup reports, storage/attachments) plus monitoring deployment, so each tool has a plausible place. It sits just above the ideal 3-15 range and the very large deploy_monitoring description does a lot of work in one tool, but nothing feels redundant.

Completeness3/5

Issues and action items have list/view/create/update and comment create/update, but no delete operations for issues, comments, or action items, and there is no way to list or remove monitored deployments (deploy_monitoring is idempotent but there is no status-list or undeploy tool). Reports are read-only by nature, which is acceptable, but the missing lifecycle ends will force agents to work around gaps.

Maintenance

ActivityActive
ResponsivenessLimited data