PostgresAI CLI reference
Descriptionโ
PostgresAI Command Line Interface is a tool for working with PostgresAI: preparing databases for monitoring, running local monitoring stacks, generating health-check reports, browsing and managing issues in the PostgresAI Console, running Joe SQL optimization commands on ephemeral DBLab clones, and exposing PostgresAI tools to AI coding clients over MCP.
The CLI is published as the postgresai npm package and ships two
equivalent binaries: postgresai (canonical) and pgai (short alias).
Both names accept exactly the same commands and options; this page uses
postgresai throughout.
Requirementsโ
The CLI requires Node.js 18+ (or Bun 1.0+). Older Node versions fail fast with a clear error rather than breaking partway through a command.
Getting startedโ
To install and authenticate, see the PostgresAI CLI how-to.
Synopsisโ
- Installed CLI
- npx
- bunx
postgresai [global options] <command> [command options] [arguments...]
# or, equivalently:
pgai [global options] <command> [command options] [arguments...]
npx postgresai@latest [global options] <command> [command options] [arguments...]
bunx postgresai@latest [global options] <command> [command options] [arguments...]
Run postgresai --help to list available commands and global options.
For command-specific help, run postgresai <command> --help (works for
nested subcommands too, e.g. postgresai mon targets --help).
Global optionsโ
These options apply to every command and override the corresponding environment variables and configuration file values:
--api-key <key>โ API key (overridesPGAI_API_KEY).--api-base-url <url>โ API base URL for backend RPC (overridesPGAI_API_BASE_URL; defaulthttps://postgres.ai/api/general/).--ui-base-url <url>โ UI base URL for browser routes (overridesPGAI_UI_BASE_URL; defaulthttps://console.postgres.ai).--storage-base-url <url>โ Storage base URL for file uploads (overridesPGAI_STORAGE_BASE_URL).
Configuration is stored in ~/.config/postgresai/config.json.
Command overviewโ
COMMANDS:
prepare-db prepare a database for monitoring (idempotent)
unprepare-db remove monitoring setup from a database
checkup generate health-check reports directly from PostgreSQL
mon manage the local monitoring stack
login authenticate via browser or store an API key directly
auth authenticate and manage the local API key
login top-level alias for `auth login`
joe Joe โ plan/EXPLAIN/exec queries on ephemeral DBLab clones
projects list the org's projects (shows which have Joe ready)
issues manage issues, comments, and action items in PostgresAI Console
reports list and download checkup reports stored in PostgresAI Console
mcp MCP server integration for AI coding tools
set-default-project store the default project for checkup uploads
set-storage-url store the storage base URL for file uploads
help show help
Command: prepare-dbโ
Prepare a database for monitoring: create the monitoring user, the required view(s), and grant permissions. The command is idempotent.
Usage
- Installed CLI
- npx
- bunx
postgresai prepare-db [conn] [options]
npx postgresai@latest prepare-db [conn] [options]
bunx postgresai@latest prepare-db [conn] [options]
[conn] is an optional positional admin connection string. Both URL
form (postgresql://admin@host:5432/dbname) and libpq key/value form
("dbname=dbname host=host user=admin") are accepted; psql-like
options (-h, -p, -U, -d) are also supported.
Examples
postgresai prepare-db postgresql://admin@host:5432/dbname
postgresai prepare-db "dbname=dbname host=host user=admin"
postgresai prepare-db -h host -p 5432 -U admin -d dbname
# Verify only (no changes)
postgresai prepare-db postgresql://admin@host:5432/dbname --verify
# Dry run: print SQL plan
postgresai prepare-db postgresql://admin@host:5432/dbname --print-sql
# Reset only the monitoring role password
postgresai prepare-db postgresql://admin@host:5432/dbname \
--reset-password --password 'new_password'
# Supabase mode (uses Management API instead of direct connection)
SUPABASE_ACCESS_TOKEN=... SUPABASE_PROJECT_REF=... \
postgresai prepare-db --supabase
Connection options
-h, --host <host>โ PostgreSQL host (psql-like).-p, --port <port>โ PostgreSQL port (psql-like).-U, --username <username>โ PostgreSQL admin user (psql-like).-d, --dbname <dbname>โ PostgreSQL database name (psql-like).--admin-password <password>โ admin password (otherwise usesPGPASSWORDif set).--db-url <url>โ admin connection URL (deprecated; pass it as the positional[conn]argument).
Monitoring role options
--monitoring-user <name>โ monitoring role name to create or update (default:postgres_ai_mon).--password <password>โ monitoring role password (overridesPGAI_MON_PASSWORD). If neither is provided, a strong password is generated.--print-passwordโ print the generated monitoring password (dangerous in CI logs).--skip-optional-permissionsโ skip optional permissions (RDS / self-managed extras).--provider <provider>โ database provider (e.g.supabase); affects which steps run.
Modes
--verifyโ verify that the monitoring role and permissions are in place; make no changes.--reset-passwordโ reset only the monitoring role password.--print-sqlโ print the SQL plan and exit; apply no changes.--jsonโ output the result as machine-readable JSON.
Supabase mode
--supabaseโ use the Supabase Management API instead of a direct PostgreSQL connection.--supabase-access-token <token>โ Supabase Management API token (orSUPABASE_ACCESS_TOKENenv var). Tokens can be created on the Supabase access tokens page.--supabase-project-ref <ref>โ Supabase project reference (orSUPABASE_PROJECT_REFenv var). Auto-detected from a Supabase database URL when one is supplied as[conn].
Command: unprepare-dbโ
Reverse prepare-db: drop the monitoring user, views, schema, and
revoke permissions.
Usage
postgresai unprepare-db [conn] [options]
Options
-h, --host,-p, --port,-U, --username,-d, --dbname,--admin-password,--db-url <url>(deprecated) โ admin connection parameters, same asprepare-db.--monitoring-user <name>โ monitoring role to remove (default:postgres_ai_mon).--keep-roleโ keep the monitoring role; only revoke permissions and drop objects.--provider <provider>โ database provider (affects which steps run).--print-sqlโ print the SQL plan and exit; apply no changes.--forceโ skip the confirmation prompt.--jsonโ output the result as machine-readable JSON.
Command: checkupโ
Generate health-check reports directly from PostgreSQL ("express mode") and optionally upload them to the PostgresAI Console.
Express mode supports PostgreSQL 14 through PostgreSQL 19. For PostgreSQL 19
beta releases, it preserves version labels such as 19beta2 while using
server_version_num (190000) for version-aware metric selection. PostgreSQL
19 remains a pre-release; use it for compatibility testing rather than
production workloads until general availability.
Usage
# Run all checks
postgresai checkup <conn>
# Run a specific check (CHECK_ID matches /^[A-Z]\d{3}$/i โ case-insensitive, e.g. H002 or h002)
postgresai checkup <CHECK_ID> <conn>
<conn> accepts the same URL / libpq / psql-like forms as
prepare-db.
Options
--check-id <id>โ specific check to run (orALL). Equivalent to passing the check ID as the first positional argument.--node-name <name>โ node name embedded in reports (default:node-01).--output <path>โ write per-check JSON results to this directory. Only the report payload is written; progress and error messages go to stderr, so the output files stay clean.--upload/--no-uploadโ upload JSON results to PostgresAI Console (requires API key). Default depends on whether an API key is configured.--project <project>โ project name or ID for the upload (used with--upload). Defaults to the value stored byset-default-project; a project is auto-generated on first run if needed.--jsonโ print JSON to stdout.--markdownโ print Markdown to stdout.
Progress and error messages are written to stderr; stdout carries only the report
payload. This means --json / --markdown can be piped safely, for example:
postgresai checkup <conn> --json | jq '.checks[] | select(.id == "H002")'
Available checks
Run postgresai checkup --help to see the full list of check IDs and titles bundled with your
CLI version. The express-mode checks span the A (general / version / cluster), D (logging and
pg_stat_statements settings), F (autovacuum / bloat), G (memory and timeouts), H (index), and I
(I/O) groups โ there are no K (query) checks in the express-mode CLI. In addition to the index
(H00x) checks, 0.15 ships the estimated bloat checks:
| Check | Finds |
|---|---|
F004 | Autovacuum: heap bloat (estimated) |
F005 | Autovacuum: index bloat (estimated) |
# Run a single bloat check
postgresai checkup F004 <conn>
The bloat estimation checks read catalog-level statistics that require the monitoring role
created by prepare-db. When the connection lacks the required
privileges, the check prints a hint:
Hint: Run "postgresai prepare-db <connection>" to create required objects.
Run prepare-db (or connect with a sufficiently privileged role) and re-run the check.
Command: monโ
Manage the local monitoring stack (Docker Compose-based: collectors, VictoriaMetrics, Grafana, โฆ).
Usage
postgresai mon <subcommand> [options]
Subcommands
local-installโ install the local monitoring stack: generate.env, configure services, and start them.startโ start monitoring services. Runsdocker compose up -donly when the stack is not already running: if any Grafana/pgwatch container is already up, it printsMonitoring services are already runningand exits without runningup -d(suggestingmon restart). When it does run,up -dcreates or recreates containers as needed, so it applies a newly pulled image and triggers aconfig-initreseed when the image version no longer matches the config-volume marker. It uses plaindocker compose up -d(not--force-recreate). A full-stackup -d --force-recreateis used bymon local-install;mon targets add/removealso force-recreate, but only the two pgwatch collector containers (pgwatch-prometheus,pgwatch-postgres). On an already-running stack a baremon startis therefore a no-op โ to apply a pulled image or recreateconfig-initon a live stack, rundocker compose up -ddirectly, ormon stopthenmon start.stopโ stop monitoring services.restart [service]โ restart all services or a specific one (docker compose restart [service]). Restarts the existing containers in place: it does not recreate them, does not apply a newly pulled image, and does not trigger aconfig-initreseed. To apply a new image or changed container env vars on a running stack, recreate the containers withdocker compose up -d(a baremon startno-ops while the stack is running, since it short-circuits withMonitoring services are already running).statusโ show services status.healthโ check that services are up and healthy.logs [service]โ show logs for all services or a specific one.configโ show monitoring configuration.update-configโ apply configuration changes after editing.env: migrates.envadditively (preserving existing values), refreshes the CLI-owneddocker-compose.ymlfor non-git installs, and regenerates the pgwatchsources.yml(docker compose run --rm sources-generator). It does not regenerate the Grafana datasources, reseed the config volume, or restart any service.updateโ update the monitoring stack: migrates.envadditively (preserving existing values), refreshes the repo/compose, and pulls the pinned images for the current tag (docker compose pull). It does not restart, recreate, orupany service โ afterward you must recreate the containers to apply the new images. On a running stack do this withdocker compose up -ddirectly (ormon stopthenmon start, or re-runmon local-install, which usesup -d --force-recreate). The command prints a hint to runmon restart, butdocker compose restartrestarts containers in place on the old image and does not apply a pulled image; and a baremon startis a no-op while the stack is running (it short-circuits withMonitoring services are already running), so it will not apply the new image on its own either. See Upgrading the monitoring stack for the full upgrade flow (including the requiredVM_AUTH_*keys in 0.15).reset [service]โ reset all services or a specific one (removes data).cleanโ clean up monitoring artifacts (stops services and removes volumes).checkโ system readiness check.shell <service>โ open an interactive shell in a monitoring service container.targetsโ manage databases to monitor (see below).generate-grafana-passwordโ generate a new Grafana password.show-grafana-credentialsโ show Grafana credentials.
Subcommand: mon local-installโ
Install (or re-install) the local monitoring stack. Replaces the older
mon quickstart name.
postgresai mon local-install [options]
Options
--demoโ demo mode with a sample database (for testing; cannot be combined with--api-key).--api-key <key>โ PostgresAI API key for automated report uploads.--db-url <url>โ PostgreSQL connection URL to monitor (form:postgresql://user:pass@host:port/db).--tag <tag>โ Docker image tag to use (e.g.0.15.0,0.15.0-dev.33).--project <name>โ project name. Used as the Docker Compose project name (default:postgres_ai). When an--api-keyis supplied (non-demo install), it is also used as the project name when registering this monitoring instance with the PostgresAI Console; the registration default ispostgres-ai-monitoring.-y, --yesโ accept all defaults and skip interactive prompts.
local-install writes .env in the monitoring directory, preserving
existing REPLICATOR_PASSWORD and VM_AUTH_* values or generating new
random ones when missing. VM_AUTH_USERNAME defaults to vmauth when
absent. The replication password is used by the demo PostgreSQL standby,
and the VM auth credentials are required before Docker Compose can
provision Grafana datasources. To rotate VM auth credentials manually,
run VM_AUTH_PASSWORD="$(openssl rand -base64 18)" ./scripts/rotate-vm-auth.sh
from the monitoring directory.
Subcommand: mon healthโ
postgresai mon health [--wait <seconds>]
--wait <seconds>โ wait up to<seconds>for services to become healthy (default:0, i.e. check once and return).
Subcommand: mon logsโ
postgresai mon logs [service] [options]
-f, --followโ follow logs.--tail <lines>โ number of trailing lines (default:all).
Subcommand: mon cleanโ
postgresai mon clean [--keep-volumes]
--keep-volumesโ keep data volumes (only stop and remove containers).
Subcommand group: mon targetsโ
Manage databases monitored by the local stack.
postgresai mon targets <subcommand> [args]
Subcommands
listโ list configured monitoring targets.add [conn-string] [name]โ add a Postgres instance to monitor. Both arguments are optional; missing values are prompted for interactively.remove <name>โ remove a monitoring target.test <name>โ test connectivity to a configured target.
Command: loginโ
Authenticate via browser (OAuth) or store an API key directly. This is
the shortest form of postgresai auth login; both commands use the same
options and behavior.
Usage
postgresai login # OAuth via browser
postgresai login --set-key <key> # store an API key directly
postgresai login --port 7777 --debug # use a fixed callback port with debug output
Options
--set-key <key>โ store an API key directly without going through the OAuth flow.--port <port>โ local callback server port (default: random).--debugโ enable debug output.
The browser flow opens your default browser, prompts for organization
selection, and writes the resulting API key to
~/.config/postgresai/config.json.
Command: authโ
Authentication and API-key management. auth is a command group; the
default subcommand is login, so plain postgresai auth triggers an
OAuth flow.
Usage
postgresai auth [subcommand] [options]
Subcommands
login(default) โ authenticate via browser (OAuth) or store an API key directly.show-keyโ show the current API key, masked.remove-keyโ remove the stored API key.
Subcommand: auth loginโ
postgresai auth # OAuth via browser
postgresai auth --set-key <key> # store an API key directly
postgresai auth login --port 7777 --debug # explicit form
For a shorter equivalent, use the top-level login
command.
Options
--set-key <key>โ store an API key directly without going through the OAuth flow.--port <port>โ local callback server port (default: random).--debugโ enable debug output.
The browser flow opens your default browser (OAuth with PKCE), prompts
for organization selection, and writes the resulting API key to
~/.config/postgresai/config.json.
postgresai login is also available as a top-level alias for
postgresai auth login (same options).
Command: joeโ
Run Joe SQL optimization commands on ephemeral DBLab thin clones. See the Joe from the CLI how-to for a task-oriented walkthrough.
The joe and projects commands ship in CLI 0.16, currently published
under the dev npm dist-tag: run them via npx pgai@dev โฆ /
npx postgresai@dev โฆ (or install with npm install -g postgresai@dev)
until 0.16 reaches latest.
Usage
postgresai joe <subcommand> [arguments] [options]
How it works
Every joe subcommand is synchronous: the CLI submits one raw Joe
command (the same text you could type at Joe in the Console or in chat),
then polls for the result until it is ready or the one-shot poll budget
(default 25 seconds) is exhausted. On budget expiry the CLI exits 0 and
prints a resume handle โ fetch the result later with
postgresai joe result <commandId>. Each invocation starts a fresh
Joe command; the command and its full result (plans, statistics,
recommendations) are stored in the Joe history in the PostgresAI
Console.
Running Joe commands requires the token owner to hold the
AllFeaturesUser or Admin role in the organization; other roles
receive 403 Forbidden.
Targeting. Every joe subcommand (except result) needs a target.
Provide it in one of three ways: pass --instance-id, pass --project,
or configure a default project once with
set-default-project <project> and omit
both flags. Resolution order is --instance-id, then --project, then
the stored default project โ an explicit flag always wins. With no flag
and no default project configured, the command errors and prompts you
to supply --instance-id (or --project).
Shared options (every subcommand except result)
--instance-id <id>โ target the Joe instance id directly (skips--projectresolution). Takes precedence over--projectand the default project.--project <id|alias>โ target a project by numeric id OR alias/name (case-insensitive; resolved via the projects API โ seeprojects). Requires the project to have a registered, active Joe instance. When omitted, falls back to the default project set byset-default-project.--budget <seconds>โ one-shot poll budget in seconds (default:25).--debugโ enable debug output.--jsonโ output the full result row as raw JSON (includesplan_text, structuredplan_json,plan_execution_text,plan_execution_json,stats,recommendations,queryid).
joe planโ
plan <sql> โ plan a query (EXPLAIN, plan-only โ no execution; the fast/safe default).
postgresai joe plan "select * from users where email = '[email protected]'" --project main-db
joe explainโ
explain <sql> โ EXPLAIN + EXPLAIN ANALYZE a query (executes on the DBLab clone).
postgresai joe explain "select * from users where email = '[email protected]'" --project 12
joe execโ
exec <sql> โ run arbitrary DDL/DML on the clone (e.g. create index, analyze, set planner parameters).
postgresai joe exec "create index i_users_email on users (email)" --instance-id 34
joe hypoโ
hypo <args> โ HypoPG hypothetical indexes (e.g. hypo "create index on users (email)", hypo desc, hypo reset).
joe activityโ
activity โ running-activity snapshot (pg_stat_activity) on the clone.
joe terminateโ
terminate <pid> โ pg_terminate_backend(pid) on the clone. The pid must be a bare positive integer; anything else is rejected client-side before any API call.
joe resetโ
reset โ reset/recreate the session's thin clone.
joe describeโ
describe <object> โ \d-family schema/relation/index metadata. Takes
--variant <variant> to select the \d-family form (default \d).
Supported variants: \d, \d+, \dt, \dt+, \di, \di+, \l,
\l+, \dv, \dv+, \dm, \dm+.
postgresai joe describe users --variant '\d+' --project main-db
joe resultโ
result <commandId> โ fetch a Joe command's output by id (resume a
budget-expired one-shot; accepts only --debug / --json).
postgresai joe result 3523
Output and exit codes for joeโ
Human-readable output prints command <id> ยท ok followed by whichever
sections the result contains: the response text, plan:, client-side
plan flags (โ โฆ, e.g. flagging a Seq Scan), execution plan (EXPLAIN ANALYZE):, stats:, recommendations:, and the queryid.
Exit codes:
0โ terminalokresult, or budget expired (resume by id).1โ terminalerrorresult,resulton a still-pending command, or any other failure.
Command: projectsโ
List the organization's projects, showing which ones have Joe ready.
This is org-level discovery (not a Joe endpoint): it powers
--project <id|alias> resolution for joe commands.
Usage
postgresai projects [--json] [--debug]
Output columns
PROJECT_IDโ numeric project id (usable as--project <id>).ALIASโ project alias (usable as--project <alias>;-if not set).PROJECTโ human-readable project name.JOEโreadywhen the project has an active Joe instance targetable byjoecommands;nootherwise.TUNNELโ whether the project's DBLab tunnel is connected.
With --json, each row also includes instance_id (the Joe instance id
that joe commands target โ usable as --instance-id) and
dblab_instance_id (the project's active DBLab instance, not used by
joe commands).
PROJECT_ID ALIAS PROJECT JOE TUNNEL
12 main-db Main DB ready yes
15 analytics Analytics no no
Command: issuesโ
Manage issues, comments, and action items in the PostgresAI Console.
Usage
postgresai issues <subcommand> [options]
All issues subcommands accept --debug (enable debug output) and
--json (force raw JSON output instead of the default human-friendly
YAML). When stdout is not a TTY (e.g. piped or redirected), JSON is
selected automatically.
Subcommands
listโ list issues.view <issueId>โ view issue details and comments.create <title> [options]โ create a new issue.update <issueId> [options]โ update an existing issue.post-comment <issueId> <content> [options]โ post a comment.update-comment <commentId> <content> [options]โ update an existing comment.files upload <path>โ upload a file to storage and print a markdown link.files download <url> [-o <path>]โ download a file from storage.action-items <issueId>โ list action items for an issue.view-action-item <id> [<id> ...]โ view one or more action items in detail.create-action-item <issueId> <title> [options]โ create an action item.update-action-item <actionItemId> [options]โ update an action item.
issues listโ
postgresai issues list [--status <status>] [--limit <n>] [--offset <n>]
--status <status>โ filter by status:open,closed, orall(default:all).--limit <n>โ maximum number of issues to return (default:20).--offset <n>โ number of issues to skip (default:0).
issues viewโ
postgresai issues view <issueId>
issues createโ
postgresai issues create <title> [options]
--org-id <id>โ organization ID (defaults to the configuredorgId).--project-id <id>โ project ID.--description <text>โ issue description (use\nfor newlines).--label <label>โ issue label; repeat to add multiple.--attach <path>โ attach a local file (uploads to storage and appends a markdown link to the description); repeatable.
issues updateโ
postgresai issues update <issueId> [options]
--title <text>โ new title (use\nfor newlines).--description <text>โ new description (use\nfor newlines).--status <value>โopen,closed,0, or1.--label <label>โ set labels; repeatable. If provided, replaces existing labels.--clear-labelsโ set labels to an empty list.--attach <path>โ attach a file; appends a markdown link to--description. If--descriptionis omitted, the existing description is fetched and the link appended to it.
issues post-commentโ
postgresai issues post-comment <issueId> <content> [options]
--parent <uuid>โ parent comment ID (for threaded replies).--attach <path>โ attach a file; appends a markdown link to the comment body. Repeatable.
issues update-commentโ
postgresai issues update-comment <commentId> <content> [options]
--attach <path>โ attach a file; appends a markdown link to<content>. Repeatable.
issues filesโ
# Upload a local file; prints the storage URL and a ready-to-paste markdown link.
postgresai issues files upload <path>
# Download a file from storage; without -o, derives the filename from the URL.
postgresai issues files download <url> [-o <output_path>]
Attaching files to issues and comments (--attach)โ
create, update, post-comment, and update-comment accept a
repeatable --attach <path> flag. Each file is uploaded to PostgresAI
storage and a markdown link is appended to the comment body or issue
description. Image extensions (.png, .jpg, .jpeg, .gif,
.webp, .svg, .bmp, .ico) render inline as ; other
files render as [](url). Multiple --attach flags preserve order;
each link goes on its own line.
# Attach a screenshot to a new comment
postgresai issues post-comment <issueId> "Saw this in prod" --attach screenshot.png
# Attach multiple files to a new issue
postgresai issues create "Slow query" --org-id 4 \
--description "Plan attached" --attach plan.txt --attach flame.svg
# Attach a file to an existing issue without changing the description
postgresai issues update <issueId> --attach trace.log
issues action-itemsโ
postgresai issues action-items <issueId>
postgresai issues view-action-item <actionItemId> [<actionItemId> ...]
issues create-action-itemโ
postgresai issues create-action-item <issueId> <title> [options]
--description <text>โ detailed description (use\nfor newlines).--sql-action <sql>โ SQL command to execute.--config <json>โ config change as JSON, e.g.'{"parameter":"work_mem","value":"64MB"}'. Repeatable.
issues update-action-itemโ
postgresai issues update-action-item <actionItemId> [options]
--title <text>,--description <text>โ update title or description.--done/--not-doneโ mark as done or not done.--status <value>โwaiting_for_approval,approved, orrejected.--status-reason <text>โ reason for the status change.--sql-action <sql>โ update the SQL command (use""to clear).--config <json>โ replace config changes; repeatable.--clear-configsโ remove all config changes.
Output format for issues commandsโ
By default, issues commands print human-friendly YAML to a terminal.
For scripting:
-
Pass
--jsonto force JSON output:postgresai issues list --json | jq '.[] | {id, title}' -
Or rely on auto-detection: when stdout is not a TTY, output is JSON automatically:
postgresai issues view <issueId> > issue.json
Command: reportsโ
List and download checkup reports stored in the PostgresAI Console.
Usage
postgresai reports <subcommand> [options]
Subcommands
list [options]โ list checkup reports.files [reportId] [options]โ list files (metadata only) of a checkup report.data [reportId] [options]โ fetch report file contents (markdown / JSON).
reports listโ
postgresai reports list [options]
--project-id <id>โ filter by project ID.--limit <n>โ maximum number of reports to return (default:20, max:100).--before <date>โ show reports created before this date (YYYY-MM-DD,DD.MM.YYYY, etc.).--allโ fetch all reports (paginated automatically). Mutually exclusive with--before.--jsonโ output raw JSON.
reports filesโ
postgresai reports files [reportId] [options]
Either reportId or --check-id is required.
--type <type>โ filter by file type:jsonormd.--check-id <id>โ filter by check ID (e.g.H002).--jsonโ output raw JSON.
reports dataโ
postgresai reports data [reportId] [options]
--type <type>โ filter by file type:jsonormd.--check-id <id>โ filter by check ID (e.g.H002).--formattedโ render markdown with ANSI styling (experimental).-o, --output <dir>โ save files to a directory (using their original filenames).--jsonโ output raw JSON.
Command: mcpโ
MCP (Model Context Protocol) server integration for AI coding tools.
Usage
postgresai mcp <subcommand> [options]
Subcommands
startโ start the MCP stdio server, exposing PostgresAI tools.install [client]โ install MCP client configuration for a supported AI coding tool.
mcp startโ
postgresai mcp start [--debug]
Starts an MCP server over stdio. Intended to be launched by an MCP client (e.g. Cursor, Claude Code) rather than invoked directly.
mcp installโ
postgresai mcp install [client]
Installs an mcpServers.postgresai entry pointing at the absolute
path of the pgai binary that invoked mcp install, with mcp start as its arguments.
client may be one of:
cursorโ writes to~/.cursor/mcp.json.claude-codeโ runsclaude mcp add -s user postgresai <pgai> mcp start.windsurfโ writes to~/.windsurf/mcp.json.codexโ writes to~/.codex/mcp.json.
If client is omitted, you are prompted to choose interactively
(1=Cursor, 2=Claude Code, 3=Windsurf, 4=Codex).
The pinned command path is the absolute path resolved at install
time. When mcp install is run via npx or bunx, that path points
into the package cache and may be garbage-collected. For a stable
install, run mcp install from a globally installed CLI
(npm install -g postgresai or brew install postgresai), or re-run
mcp install after each CLI upgrade.
A typical Cursor entry written by mcp install looks like:
{
"mcpServers": {
"postgresai": {
"command": "<absolute-path-to-pgai>",
"args": ["mcp", "start"]
}
}
}
The command value is the absolute path resolved by mcp install at
install time. Typical values:
/opt/homebrew/bin/pgaiโ Homebrew on Apple Silicon macOS/usr/local/bin/pgaiโ Homebrew on Intel macOS ornpm install -gon Linux/macOS~/.nvm/versions/node/<version>/bin/pgaiโnpm install -gunder nvm~/.npm/_npx/<hash>/node_modules/.bin/pgaiโ invoked vianpx(ephemeral; see the note above)
To point the server at a non-production endpoint, add an env block
manually:
"env": {
"PGAI_API_BASE_URL": "https://v2.postgres.ai/api/general/",
"PGAI_UI_BASE_URL": "https://console-dev.postgres.ai"
}
MCP tools exposed
The 0.15 MCP server registers 15 tools in four groups.
Issues:
list_issuesโ same JSON aspostgresai issues list.view_issueโ view a single issue with its comments.create_issueโ create a new issue.update_issueโ update title / description / status / labels.post_issue_commentโ post a comment.update_issue_commentโ update an existing comment.
Action items:
list_action_itemsโ list action items for an issue.view_action_itemโ view one or more action items with full detail.create_action_itemโ create an action item (title, description, optionalsql_actionand config changes) for an issue.update_action_itemโ mark done / not done, approve / reject, or edit an action item.
Reports: (new in 0.15 โ the only place the reports capability is exposed to AI agents)
list_reportsโ list checkup reports (metadata: id, project, status, timestamps; supportsbefore_datefiltering).list_report_filesโ list files in a report (per-checkjson/mdfiles; filter byreport_id,type, orcheck_id).get_report_dataโ fetch report file content (type=mdfor analysis,type=jsonfor raw check data).
Files:
upload_fileโ upload a local file and return the storage URL plus a ready-to-paste markdown link.download_fileโ download a file from storage.
The issue / comment tools accept an optional attachments: string[] of
local file paths. Each file is uploaded to PostgresAI storage and the
resulting markdown link is appended to the comment body or issue
description, using the same image-extension rules as the --attach
CLI flag.
For post_issue_comment and update_issue_comment, either content or
attachments must be non-empty (attachments alone are allowed). For
update_issue with attachments but no description, the existing
description is fetched first and the new links are appended to it.
MCP threat modelโ
The MCP server runs in your local user account with your PostgresAI API key. It treats the connected MCP client (the LLM agent) as trusted โ the same way the CLI treats you when you type a command. In particular:
upload_fileand theattachments: string[]parameter on the issue / comment tools read any local file the CLI process can read, including secrets like~/.ssh/id_rsa,~/.aws/credentials, or~/.config/postgresai/config.json(which contains your own API key). The file's bytes are uploaded to PostgresAI storage and the resulting URL becomes visible to anyone with read access to the issue or comment it ends up in.download_filewrites to any path the CLI process can write to whenoutput_pathis supplied (~/.ssh/authorized_keys,~/.bashrc, etc. are all fair game). Whenoutput_pathis omitted, downloads are restricted to the current working directory.
This is fine when the agent and the upstream context the agent is reading are trusted. It is not safe to run this MCP server against an agent that is processing untrusted text (issue bodies, comments, web pages, third-party docs) without additional sandboxing โ a prompt-injection in any input the agent reads could be used to exfiltrate local secrets or write arbitrary files. If you need to expose this MCP server to such an agent, run the agent (and this server) in a container or restricted user account that has no access to anything sensitive.
Command: set-default-projectโ
Store the default project used for checkup uploads and other
project-scoped operations.
postgresai set-default-project <project>
Command: set-storage-urlโ
Store the storage base URL used for file uploads. Equivalent to setting
PGAI_STORAGE_BASE_URL permanently in the configuration file.
postgresai set-storage-url <url>
Configurationโ
The CLI stores configuration in ~/.config/postgresai/config.json,
including:
- API key
- API / UI / storage base URLs
- Organization ID
- Default project
Configuration priorityโ
API key resolution order:
- Command-line option (
--api-key). - Environment variable (
PGAI_API_KEY). - User config file (
~/.config/postgresai/config.json). - Legacy project config (
.pgwatch-config).
Base URL resolution order:
- API base URL (
apiBaseUrl):- Command-line option (
--api-base-url). - Environment variable (
PGAI_API_BASE_URL). - User config file (
baseUrlin~/.config/postgresai/config.json). - Default:
https://postgres.ai/api/general/.
- Command-line option (
- UI base URL (
uiBaseUrl):- Command-line option (
--ui-base-url). - Environment variable (
PGAI_UI_BASE_URL). - Default:
https://console.postgres.ai.
- Command-line option (
- Storage base URL (
storageBaseUrl):- Command-line option (
--storage-base-url). - Environment variable (
PGAI_STORAGE_BASE_URL). - Value stored by
postgresai set-storage-url. - Default:
https://postgres.ai/storage.
- Command-line option (
A single trailing / is stripped from URL values to ensure consistent
path joining.
Environment variablesโ
PGAI_API_KEYโ API key for PostgresAI services.PGAI_API_BASE_URLโ API endpoint for backend RPC (default:https://postgres.ai/api/general/).PGAI_UI_BASE_URLโ UI endpoint for browser routes (default:https://console.postgres.ai).PGAI_STORAGE_BASE_URLโ storage endpoint for file uploads.PGAI_MON_PASSWORDโ default password for the monitoring role created byprepare-db.PGPASSWORDโ admin password used byprepare-db/unprepare-dbwhen--admin-passwordis not given.SUPABASE_ACCESS_TOKEN,SUPABASE_PROJECT_REFโ credentials forprepare-db --supabase.
Examplesโ
For production (uses default URLs):
postgresai auth --debug
For staging / development environments:
# Linux / macOS (bash, zsh)
export PGAI_API_BASE_URL=https://v2.postgres.ai/api/general/
export PGAI_UI_BASE_URL=https://console-dev.postgres.ai
postgresai auth --debug
# Windows PowerShell
$env:PGAI_API_BASE_URL = "https://v2.postgres.ai/api/general/"
$env:PGAI_UI_BASE_URL = "https://console-dev.postgres.ai"
postgresai auth --debug
Via CLI options (overrides environment variables):
postgresai auth --debug \
--api-base-url https://v2.postgres.ai/api/general/ \
--ui-base-url https://console-dev.postgres.ai