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

PGBHub (pgb) Developer & Agent Guide

One set of environment variables configures every SDK, the CLI and the MCP server. Learn how developers and AI agents connect, query, and generate type-safe models without spending AI tokens.

1

The Mental Model: Local Mock & Cloud

Whether you are an engineer writing application code or an LLM autonomous agent orchestrating database tasks, pgb is configured the same way everywhere: point PGBHUB_ENDPOINT at a local mock gateway while wiring things up, then at PGBHub Cloud for real data.

Local Mock GatewayOffline & Free
  • pgb dev serves canned responses on 127.0.0.1:4000.
  • Covers /sql, /auth, /mail/send, /storage and /functions routes.
  • Good for wiring clients and unit tests offline.
  • Does not run real queries or your function code.
PGBHUB_ENDPOINT=http://127.0.0.1:4000
PGBHub Cloud & PodsManaged Edge
  • PostgreSQL 18 with PgBouncer connection pooling.
  • Daily snapshots copied to offsite object storage.
  • Dedicated pods for single-organization isolation.
PGBHUB_ENDPOINT=https://console.pgbhub.com
Same code, different endpoint. Your SDK calls do not change between the local mock and the cloud; only PGBHUB_ENDPOINT and the key do. Validate real behavior (queries, RLS, functions) against a PGBHub project before you ship.
2

60-Second Quickstart

app.ts
import { createClient } from "@pgb/sdk";

// Options fall back to PGBHUB_ENDPOINT, PGBHUB_API_KEY and PGBHUB_DATABASE
const pgb = createClient({
  endpoint: process.env.PGBHUB_ENDPOINT || "https://console.pgbhub.com",
  apiKey: process.env.PGBHUB_API_KEY, // project secret key, server-side only
  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: "[email protected]",
    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 via the HTTP Database Gateway
  const result = await pgb.db.query(
    "SELECT id, name, email FROM users WHERE email = $1",
    ["[email protected]"]
  );
  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 Generationpgb CLI (@pgb/sdk)
npx pgb pull --db myapp --out pgbhub.d.ts

Run inside a project with @pgb/sdk installed. Pulls your database's live schema.json and writes TypeScript declarations that give pgb.table() table and column autocomplete.

Python Pydantic v2 Generationpgbhub CLI
python -m pgbhub.cli pull --db myapp --out models.py

Generates Pydantic v2 models for each table, with optional fields for nullable columns. The pgbhub pull console script does the same.

When is AI used?

AI is opt-in and only used when you ask the PGBHub Cloud console to suggest business actions from your schema. Type generation and schema pulls never call an AI model.

4

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

PGBHub supports AI coding agents through its Model Context Protocol (MCP) server (@pgb/mcp, stdio transport). It is not on npm yet: clone github.com/PGBHub/pgb-mcp, run npm install && npm run build, and point your client at dist/index.js. Once it is published, npx -y @pgb/mcp works too.

How to Generate Your Secret API Key:

Project keys live under Project Settings & API Keys in the console: a secret key (pgb_sec_...) for servers and agents, and a publishable key (pgb_pub_...) for browsers and apps. Account-wide keys (pgb_live_...) are under API Keys & AI Agent Access on your account page. Give agents a project key so they can reach only that project.

Claude Desktop (claude_desktop_config.json) / Cursor (.cursor/mcp.json)
{
  "mcpServers": {
    "pgbhub": {
      "command": "node",
      "args": ["/absolute/path/to/pgb-mcp/dist/index.js"],
      "env": {
        "PGBHUB_API_KEY": "<your PGBHub API key>",
        "PGBHUB_PROJECT_ID": "<your project id>",
        "PGBHUB_ENDPOINT": "https://console.pgbhub.com"
      }
    }
  }
}
Recommended AI Agent System Prompt
You are programming with the PGBHub (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.db.query(query, [params]) (TypeScript only). The Python SDK has table() CRUD and actions; the Go and Rust SDKs have auth and actions; none of them has a raw SQL method yet.
- Never interpolate user input directly into SQL strings.
- In TypeScript, import from @pgb/sdk. In Python, import from pgbhub.
- Configure every SDK, the pgb CLI and the MCP server with the same variables: PGBHUB_ENDPOINT=https://console.pgbhub.com, PGBHUB_API_KEY=<key>, PGBHUB_DATABASE=<db>, PGBHUB_PROJECT_ID=<project id>.
- Read API keys from environment variables. Never hard-code or log them, and never ship the secret key (pgb_sec_) in frontend code.
- For offline wiring, run "pgb dev" and set PGBHUB_ENDPOINT=http://127.0.0.1:4000. It returns canned responses and does not run real queries or functions.
5

Production Recipes

Recipe 1: Scheduled Job + Background Processing (TypeScript)

// Uses the pgb client from the quickstart (endpoint https://console.pgbhub.com)

// 1. Schedule a nightly reconciliation job against a serverless function
await pgb.cron.create("nightly-reconciliation", "0 2 * * *", "function", {
  function_name: "reconcile-ledger",
});

// 2. Enqueue a one-off background job, e.g. from a webhook handler
const payout = { fromId: "acct_123", toId: "acct_456", amount: 2500 };
const job = await pgb.jobs.enqueue(
  "send-payout",
  "function",
  { function_name: "run-payout" },
  { payload: payout, idempotencyKey: "payout-acct_123-2026-10-22" }
);

console.log("Queued job:", job.id, job.status);

Recipe 2: Vector Search / Embeddings with pgvector (TypeScript)

// Needs the vector extension enabled for the database (console > Extensions)
async function searchDocuments(queryEmbedding: number[], limit = 5) {
  const result = await pgb.db.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`,
    [JSON.stringify(queryEmbedding), limit]
  );
  return result.rows;
}