psql · PostgreSQL Global Development Group

PostgreSQL psql for AI Agents

Query PostgreSQL non-interactively with explicit credentials, output, transactions, and write boundaries.

Official toolOperational risk: R0R3verified
Agent readiness
83/100
Evidence confidence
verified
Documentation checked
2026-07-10
Independently tested version
18.1

Install for an Agent

Choose an official installation path that matches the runtime. Pin a version for team or CI use, then record the version before the first task.

Homebrew libpqRecommended
macos · linux
$ shell
brew install libpq
Authentication and Minimum Permissions
Grant only the permissions the task needs. Pass credentials through environment variables or a platform secret store, never through prompts, repositories, or logs.
Authentication requiredHeadless authentication supported

Use a read-only database role, TLS, and a database/schema search path limited to the task.

Methods
connection URI, password file, service file, peer authentication
Secret environment variables
DATABASE_URL, PGHOST, PGUSER, PGPASSWORD, PGSERVICE
Credential storage
For headless runs, inject DATABASE_URL, PGHOST, PGUSER, PGPASSWORD, PGSERVICE from the CI or platform secret manager at process start. For local interactive use, prefer the CLI or operating-system credential store when the official client supports one. Never save values in repository files.
Agent and Environment Compatibility
Confirm shell access first, then check the platform, network boundary, and credential path.
claude-codecodexgemini-clicopilot-cli
Environments
local, ci, container, headless, remote
Platforms
macos, linux, windows

Structured Output for Reliable Automation

Prefer a machine-readable format. Treat stdout as the result channel and stderr as diagnostics so the agent can parse failures separately.

csv · unaligned text · html · latex
Use --csv or --tuples-only or --no-psqlrc where supported and keep diagnostic logs on stderr.
--csv--tuples-only--no-psqlrc

No independently captured output sample

Structured-output support currently comes from official documentation. CLI Finder does not show a guessed example or invented schema before a bounded, non-destructive execution captures stdout.

R0–R3 Command Risk Guide

Risk is assigned per command. R0 is local or remote read-only, R1 is reversible local write, R2 changes remote state, and R3 can be irreversible or production-impacting.

Read-only does not mean public

R0 only means the command does not change local or remote state. A read-only command may still return secrets, identity data, configuration, or production data. Expose only the minimum needed for the task, and never place it in logs, prompts, or commits.

R0Run a read-only query
Executes a bounded SELECT and emits CSV.
$ shell
psql "$DATABASE_URL" --no-psqlrc --csv --command "SELECT * FROM table_name LIMIT 20"
IdempotentSensitive output
R2Update rows
Changes database records and should run in a reviewed transaction.
$ shell
psql "$DATABASE_URL" --command "BEGIN; UPDATE table_name SET ...; COMMIT;"
Confirmation requiredMay repeat a change
R3Drop a database
Permanently deletes a database.
$ shell
dropdb --if-exists DATABASE_NAME
Confirmation requiredMay repeat a change

How the Agent Readiness Score Is Built

Readiness describes how reliably an agent can operate the tool. It does not make every command safe and it does not replace an independent execution test.

Documentation indicates an agent-readiness score of 83/100. A bounded local smoke test is recorded for 18.1; review its limitations before relying on untested commands.

Structured output
Use --csv or --tuples-only or --no-psqlrc where supported and keep diagnostic logs on stderr.
18/20
x
Headless operation
Official documentation describes a non-interactive authentication or execution path.
14/15
x
Safety controls
CLI Finder separates read commands from commands that require confirmation.
11/15
x
Determinism
Commands use explicit arguments and documented output controls where available.
8/10
x
Authentication
Use a read-only database role, TLS, and a database/schema search path limited to the task.
8/10
x
Documentation
This entry cites official documentation checked on 2026-07-10.
9/10
x
Installation
Official installation paths cover macOS, Linux, and Windows.
8/8
x
Maintenance
Maintenance is documented by the official publisher source.
5/7
x
Agent artifacts
CLI Finder can generate registry-derived skills and policies; the tool itself was not credited with shipping them.
2/5
x

Generate a Skill or Agent Policy

Choose an agent and safety mode to generate a copyable artifact with installation, allowed commands, approval boundaries, and the evidence limitation.

Generated artifact preview
SKILL.md
---
name: psql-agent-workflow
description: Use PostgreSQL psql for PostgreSQL queries, schema inspection, CSV export with explicit command risk and evidence boundaries.
---

