Documentation/Developer & AI Agent Guide
Unified Local & Cloud Mental Model

PGBox (`pgb`) Developer & Agent Guide

Seamlessly switch between local Docker testing and production cloud with zero code rewrites. Learn how human developers and autonomous AI agents discover, query, and generate type-safe models with zero token costs.

1

The Unified Mental Model: Local & Cloud Together

Whether you are an engineer writing application code or an LLM autonomous agent orchestrating database tasks, pgb provides a single unified interface that works identically across environments.

Local EnvironmentOffline & Free
  • 100% offline & free with local Docker.
  • Standard PostgreSQL 16 compatibility.
  • Sub-millisecond latency for local unit tests.
  • Git-versioned portable database actions.
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/myapp
PGBox Cloud & PodsManaged Edge
  • Sub-ms Edge wire proxy & connection pooling.
  • Automated Cloudflare R2 backup replication.
  • Threat detection SOC & rate limit shields.
  • Dedicated VPS Pods for 100% isolated enterprise compute.
PGBOX_ENDPOINT=https://console.pgbhub.com
The Invariant: Zero Code Rewrites. You write your queries, tables, and actions once. Promoting your application from local testing to production cloud is strictly a matter of swapping your environment variable.
2

60-Second Quickstart

app.ts
import { createClient } from "@pgbox/client";

// Initializes from environment variables (PGBOX_ENDPOINT, PGBOX_API_KEY, or DATABASE_URL)
const pgb = createClient({
  endpoint: process.env.PGBOX_ENDPOINT || "https://console.pgbhub.com",
  apiKey: process.env.PGBOX_API_KEY,
  database: "myapp",
});

async function main() {
  // 1. High-level Typed Table CRUD
  const users = pgb.table("users");

  // Create
  const newUser = await users.create({
    name: "Alex Rivera",
    email: "alex@example.com",
    role: "admin",
  });
  console.log("Created user:", newUser);

  // Find with filters & pagination
  const activeAdmins = await users.find(
    { role: "admin" },
    { limit: 10, orderBy: "created_at", order: "DESC" }
  );
  console.log("Active admins:", activeAdmins);

  // 2. Safe Parameterized Raw SQL
  const result = await pgb.sql(
    "SELECT id, name, email FROM users WHERE email = $1",
    ["alex@example.com"]
  );
  console.log("Query result:", result.rows);
}

main().catch(console.error);
3

Deterministic Code Generation (Zero AI Tokens)

Developers and build pipelines can generate 100% type-safe TypeScript interfaces and Python Pydantic models without spending a single AI token or incurring LLM latency.

TypeScript Type Generation@pgbox/cli
npx @pgbox/cli pull --db myapp --out pgbox.d.ts

Introspects live information_schema and outputs TypeScript interfaces with complete table and column autocomplete.

Python Pydantic v2 Generationpgbox CLI
python -m pgbox.cli pull --db myapp --out models.py

Generates clean Pydantic v2 classes with validated type annotations, foreign keys, and optional fields.

When is AI used?

AI generation is strictly opt-in and reserved for when developers log into the PGBox Cloud Web Console to synthesize custom business actions from natural-language prompts (e.g. "Write an action that reconciles pending subscriptions"). Routine model generation and schema synchronization always run deterministically for free.

4

Guide for Autonomous LLM Agents (Cursor, Claude, Antigravity)

PGBox provides first-class support for autonomous AI coding agents via the Model Context Protocol (MCP) server (@pgbox/mcp).

How to Generate Your Secret API Key:

Navigate to API Keys & Access in your PGBox Cloud Web Dashboard or PGBox Admin Console, and click "Generate New API Key". You can copy the generated token (pgb_live_...) or click "Copy MCP Config" to get the JSON snippet with your key already filled in.

Claude Desktop / Cursor MCP Configuration
{
  "mcpServers": {
    "pgbox": {
      "command": "npx",
      "args": [
        "-y",
        "@pgbox/mcp",
        "--endpoint", "https://console.pgbhub.com",
        "--key", "YOUR_PGBOX_API_KEY",
        "--db", "myapp"
      ]
    }
  }
}
Recommended AI Agent System Prompt
You are programming with the PGBox (pgb) unified database client.
- Always use pgb.table('table_name') for standard CRUD operations (find, findFirst, create, update, delete).
- For raw SQL, always use parameterized queries with $1, $2 placeholders via pgb.sql(query, [params]).
- Never interpolate user input directly into SQL strings.
- In TypeScript, import from @pgbox/client. In Python, import from pgbox.
- For offline or local testing, set DATABASE_URL=postgresql://postgres:postgres@localhost:5432/<dbname>.
- In production, set PGBOX_ENDPOINT=https://console.pgbhub.com and PGBOX_API_KEY=<key>.
5

Production Recipes

Recipe 1: Atomic Multi-Table Transaction (TypeScript)

await pgb.transaction(async (tx) => {
  // 1. Deduct sender
  await tx.sql("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, fromId]);
  // 2. Credit receiver
  await tx.sql("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, toId]);
  // 3. Log audit ledger
  await tx.table("transfers").create({ from_id: fromId, to_id: toId, amount });
});

Recipe 2: Vector Search / Embeddings with `pgvector` (Python)

def search_documents(query_embedding: list[float], limit: int = 5):
    query = """
    SELECT id, title, content, 1 - (embedding <=> $1::vector) AS similarity
    FROM documents
    WHERE 1 - (embedding <=> $1::vector) > 0.75
    ORDER BY embedding <=> $1::vector ASC
    LIMIT $2;
    """
    return client.sql(query, [str(query_embedding), limit])