postgresql-agent
PostgreSQL Read-Only Agent
A production-ready Agency Swarm agent focused on answering business questions with validated read-only SQL. It packages a configurable onboarding workflow, strict guardrails, and a toolbelt for inspecting PostgreSQL schemas, describing tables, and executing safe SELECT/CTE queries.
β¨ Highlights
- Read-only enforcement β
input_guardrail.pyandensure_read_only_sqlblock INSERT/UPDATE/DDL intent before any tool runs. - Configurable onboarding β
onboarding_tool.pygeneratesonboarding_config.py, allowing custom agent name/description, model selection (gpt-4.1,gpt-5,gpt-5.1), and guardrail toggles. - Purpose-built tooling
PgListSchemasToolβ enumerate non-system schemas.PgListTablesToolβ list tables within a schema.PgDescribeTableToolβ inspect column metadata.PgRunReadQueryToolβ execute validated SQL with row limits and timeouts.
- Optimized instructions β
postgresql_agent/instructions.mdkeeps responses concise, SQL-first, and transparent about truncation/limits.
π Repository Layout
postgresql-agent/ βββ agency.py # Optional multi-agent entry point βββ onboarding_tool.py # CLI to create onboarding_config.py βββ postgresql_agent/ β βββ __init__.py # expose create_postgresql_agent β βββ instructions.md # system prompt for the agent β βββ input_guardrail.py # read-only guardrail logic β βββ postgresql_agent.py # agent factory + standalone runner β βββ tools/ # PostgreSQL tools (schemas/tables/queries) β βββ utils/ # shared DB connector + SQL validator βββ requirements.txt βββ README.md
π§° Requirements
- Python 3.11+ (3.12 recommended)
- PostgreSQL connection string with read access
- OpenAI API key with access to the selected model
βοΈ Setup
- Clone & create a virtual environment
bash
git clone <repo-url> postgresql-agent cd postgresql-agent python3 -m venv .venv source .venv/bin/activate - Install dependencies
bash
pip install -r requirements.txt - Create
.envbashOPENAI_API_KEY=sk-... PG_URL=postgresql://user:pass@host:5432/dbname # Optional PG_DEFAULT_SCHEMA=public PG_DEFAULT_TABLE=users PG_TEST_SQL="SELECT 1" - Generate the onboarding config
bashThe CLI serializes your selections to
python onboarding_tool.pyonboarding_config.py. Re-run anytime you need to update the agent identity or model.
βΆοΈ Running the Agent
Standalone evaluation
PYTHONPATH=. python postgresql_agent/postgresql_agent.py
The script spins up the agent, runs a small suite of prompts (schema listing, table description, write attempt), and prints the responses. Guardrail violations are logged but donβt crash the process.
Import into your own agency
from postgresql_agent import create_postgresql_agent postgres_agent = create_postgresql_agent()
Pass postgres_agent into your Agency communication flow or orchestrator. The guardrail and tools are wired up automatically based on onboarding_config.py.
π Guardrails & Validation
- Input guardrail (
input_guardrail.py) inspects raw user text for write intent and blocks anything that isnβt satisfiable with SELECT/CTE/VALUES SQL. - SQL validator (
pg_readonly_validator.py) parses statements viasqlglot, rejects forbidden AST nodes (INSERT/UPDATE/DDL/LOCK/etc.), and enforces read-only root expressions. - DB connector (
pg_connection.py) opens sessions withSET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY, statement timeouts, and idle-in-transaction limits.
These layers ensure the agent cannot modify data even if a malicious prompt slips through.
π οΈ Tool Reference
| Tool | Description | Key Inputs |
|---|---|---|
PgListSchemasTool | Lists all non-system schemas. | none |
PgListTablesTool | Lists tables for a schema. | target_schema |
PgDescribeTableTool | Returns column name/type/nullability. | target_schema, table |
PgRunReadQueryTool | Executes validated read-only SQL. | sql, max_rows, timeout_ms |
All tools read PG_URL from the environment and reuse the shared connector/validator utilities.
β Testing & Troubleshooting
- Agent demo:
PYTHONPATH=. python postgresql_agent/postgresql_agent.py - Agency console:
python agency.py - Common issues
ImportError: onboarding_configβ Runpython onboarding_tool.py.Error: database_url is requiredβ EnsurePG_URLis set in.env.- Guardrail trips on valid SELECT β Double-check the prompt doesnβt mention βupdateβ, βdeleteβ, or other write verbs.
π€ Contributing
- Fork & branch.
- Keep edits ASCII-clean and documented.
- Include testing notes (commands + outcomes) in your PR.
Ideas, issues, or enhancements for additional tooling (e.g., query templating, caching, or warehouse fallbacks) are always welcome!