# PostgreSQL psql agent workflow

Use this skill when the task needs PostgreSQL queries, schema inspection, CSV export, migration checks.

## Evidence boundary

- Registry confidence: `verified`
- Documentation checked: `2026-07-10`
- Locally tested version: `18.1`
- Treat only the recorded executed checks as independently verified; every unlisted command remains documentation-only.

## Executed smoke checks

- `psql --version` — passed; exit 0. The recorded smoke check completed successfully.
- `psql --help` — passed; exit 0. The recorded smoke check completed successfully.

## Installation

- Homebrew libpq (macos, linux): `brew install libpq`

## Authentication

- Methods: connection URI, password file, service file, peer authentication
- Secret environment variables: `DATABASE_URL`, `PGHOST`, `PGUSER`, `PGPASSWORD`, `PGSERVICE`
- Minimum permissions: Use a read-only database role, TLS, and a database/schema search path limited to the task.
- Credential storage: For headless runs, inject DATABASE_URL, PGHOST, PGUSER, PGPASSWORD, PGSERVICE from the CI or platform secret manager at process start. For local interactive use, prefer the CLI or operating-system credential store when the official client supports one. Never save values in repository files.
- Never print, persist, or commit credential values.

## Allowed commands (read-only)

- `psql "$DATABASE_URL" --no-psqlrc --csv --command "SELECT * FROM table_name LIMIT 20"` — R0: Executes a bounded SELECT and emits CSV.

## Commands requiring explicit approval (read-only)

- None recorded.

## Forbidden commands (read-only)

- R2 `psql "$DATABASE_URL" --command "BEGIN; UPDATE table_name SET ...; COMMIT;"` — Changes database records and should run in a reviewed transaction.
- R3 `dropdb --if-exists DATABASE_NAME` — Permanently deletes a database.

## Execution rules

1. Mode boundary: R0 exact commands may be used; R1, R2, and R3 commands are forbidden.
2. Confirm the selected account, project, context, database, namespace, or environment before any command.
3. Prefer structured output using `--csv`, `--tuples-only`, `--no-psqlrc`.
4. Capture the exact command, exit code, stdout, and stderr separately.
5. A generated prefix policy must prompt unless that exact prefix is explicitly marked suffix-safe; do not infer safety from the executable name.
6. Never broaden credentials or disable safety controls to make a command succeed.

## Official sources

- [PostgreSQL psql documentation](https://www.postgresql.org/docs/current/app-psql.html)

CLI vs MCP vs API for This Task

CLI
Use the CLI on a developer machine, in CI, or in a container when the task should reuse existing shell state, credentials, and scripts and remain directly observable.
MCP
Consider MCP when the agent benefits from controlled tool definitions, delegated identity, or centrally governed server-side access.
API
Use the direct API for persistent application integrations, high-volume requests, or event-driven work where starting a process adds unnecessary overhead.
Read the full CLI vs MCP guide

Verification History and Official Evidence

CLI Finder records documentation review separately from real execution. Installation, help, exit codes, and output cannot be called Verified until they were run.

Current evidence boundary
The installed psql binary, version output, help rendering, and zero exit status were checked locally. No server connection, authentication, SQL query, CSV output, transaction, write, or destructive database command was executed.
Evidence confidence
verified
Independently tested version
18.1 · 2026-07-10
Test environment
macOS 26.5.1 (arm64), local non-interactive shell

Executed checks

  • PassedExit code: 0
    psql --version

    The recorded smoke check completed successfully.

    stdout excerpt

    psql (PostgreSQL) 18.1
  • PassedExit code: 0
    psql --help

    The recorded smoke check completed successfully.

Official sources
Open the official material to confirm the current version and command behavior.

Alternatives and Related Paths

Query and administer local or remote databases through scriptable commands.
Run non-interactive MySQL queries while isolating credentials and database writes.
Inspect and transform local SQLite databases with stable batch and machine-readable output modes.
Query local files and analytical data directly with fast SQL and structured exports.
Use psql non-interactively with a read-only role, bounded queries, and machine-readable output.
Pair Codex with deterministic local tools and add remote CLIs only when the sandbox and approval policy allow the task.
Choose CLI for shell-native local and CI work; choose MCP when typed discovery and mediated remote permissions matter more.

Questions About PostgreSQL psql for AI Agents