# PgBeam Documentation (Full) > Safe Postgres access for AI agents and humans. A scoped connection string and a hosted MCP endpoint with read-only enforcement, table allowlists, row-level policies, PII masking, query budgets, a kill-switch, a full audit trail, SCRAM auth, anomaly detection, webhook and SIEM audit export, instant branches with always-rollback dry-run, and safe-migration linting. Works with any Postgres, with zero code changes. ## Developer resources - PgBeam REST API (docs): https://pgbeam.com/docs/api - PgBeam OpenAPI 3.1 spec: https://pgbeam.com/openapi.json - PgBeam MCP server (docs): https://pgbeam.com/docs/mcp ; card at https://pgbeam.com/.well-known/mcp/server-card.json - PgBeam CLI: https://pgbeam.com/docs/cli - PgBeam TypeScript SDK: https://pgbeam.com/docs/ts-sdk - PgBeam Go SDK: https://pgbeam.com/docs/go-sdk - API catalog: https://pgbeam.com/.well-known/api-catalog ## Key pages - Features: https://pgbeam.com/features - Pricing: https://pgbeam.com/pricing - About: https://pgbeam.com/about - Contact: https://pgbeam.com/contact --- # PgBeam Documentation URL: https://pgbeam.com/docs/README Description: ## PgBeam Documentation Source files for pgbeam.com/docs — the documentation for PgBeam, a globally distributed PostgreSQL proxy platform with connection pooling and query caching. ## Structure ## Contributing Documentation is written in MDX (Markdown + JSX). Pages use Fumadocs conventions. To preview locally, run from the monorepo root: ## License Apache 2.0 — see LICENSE. --- # Agent Credentials URL: https://pgbeam.com/docs/agent-credentials Description: Scoped, revocable Postgres credentials and MCP tokens for AI agents. The agent never sees your real database credentials. An agent credential is a PgBeam-issued identity for one agent. It comes with a scoped Postgres username and password and an API token for the hosted MCP endpoint. PgBeam authenticates the credential itself and connects upstream with your stored database credentials, so the agent never sees your real ones. Every credential is scoped to a policy, revocable, and kill-switchable on its own. The same credential model issues identities for people, not just agents. Every credential carries a `principal_type` of `agent` or `human`. A human credential gives an analyst or contractor a scoped, masked, audited connection with the exact same guardrails an agent gets. Throughout these docs, "agent credential" is the common case; the mechanics are identical for human credentials. See Policies for project default and per-database policies that cover your application's passthrough connections too. ## Create a credential Open your project, go to **Credentials**, and select **New credential**. Pick a policy profile and copy the connection string and MCP URL from the result. The response includes both front doors: ## What a credential carries Field Description Postgres user `agent_`, used in the scoped connection string. Postgres secret Generated password. Shown once at creation. MCP token `pba_…` bearer token for the hosted MCP endpoint. Policy profile The rules enforced for this credential. See Policies. Status Active, revoked, or killed. ## Right-size its policy from traffic Once a credential has run for a while, PgBeam can derive the tightest policy that would still pass everything it has legitimately run, from its audit history: the exact tables it touched, the statement kinds it used, read-only when it never wrote, and a `max_rows` ceiling from its observed result sizes. The candidate is proven safe by replaying it against that same history and is advisory only. It loads into the policy editor for review and never changes anything until you save. See Right-size from traffic. ## Revoke a credential Revocation is immediate. The next statement on that credential is refused. To stop an agent without deleting it, use the kill-switch. The kill-switch pauses access with no credential rotation; revocation removes the credential entirely. ## Rotate a credential Rotation issues a fresh Postgres password and MCP token for the credential **in place**: the id, username, name, policy, and audit history stay the same. Connections using the old password are dropped within seconds, so update your agent before its next call. The new secrets are shown once. The same operation is available in the **Credentials** tab (the rotate action on a credential) and over the API as `POST /v1/projects/{project_id}/agents/{agent_id}/rotate`. Need zero overlap instead? Issue a second credential, cut the agent over, then revoke the first. Rotation in place is simpler, but two credentials let you verify the new one before retiring the old. Issue one credential per agent. A per-agent credential gives you a clean audit trail and lets you revoke or kill a single agent without affecting the others. ## Authentication model PgBeam terminates authentication itself. The credential's password is verified against the credential, not passed through to your database. Authentication uses SCRAM-SHA-256 by default, so the password never crosses the wire, with cleartext-over-TLS available as a fallback for clients that cannot do SCRAM. TLS is mandatory either way. ## Related Policies: attach rules to a credential. SCRAM-SHA-256 auth: how the password is verified. Connection string: connect a driver or ORM. Hosted MCP: connect an MCP client. Kill-switch: pause access instantly. --- # AI assist URL: https://pgbeam.com/docs/ai-assist Description: Optional, metadata-only AI features that help you author policies, explain incidents, search the audit trail, classify PII, and draft schema descriptions. They never see a row of your data, and they are off until you turn them on. PgBeam ships a set of optional AI assist features in the dashboard. They help an operator do the security work: draft a policy from plain English, explain an anomaly, ask the audit trail a question, raise confidence on ambiguous PII, and draft schema descriptions. Every one of them runs on metadata only, and every one is off by default. ## Metadata only The whole product is safe data access, so the AI features hold the same line: they never send customer row data or masked column values to a model. What they send is metadata: schema shape (table and column names and Postgres types), policy configuration, normalized and hashed query shapes, aggregate counts, and audit-event fields. This is enforced in code, not just by policy: every model call passes through a redaction assertion that whitelists metadata fields and rejects SQL text, client IPs, row values, and audit hash-chain fields. Model calls route through the Vercel AI Gateway, which applies per-organization spend caps, provider fallback, and no-training headers. ## Off until you enable them Each feature is gated by its own flag and defaults to off. A feature that is off, or that has no gateway key configured, is inert: it never runs, never throws, and never blocks a page. Nothing about AI is on until an operator turns it on. To enable AI assist: Set the `AI_GATEWAY_API_KEY` environment variable on the dashboard deployment (a Vercel AI Gateway key). Without it, every AI feature stays inert even if a flag is on. Turn on the features you want from **Settings, AI assist**. The panel lists each feature, whether its flag is on, and whether the gateway key is configured. ## The features Feature What it does Incident explainer Summarizes one audit event or anomaly (what happened, blast radius, recommended action) from its metadata, on the anomaly and audit detail views. Policy authoring assist Drafts a policy profile from a plain-English description and your schema shape. The draft is clamped to your real catalog and loaded into the editor for review. Nothing is saved automatically. Ask your audit Answers a plain-English question over normalized audit metadata and cites the audit event ids it used. PII classification assist Raises confidence on the columns the heuristic PII scan is unsure about, using column name and type only (never sample values). Each suggestion is reviewed in the scan dialog. Weekly security digest A metadata-only weekly summary of agent activity: query volume, top query shapes, policy near-misses, top credentials, and anomaly trips, with recommendations. Preview it in the dashboard or receive it by scheduled email and Slack. Schema description drafting Drafts plain-English table and column descriptions from the schema shape for the schema-annotations feature. Accepting a draft saves it through the schema-annotations API. Each feature reviews its output before anything is applied. Policy drafts load into the editor for you to edit and save, PII suggestions appear for review in the scan dialog, and schema descriptions are saved only when you accept them. ## Eve, the Slack agent Eve is a customer-facing Slack agent built on the same metadata-only foundation. It turns PgBeam's security primitives into a Slack surface: approve or deny a held agent write with a button, ask the audit trail a question, summarize what a policy allows, toggle the kill-switch, and list honeytokens. Every Eve tool returns metadata only and checks the Slack user's mapped PgBeam role before it runs. Eve is a foundation today and not yet generally available; contact us if you want early access. ## Notes AI assist is an operator convenience. It does not change enforcement: policies are still enforced on the wire, and a drafted policy only takes effect once you save it. The features are organization-scoped and cost is capped at the gateway. Leave a feature off if you do not want any metadata leaving for a model. --- # Table Allowlists URL: https://pgbeam.com/docs/allowlists Description: Allow the exact schemas and tables an agent may touch. Anything off the list is blocked in the wire protocol. A table allowlist names the schemas and tables an agent is allowed to touch. PgBeam parses each statement, resolves the relations it references, and blocks the statement if any of them is not on the list. When an allowlist is set the default is deny: an agent reaches only what you explicitly allow. A table **denylist** does the opposite: it names relations that are always blocked, and it takes precedence over the allowlist. ## Define an allowlist Set the allowlist and denylist on a policy profile. In the dashboard, edit the profile under **Allowlist**. From the CLI, pass a JSON profile file: ## How matching works **Tables**: a statement is allowed only if every relation it reads (or writes, in read-write mode) is on the table allowlist and none is on the denylist. **Schemas**: an entry is schema-qualified (`billing.orders`) or bare (`orders`). A bare allowlist entry grants the `public` schema only, because `SET search_path` is blocked and `public` is the only schema a bare name can resolve to. `billing.orders` is a different table, and allowlisting `orders` does not reach it. A bare **denylist** entry works the other way and blocks that relation in every schema, so a denylist is never narrower than you meant. **Catalog**: reads of `pg_catalog` and `information_schema` are permitted without an allowlist entry, so the agent can introspect the schema it is allowed to query. Three groups are carved out of that, because none of them is introspection: the views carrying other sessions' SQL text (`pg_stat_activity`, `pg_stat_statements`, `pg_prepared_statements`, `pg_cursors`), the catalogs carrying credentials or raw bytes (`pg_authid`, `pg_shadow`, `pg_subscription`, `pg_user_mapping`, `pg_user_mappings`, `information_schema.user_mapping_options`, `pg_largeobject`), and the planner statistics that carry sampled values out of your tables (`pg_stats`, `pg_statistic`, `pg_stats_ext`, `pg_stats_ext_exprs`, `pg_statistic_ext_data`). That last group is the one worth knowing about if you rely on masking: `pg_stats.most_common_vals` holds real values from a column, and it is read off the statistics relation rather than off your table, so no mask applies to it. Anything in these three groups needs an explicit allowlist entry, written with the schema (`pg_catalog.pg_stat_activity`), the same as any other table. **Columns**: there is no column allowlist. To restrict what individual columns return, use masking (redact, null, or hash a column's values in flight). A blocked statement comes back as a Postgres error (SQLSTATE `42501`): The message is written to be read by an LLM, so an agent can correct its plan and retry within the rules. ## Honest limits Relation allowlists do not see through views. If you want an agent to read a view, allowlist the view explicitly. `SET search_path` is blocked for agent credentials to prevent allowlist evasion through unqualified names. For columns that exist but should never leave the database in cleartext, reach for masking: the column stays usable for joins and grouping, but its values are hashed or redacted in flight. ## Related Policies Read-only enforcement PII masking --- # Anomaly Detection URL: https://pgbeam.com/docs/anomaly-detection Description: PgBeam learns each credential's normal behavior and alerts when it drifts. Volume spikes, off-hours access, new query shapes, and error or egress spikes. Anomaly detection watches each credential's traffic and raises an alert when it drifts from its own baseline. A bot that quietly read four tables for a month and suddenly scans a fifth, runs at 3am, or pulls ten times its usual rows is doing something worth a look. PgBeam flags it without you writing a single threshold. It runs on agent credentials and human credentials alike. The baseline is per-credential, so a noisy analytics agent and a quiet support bot each get judged against their own history, not a shared average. ## What it watches Signal What trips it Volume spike Query count or rate well above the credential's recent baseline. Off-hours access Activity outside the hours this credential normally runs. New query shape A normalized statement shape never seen from this credential before. Error spike A burst of blocked or failing statements (often probing or a loop). Egress spike Bytes returned well above baseline (a possible bulk exfiltration). A "query shape" is the statement with its literals stripped, so `SELECT * FROM orders WHERE id = 1` and `... WHERE id = 2` are the same shape. A genuinely new shape means the credential is doing something it has not done before. ## Alerts Each detection becomes an anomaly alert with the signal, the credential, the window, and the statements that triggered it. Review them on the **Anomalies** tab, or pull them from the API: Acknowledge or resolve an alert once you have looked at it: The CLI does the same with `pgbeam anomalies ack`: pass one or more alert ids, or `--all` to acknowledge every open alert in the project. `pgbeam anomalies resolve` closes them out, and `pgbeam anomalies list` shows what is open. Every alert can also fire an `anomaly_alert` webhook, so it lands in Slack, PagerDuty, or your SIEM the moment it is raised. ## From alert to action Anomaly detection tells you something changed; the rest of the policy engine lets you respond. A volume or egress spike on a credential that should be quiet: trip the kill-switch and investigate. A new query shape that should never happen: tighten the allowlist or add a row filter. A run of blocked statements: read the audit log to see what the agent kept trying, then adjust its policy. A new credential has no baseline yet, so its first hours of traffic establish one rather than triggering alerts. Detection sharpens as a credential builds a track record. ## Related Audit log: the per-statement record alerts are built from. Audit export: forward `anomaly_alert` events to a SIEM. Kill-switch: stop a credential the moment something looks wrong. Budgets: hard ceilings that complement baseline detection. --- # API Keys URL: https://pgbeam.com/docs/api-keys Description: Create, rotate, and revoke PgBeam API keys for programmatic access. API keys authenticate programmatic access to the PgBeam REST API and CLI. ## Key types PgBeam supports two types of API keys: Type Prefix Scope Manage in **Personal keys** `pbu_` All your organizations **Settings > Account > API Keys** **Organization keys** `pbo_` Single organization **Settings > Organization > API Keys** Use **organization keys** for CI/CD and shared automation. Use **personal keys** for your own tools and scripts. ## Create an API key ## Navigate to API Keys From the dashboard, go to **Settings** and select the relevant **API Keys** page (Account or Organization level). ## Create the key Click **Create Key** and configure: **Name**: A label to identify the key (e.g., "CI/CD", "monitoring", "staging deploy") **Expiry**: Optional. Choose 30 days, 90 days, 365 days, or no expiry. ## Copy the key The full key is shown **only once** after creation. Copy it immediately and store it securely. You cannot retrieve the full key after closing the dialog. ## Use an API key Pass the key in the `Authorization` header as a bearer token: ## Rotate a key ## Create a new key Generate a new key with the same permissions as the one you want to rotate. ## Update your application Update your application, CI/CD pipeline, or scripts to use the new key. ## Verify the new key Confirm the new key works correctly in all environments. ## Revoke the old key Delete the old key from **Settings > API Keys**. Revoked keys stop working immediately. ## Security best practices **Store keys in environment variables** or a secret manager. Never commit them to source control. **Set an expiry** for keys used in CI/CD or automation. **Use separate keys** for different environments (production, staging, development). **Use organization keys** for shared automation so revoking a team member's access does not break CI/CD. **Revoke keys immediately** if they may have been exposed. **Audit key usage**: review active keys periodically and revoke any that are no longer needed. --- # Human-in-the-Loop Approvals URL: https://pgbeam.com/docs/approvals Description: Hold an agent's writes and DDL until a human approves them. Approve or reject in the dashboard, set auto-approve rules for safe changes, and auto-expire stale requests. Approvals hold a statement before it reaches your database and wait for a human to say yes. Turn it on for a credential, and every write or DDL statement it runs is parked as an approval request instead of executing. A reviewer approves or rejects it in the dashboard, the agent's session blocks until then, and the statement runs only on approval. This is the middle ground between read-only (no writes ever) and read-write (any write, immediately). The agent stays productive: it can draft a change and hand it to a person, rather than being told no. Approvals apply to agent credentials and to human credentials. A junior analyst's write can be held for a senior reviewer the same way an agent's is. ## Turn it on Add an approval rule to a policy. It names which statement kinds are held. On the policy profile, open **Approvals**, choose which statement kinds to hold (writes, DDL, or both), and set an expiry. Pending requests show up on the **Approvals** tab with the full context a reviewer needs (see below). `approval_mode` is one of `off`, `writes`, `ddl`, or `all`, and sets which statement classes are held for a reviewer. ## What the agent sees When a held statement is parked, the agent gets an LLM-readable notice on the wire and the session waits: If the request is approved, the statement runs and the agent gets its result. If it is rejected or expires, the agent gets an error explaining why, so it can move on instead of hanging. ## What reviewers see Each pending request on the **Approvals** tab carries the context needed to decide without opening a SQL console: The full SQL of the held statement and the credential that ran it, shown by its friendly name rather than an opaque `agt_…` id. The statement kind (for example `update`, `delete`, or a DDL kind) as a badge. The target tables the statement touches. An affected-row estimate, always labeled estimated because the data can change between the estimate and execution. A warning when the estimate exceeds the policy's `max_affected_rows` cap: even if the request is approved, the gateway still blocks a write that actually affects more rows than the cap. ## Approve or reject a request Reviewers act in the dashboard, or from the API for automation: ## Auto-approve rules Holding every write on a busy credential is noise. The `approval_auto_max_rows` setting lets the safe changes through and reserves human attention for the rest. It is a single row ceiling for the whole policy: a held write that touches at most that many rows is approved automatically, and anything larger stays held. PgBeam counts the rows a write would affect before it commits. A write at or under the ceiling is approved and recorded; a write over it is parked for a person. Set `approval_auto_max_rows` to `0` to auto-approve nothing. DDL and other statements with no countable row effect are never auto-approved. ## Auto-expire A held request that no one acts on expires after the policy's expiry window. The statement is rejected, the agent is told, and the request closes. This keeps a forgotten request from holding an agent session open forever. Every approval, rejection, and expiry is written to the audit log and can fire an `approval_requested` webhook. ## Related Read-only enforcement: block writes entirely instead of holding them. Sandbox writes: let an agent write freely against a throwaway branch. Audit log: every approval decision is recorded. Audit export: fire a webhook when a request is created. --- # Audit Export URL: https://pgbeam.com/docs/audit-export Description: Stream audit events to your own systems. HMAC-signed webhooks for any endpoint, plus native formats for Splunk HEC, Datadog, and Elastic. Audit export pushes PgBeam events to your systems as they happen. Point it at a webhook endpoint and PgBeam delivers a signed JSON payload for each event. Point it at a SIEM and PgBeam formats the events the way that SIEM expects. The audit log keeps the full history for querying; export is for getting events out in real time. ## Event types Event Fires when `query_blocked` A statement is rejected by policy (allowlist, read-only, etc.). `budget_exhausted` A credential hits its query or row budget. `kill_switch` A credential or project kill-switch is tripped. `masked` A result is returned with one or more masked columns. `migration_flagged` A DDL statement is flagged by the safe-migration linter. `approval_requested` A write or DDL is held for approval. `anomaly_alert` Anomaly detection raises an alert. For each event's full payload shape, see webhook events. ## Create a webhook endpoint Open **Webhooks**, add an endpoint URL, pick the events to send, and copy the signing secret. Use **Send test event** to verify your receiver before you rely on it. You set the signing secret when you create the endpoint. It is write-only: PgBeam stores it to sign deliveries and never returns it, so keep your own copy. The same secret verifies every delivery. ## Webhook payload Each delivery is a JSON body with the event, the project, and the event-specific detail under `data`. The webhook events page documents the `data` fields for every event type. PgBeam signs every native (`json`) and `elastic` delivery. Two signature headers are sent, both as `sha256=` keyed with your signing secret: `X-PgBeam-Signature` (v1) is the HMAC-SHA-256 of the raw request body only. `X-PgBeam-Signature-V2` (v2) is the HMAC-SHA-256 of the exact byte string `timestamp + "." + body`, where `timestamp` is the same value sent in the `X-PgBeam-Timestamp` header (unix seconds, as a decimal string) and `.` is a single literal period. Because the timestamp is part of the signed bytes, a captured delivery cannot be replayed with a rewritten timestamp: rewriting it invalidates the signature. This is the same construction Stripe uses. Each delivery also carries `X-PgBeam-Event`, `X-PgBeam-Event-Id`, `X-PgBeam-Timestamp` (unix seconds), and `X-PgBeam-Delivery` (a per-attempt id for de-duplication). We recommend verifying `X-PgBeam-Signature-V2` and rejecting stale timestamps. v1 stays in place unchanged for existing receivers, so you can migrate at your own pace. The SIEM/token destinations (Splunk HEC, Datadog) carry neither signature; they authenticate with the destination's own token. Verify against the raw request body, before any JSON parsing reserializes it, and use the `X-PgBeam-Timestamp` value verbatim so your recomputed signature matches the bytes we signed. Compare with a constant-time function. Rejecting deliveries whose `X-PgBeam-Timestamp` is far from the current time (5 minutes is a reasonable window) is what closes the replay gap, so enforce it when you verify v2. The v1 header is still valid if you have not migrated. It signs the body only, so it cannot bind the timestamp: Splunk HEC and Datadog deliveries are not HMAC-signed. They authenticate with the destination's own token instead: Splunk uses an `Authorization: Splunk ` header and Datadog uses `DD-API-KEY`. Set that token as the endpoint's secret. PgBeam expects a `2xx` within a few seconds. A non-`2xx` or a timeout is retried with exponential backoff. Make your receiver idempotent by keying on the event `id`, which is stable across retries. ## SIEM formats For a SIEM, set the endpoint's `format` and PgBeam shapes each event the way that product ingests it. The signing and retry behavior is the same. Format Sends `splunk_hec` Splunk HTTP Event Collector (HEC) envelope. Set your HEC token as the secret. `datadog` Datadog Logs intake payload with `ddsource: pgbeam` and event tags. `elastic` Elastic / OpenSearch JSON documents with an ECS-style shape. For `splunk_hec` and `datadog`, the endpoint secret is the destination's own token (Splunk sends it as `Authorization: Splunk `, Datadog as `DD-API-KEY`) rather than an HMAC signature. ## Related Webhook events: every event type and its payload shape. Audit log: the queryable history these events come from. Anomaly detection: source of `anomaly_alert` events. Approvals: source of `approval_requested` events. Safe migrations: source of `migration_flagged` events. --- # Audit Log URL: https://pgbeam.com/docs/audit-log Description: Every statement an agent runs, allowed or blocked, recorded with its decision, reason, rows, bytes, latency, and credential. The audit log records every statement a credential runs through PgBeam, whether it was allowed, masked, blocked, or throttled. Each entry captures the SQL, the decision and the reason for it, the rows and bytes returned, the latency, and the credential that ran it. Recent entries are queryable in the control plane; older entries are archived for retention. It covers agent and human credentials, and records each credential's `principal_type` so you can tell agent traffic from people. To stream events to your own systems in real time, see audit export; to flag unusual behavior automatically, see anomaly detection. ## What is recorded Field Description Time When the statement ran. Credential The agent credential that ran it. SQL The statement, as parsed. Decision `allowed`, `masked`, `blocked`, or `throttled`. Reason Why it was blocked, masked, or throttled. Rows Rows returned to the agent (after masking and row caps). Bytes Bytes returned. Latency Time to serve the statement. Source Connection string or hosted MCP. ## Read the log Open the **Audit** tab in the dashboard to filter by agent, decision, or time range and export the result. From the terminal or API: ## How the pipeline works Each data plane captures the decision for every agent statement and ships it to the control plane. Recent entries are stored in control-plane Postgres for fast querying, and batched archives are written to object storage for long-term retention. Audit retention depends on your plan: 7 days on Starter, 30 days on Pro, and 90 days on Scale. See Plans. Archived entries remain available for export within your retention window. ## What it is good for Answer "what did this agent do" with the exact statements and decisions. Show a reviewer or security owner that an agent was held to its policy. Spot an agent that is hitting blocks or budgets and needs its policy adjusted. ## Related Audit export: HMAC-signed webhooks and SIEM formats. Anomaly detection: alert on drift from baseline. Approvals: every approval decision is recorded here. Policies Kill-switch Plans --- # AWS Marketplace URL: https://pgbeam.com/docs/aws-marketplace Description: Subscribe to PgBeam through the AWS Marketplace. Provision a policy-enforced Postgres gateway with consolidated AWS billing. Subscribe to PgBeam through the AWS Marketplace. The listing lets you provision PgBeam with consolidated billing through your existing AWS account, with no separate payment method required. AWS Marketplace SaaS provisioning and metering are built. The public AWS Marketplace listing goes live at launch. Until then, sign up from the dashboard. ## How it works ## Subscribe on AWS Marketplace Find PgBeam on the AWS Marketplace and subscribe. AWS handles payment through your existing AWS billing account. ## Create your PgBeam account After subscribing, you are redirected to PgBeam to create an organization linked to your AWS account. Your subscription and entitlements are automatically synced. ## Provision a project From the PgBeam dashboard, create a project and connect your RDS, Aurora, or other PostgreSQL database. PgBeam provisions a proxy endpoint with connection pooling and optional query caching. ## Connect your app Update your application connection string to point at the PgBeam proxy endpoint. No other code changes are required. ## Features **AWS consolidated billing**: PgBeam charges appear on your AWS invoice **No separate payment method**: use your existing AWS account **SaaS provisioning**: subscribe and start using PgBeam in minutes **Usage metering**: query and data transfer usage reported to AWS **Private offers**: custom pricing available for enterprise customers ## Billing PgBeam usage subscribed through AWS Marketplace is billed through AWS. The same plan tiers (Starter, Pro, Scale) and overage rates apply, metered and reported to AWS on an hourly basis. See Plans and Limits for details. ## Further reading Connection Pooling: pool modes and sizing Caching: query caching and SWR Read Replicas: replica routing Plans: plan limits and pricing --- # Query Budgets URL: https://pgbeam.com/docs/budgets Description: Cap queries per window and rows per result for an agent credential. Runaway loops and full-table scans hit a ceiling instead of your database. A budget caps how much an agent can run. You set queries per window, a maximum number of rows per result, and a statement timeout. When an agent loops or asks for too much, the budget stops it at the wire instead of letting it hammer your database. ## Set a budget In the dashboard, set the budget on the policy profile under **Budgets**. ## What you can cap Limit Effect Queries per window Cap statements per hour or per day. The next query past the cap is blocked with an error until the window resets. Max rows Truncate any result to at most this many rows. Write row cap Hard cap on rows a single write (INSERT/UPDATE/DELETE) may affect. Set with `--max-affected-rows`. Statement timeout Cancel a statement that runs longer than this. ## What the agent sees A query past the cap comes back as a Postgres error (SQLSTATE `53400`): The message names the window and the exact reset time, so an agent can back off rather than retry blindly. A per-day egress (bytes) budget produces a similar message when exceeded. ## Headroom on the MCP endpoint Over the hosted MCP endpoint, an agent does not have to wait for that error to learn where it stands. Every row-returning tool result (`query`, `explain`, `list_tables`, `describe_table`) carries a `budget` block for the credential that ran it: A window your policy leaves uncapped is omitted, so a present key means the cap is enforced. A credential with no budget at all gets no `budget` block. The figures are the same per-region counters the wire path enforces, so they are approximate in the same way, and the egress figure can trail the agent's last statement by a moment because bytes are charged after the response is sent. It is a signal for pacing a long job, not a billing record. ## Write row cap `--max-affected-rows` bounds how many rows a single write may affect, separate from `--max-rows` (which truncates read results). A write whose affected-row count would exceed the cap runs inside a transaction, is checked, and is rolled back so nothing persists, then blocked. It applies to INSERT, UPDATE, and DELETE and is enforced independently of human approval. 0 means unlimited. Budget counters are kept per data plane and per region, like the rate limiter. An agent connects to one region in practice, so the window it sees is consistent. The control plane aggregates usage across regions and can trip the kill-switch if an organization-level ceiling is breached. ## Related Policies Kill-switch Query timeout --- # Caching URL: https://pgbeam.com/docs/cache Description: How PgBeam caches query results at the edge, when it bypasses cache, and how to turn it on safely for your workload. PgBeam caches query results at the data plane level. When a cached result is available, PgBeam returns it directly without touching the upstream database. This reduces upstream load, lowers read latency, and saves you money on database compute. Each region keeps its own independent cache. There is no cross-region coherence layer. That is a deliberate tradeoff. Synchronizing caches across regions would add latency to every read, which defeats the purpose of caching. Caching starts **disabled** for new databases. This is the safe default. Turn it on after traffic is flowing and you know which reads are stable enough to benefit from caching. ## When caching helps Caching is most effective when your workload has **repeated reads** that return the same data across many requests. Common examples: Product catalogs and category listings Configuration tables read on every request User profile lookups that change infrequently Leaderboards, stats, and aggregation queries that can tolerate staleness Reference data (countries, currencies, feature flags) Caching is **not** a good fit for: Queries that must always return the latest data (e.g., account balances) Write-heavy workloads where data changes between reads Queries with highly variable parameters that produce unique results each time ## How caching works ## Query classification PgBeam classifies each incoming query. Read statements (`SELECT`) are candidates for caching. Writes (`INSERT`, `UPDATE`, `DELETE`), DDL (`CREATE TABLE`, `ALTER`), session-changing commands (`SET`, `DISCARD`), and queries with volatile functions (`NOW()`, `RANDOM()`, `pg_advisory_lock()`) are never cached. ## Cache key generation For cacheable queries, PgBeam generates a cache key from the **normalized SQL text plus parameter values**, scoped to the project. Normalization means whitespace and casing differences do not create separate cache entries. The same query template with different parameter values produces different cache entries: ## Cache lookup PgBeam checks the local cache and then the regional shared cache for a matching entry: **Hit**: A fresh cached result is returned immediately. The upstream database is never contacted. **Stale hit**: The cached result has passed its TTL but is within the stale-while-revalidate (SWR) window. PgBeam returns the stale result immediately and refreshes the cache in the background. **Miss**: No cached result exists. The query goes to the upstream database, and the result is stored in the cache for future requests. ## Cache defaults Setting Default What it controls **TTL** `60s` How long a cached result is considered fresh **SWR** `30s` Extra window after TTL where stale results can be served while refreshing **Max entries** `10,000` Approximate upper bound of cached entries per project **Enabled** `false` Caching is off by default for new databases ## Understanding TTL and SWR TTL and SWR work together to balance freshness and performance: During the TTL window, cached results are returned without any upstream query. During the SWR window, the stale result is returned immediately (keeping latency low), and PgBeam refreshes the entry in the background. After the SWR window, the entry is treated as a miss and the upstream is queried. ## Invalidation: writes do not auto-clear the cache PgBeam does **not** automatically invalidate cached results when a write flows through the proxy. Writes are never cached, but a `SELECT` cached before the write keeps being served until its TTL (and SWR window) expire. Plan for a staleness window of up to `TTL + SWR` after any change. If you need cached data cleared sooner than its TTL, opt in to event-based invalidation. PgBeam listens on the `pgbeam_invalidate` channel on your upstream database and evicts cached entries for a table when it receives a notification naming that table. You emit those notifications from triggers you install on the tables you cache: The `NOTIFY` payload is the table name (bare or schema-qualified). PgBeam evicts the cached entries that read from that table. `LISTEN`/`NOTIFY` requires a session-level connection. PgBeam opens one direct session connection to your upstream to listen on `pgbeam_invalidate`. If the upstream connection details you gave PgBeam point at a PgBouncer-style transaction pooler (PlanetScale, the Supabase pooler, RDS Proxy), the `LISTEN` silently receives nothing and invalidation does nothing, with no error. Point PgBeam's upstream at a direct, session-capable endpoint (not the pooler port) if you want `NOTIFY` invalidation to work. If a table changes often and must never be served stale, do not rely on invalidation timing. Either skip the cache for those reads with `/* @pgbeam:cache noCache */`, or give them a very short TTL (for example `/* @pgbeam:cache maxAge=1 */`) so the freshness window is bounded regardless of whether a notification arrives. ## Ways to control cache behavior PgBeam checks cache controls in priority order. The first match wins: Priority Source Example Scope 1 SQL annotation `/* @pgbeam:cache noCache */` Per query 2 Session override off `SET pgbeam.cache = off` Per session 3 Cache rule Dashboard rule for query shape Per query shape 4 Session override on `SET pgbeam.cache = on` Per session 5 Database default Database-level cache setting All queries 6 Fallback Off n/a This precedence lets you set broad defaults and override them precisely where needed. ## SQL annotations Embed cache directives directly in your SQL as comments. PgBeam strips the annotations before forwarding to the upstream, so your database never sees them. ## Annotation reference Annotation Effect `/* @pgbeam:cache */` Enable caching with default TTL and SWR `/* @pgbeam:cache maxAge=N */` Cache for N seconds `/* @pgbeam:cache swr=N */` Set SWR window to N seconds `/* @pgbeam:cache maxAge=N swr=M */` Set both TTL and SWR `/* @pgbeam:cache noCache */` Bypass cache for this query `/* @pgbeam:replica */` Route to a read replica ## Session overrides Control caching for an entire connection session. Useful for debugging or for application code that needs to temporarily force cache behavior. When `pgbeam.debug` is on, every query returns a `NOTICE` with cache information: ## Cache bypasses PgBeam skips the cache entirely when any of these conditions are true: Condition Why it bypasses Caching not enabled for the query No rule, annotation, or session override Statement mutates data `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE` Statement changes session state `SET`, `DISCARD`, `RESET` Query uses volatile functions `NOW()`, `RANDOM()`, `pg_advisory_lock()`, etc. Query is inside an explicit transaction `BEGIN` ... `COMMIT` blocks SQL annotation says `noCache` Explicit opt-out Session override is `pgbeam.cache = off` Session-level opt-out ## Cache layers PgBeam uses a two-layer cache for speed and resilience: Layer Scope Latency Failure behavior **L1** Per-process Microseconds Process-local; failure is extremely rare **L2** Shared per region Sub-millisecond Fail-open: queries go to upstream L1 is checked first. On an L1 miss, L2 is checked. On an L2 miss, the query goes to the upstream database. Results from the upstream are written back to both layers. If the shared cache is unavailable, PgBeam falls through to the origin database. Your application continues working. It just loses the caching benefit until the cache recovers. ## Cache rules Cache Rules give you a dashboard-based way to enable caching for specific query shapes without changing application code. PgBeam automatically tracks the distinct query shapes flowing through your project, so you can see what your traffic looks like before you start caching anything. ## View cache rules Open your database in the dashboard and go to **Cache Rules**. You will see a list of detected query shapes with frequency and timing data. ## Enable caching for a query shape Once you identify a high-frequency read query that would benefit from caching, enable it from the dashboard or API: Find the query shape in **Cache Rules** and toggle caching on. You can optionally set a custom TTL and SWR for that shape. ## Recommended approach **Let traffic flow for a while**: PgBeam needs to see your query patterns before you can make informed caching decisions. **Start with high-frequency, stable reads**: Look for queries that run hundreds or thousands of times per day and return data that changes infrequently. **Avoid caching queries with volatile data**: If a query returns different results every time, caching wastes memory without saving upstream load. **Monitor cache hit rates**: Use the dashboard or Query Insights to see whether caching is actually helping. ## Further reading Read Replicas: Route reads to replicas for load distribution Plans & Limits: Cache entry limits and defaults per plan tier Troubleshooting: Debugging "cache is not doing anything" --- # Connection String URL: https://pgbeam.com/docs/connection-string Description: Give an AI agent a scoped Postgres connection string. Every driver, ORM, and agent framework works unchanged, with policy enforced in the wire protocol. A scoped connection string is the second front door for an agent. It looks like an ordinary PostgreSQL URL, so every driver, ORM, and agent framework works unchanged. The difference is that the username and password belong to a PgBeam agent credential, and every statement is enforced against that credential's policy before it reaches your database. ## Use it like any Postgres URL The agent framework does not need a PgBeam SDK. Set the agent's `DATABASE_URL` to the scoped connection string and it is enforced from the first query. ## What enforcement looks like to the agent A blocked statement returns a PostgreSQL `ErrorResponse` with an LLM-readable reason, so an agent reading the error can correct itself: Masked columns come back redacted, hashed, or nulled in the result, depending on the rule. See Masking. Agent connections must use TLS. The hostname (`.proxy.pgbeam.app`) carries the SNI used for routing, so use the full connection string PgBeam issued, with `sslmode=require` or stronger. ## Connection string vs hosted MCP Use the connection string when… Use the hosted MCP endpoint when… The agent already uses a Postgres driver. The client speaks MCP (Claude Code, Cursor). You want ORM and framework compatibility. You want ready-made `query`/`describe` tools. You run your own query loop. You want a paste-one-URL setup. Both are backed by the same policy engine. See Hosted MCP. ## Related Agent credentials: issue and revoke the credential. Policies: the rules enforced on every statement. Serverless: pooling for short-lived agent connections. --- # Crossplane URL: https://pgbeam.com/docs/crossplane Description: Manage PgBeam projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, self host enrollments, and honeytokens as Kubernetes custom resources using the Crossplane provider. Manage your PgBeam infrastructure as Kubernetes custom resources with Crossplane. The `provider-pgbeam` package provides managed resources for projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, self host enrollments, and honeytokens. ## Setup ## Install the provider The Crossplane provider is coming soon. Registry publishing is on the roadmap. ## Configure credentials Create a Secret with your PgBeam API key, then reference it in a ProviderConfig: ## Create a project ## Apply Crossplane creates the PgBeam project and its primary database atomically. The proxy hostname is available in `status.atProvider.proxyHost` and published to the connection secret. ## Resources **Approval and anomaly rules are not yet managed as code.** Policy profiles and honeytokens are managed resources, so the enforcement rules and the decoys live in your reviewed IaC flow and are covered by drift detection. Approval rules and anomaly rules are not: the API exposes them only as events to review after the fact (approve/reject, ack/resolve), so there is nothing to declare yet. Those two still live outside IaC. ## Project Manages a PgBeam project with a primary database. **Status:** `proxyHost`, `queriesPerSecond`, `burstSize`, `maxConnections`, `databaseCount`, `activeConnections`, `createdAt`, `updatedAt`, `primaryDatabaseID` ## Database Manages an upstream database connection within a PgBeam project. **Status:** `connectionString`, `createdAt`, `updatedAt` ## Replica Manages a read replica for a PgBeam database. Replicas are immutable; any spec change triggers recreation. **Status:** `createdAt`, `updatedAt` ## CustomDomain Manages a custom domain for a PgBeam project. CustomDomains are immutable; any spec change triggers recreation. **Status:** `verified`, `verifiedAt`, `tlsCertExpiry`, `dnsVerificationToken`, `dnsInstructions`, `createdAt`, `updatedAt` ## CacheRule Manages a per-query cache rule. Deletion disables caching (soft-delete). **Status:** `queryHash`, `normalizedSQL`, `queryType`, `callCount`, `avgLatencyMs`, `p95LatencyMs`, `avgResponseBytes`, `stabilityRate`, `recommendation`, `firstSeenAt`, `lastSeenAt` ## SpendLimit Manages the monthly spend limit for an organization. **Status:** `orgID`, `plan`, `billingProvider`, `subscriptionStatus`, `currentPeriodEnd`, `enabled`, `customPricing`, `spendCapped`, `spendCappedAt`, `limits`, `createdAt`, `updatedAt` ## AgentCredential Manages a scoped agent credential (a PgBeam-issued Postgres login plus a hosted MCP token) for an AI agent. The connection string and MCP token are one-time secrets returned only at creation and exposed as sensitive computed outputs; they cannot be retrieved again. To rotate the secrets, taint/replace the resource (or use the rotate endpoint out of band). **Status:** `pgUsername`, `authMethod`, `lastUsedAt`, `createdAt`, `updatedAt`, `connectionString`, `mcpURL`, `mcpToken` ## PolicyProfile Manages a policy profile: a named bundle of agent-gateway enforcement rules (access mode, table allow/deny lists, statement-kind rules, PII masking rules, per-relation row filters, query/egress budgets, write mode, approvals, and migration safety) attached to agent credentials and enforced in the PG wire protocol. Nested-list fields (masking\_rules, row\_filters) and the nested statement\_rules object are expressed as structured config. **Status:** `createdAt`, `updatedAt` ## WebhookEndpoint Manages a webhook endpoint that receives project audit and anomaly event deliveries. The signing secret is write-only and never returned by the API. **Status:** `createdAt`, `updatedAt` ## SelfHostEnrollment Manages a self-host (BYOC) enrollment: a token a self-hosted proxy uses to authenticate to the control plane's config/audit stream. The token is a one-time secret returned only at creation and exposed as a sensitive computed output; it cannot be retrieved again. To rotate the token, replace the resource. Deletion revokes the enrollment. SelfHostEnrollments are immutable; any spec change triggers recreation. **Status:** `createdBy`, `createdAt`, `lastSeenAt`, `revokedAt`, `token` ## Honeytoken Manages a honeytoken: a decoy (canary) relation that no legitimate query should ever touch. Any agent statement referencing it is blocked and recorded as a canary\_tripped audit event; the kill action additionally disables the tripping credential via the kill-switch. The relation does not have to exist in the upstream database: enforcement is by name, in the wire protocol, before the statement reaches Postgres. **Status:** `createdAt`, `updatedAt` ## Configuration Setting Source Description `apiKeySecretRef` ProviderConfig Secret reference for the API key `baseURL` ProviderConfig API base URL (default: `https://api.pgbeam.com`) ## Replacement vs update Some spec changes trigger resource recreation rather than in-place updates: Resource Recreation triggers Project `orgId`, `cloud`, `selfHosted` Database `projectId` Replica Any spec change (immutable) CustomDomain Any spec change (immutable) CacheRule `projectId`, `databaseId`, `queryHash` SpendLimit `orgId` AgentCredential `projectId`, `policyProfileId`, `name`, `principalType`, `expiresAt` PolicyProfile `projectId` WebhookEndpoint `projectId` SelfHostEnrollment Any spec change (immutable) Honeytoken `projectId` ## Further reading Connection Pooling: pool modes and sizing Caching: query caching and SWR Read Replicas: replica routing Custom Domains: DNS setup and verification API Keys: managing API credentials Plans: plan limits and pricing --- # Custom Domains URL: https://pgbeam.com/docs/custom-domains Description: Use your own domain for PgBeam connection strings with automatic TLS certificate provisioning and renewal. Scale plan only. Replace the default `*.proxy.pgbeam.app` hostname in your connection string with your own domain. Your applications connect to `db.yourcompany.com` instead of `abc.proxy.pgbeam.app`, while PgBeam handles TLS certificates automatically. Custom domains are available on the **Scale plan** only. See Plans & Pricing for details. ## Why use a custom domain **Portability.** If you move between proxy providers, your connection strings stay the same. No application changes needed. **Branding.** Internal tools and dashboards show your domain instead of a third-party hostname. **Security policy compliance.** Some organizations require all external connections to use company-owned domains. ## Prerequisites A **Scale plan** subscription Access to your domain's **DNS settings** (through your registrar or DNS provider like Cloudflare, Route 53, etc.) A project with at least one configured database ## Setup ## Add the domain From the dashboard, go to your project, then **Domains**, and click **Add Domain**. Enter your domain (e.g., `db.example.com`). The response includes your **verification token** and DNS instructions. ## Add DNS records Add all three records to your domain's DNS: Record Host Value Purpose `CNAME` `db.example.com` `abc.proxy.pgbeam.app` Routes traffic to PgBeam `TXT` `_pgbeam-verify.db.example.com` `pgbeam-verify=` Proves domain ownership `CNAME` `_acme-challenge.db.example.com` `_acme-challenge.abc.proxy.pgbeam.app` Delegates TLS cert issuance Replace `abc` with your project's subdomain and `` with the verification token from the previous step. DNS changes can take anywhere from a few minutes to 24 hours to propagate, depending on your DNS provider and existing TTL settings. Most providers complete this within 1-10 minutes. ## Verify the domain After DNS propagates, trigger verification: Click **Verify** next to the domain in your project's domain settings. PgBeam checks two things: The TXT record exists and matches the verification token The CNAME points to your PgBeam project subdomain ## Update your connection string Once verified, use your custom domain in your application: TLS is handled automatically. PgBeam provisions a certificate for your domain and uses SNI to match incoming connections to your project. ## TLS certificate management PgBeam provisions and renews TLS certificates for your custom domain automatically. The ACME challenge CNAME you added in the DNS step delegates the certificate challenge, so PgBeam can issue and renew certificates without any further action from you. **Provisioning** happens within minutes of successful domain verification. **Renewal** happens automatically before the certificate expires. **Revocation** happens automatically when you remove the custom domain. You do not need to upload or manage certificates manually. ## Multiple custom domains You can add multiple custom domains to a single project. Each domain gets its own TLS certificate and DNS verification. This is useful when you want different domains for different environments or services while routing to the same PgBeam project: ## Remove a custom domain Go to your project's **Domains** settings and click **Remove** next to the domain. After removal: The TLS certificate is revoked Connections to the custom domain stop working The default `abc.proxy.pgbeam.app` hostname continues to work You should remove the DNS records from your DNS provider ## Troubleshooting ## Verification failures Issue Likely cause Fix TXT record not found DNS propagation delay Wait and retry. Check with `dig TXT _pgbeam-verify.db.example.com` CNAME mismatch Target is not the exact project subdomain Verify the CNAME points to `abc.proxy.pgbeam.app` exactly CNAME lookup failed Missing trailing dot at some providers Try `abc.proxy.pgbeam.app.` (with trailing dot) ## Certificate issues Issue Likely cause Fix Certificate not ready ACME challenge CNAME missing or wrong Verify `_acme-challenge` CNAME record is correct Certificate expired ACME challenge CNAME was removed Re-add the ACME challenge CNAME to enable auto-renewal TLS error on connect Client does not trust the certificate Update system CA bundle; PgBeam certs are trusted by all modern systems ## Cloudflare-specific notes If your DNS is managed by Cloudflare, make sure the CNAME record has the **proxy toggle disabled** (DNS-only / grey cloud). Cloudflare's proxy intercepts TCP traffic and will break PostgreSQL wire protocol connections. ## Further reading Plans & Limits: Custom domains are available on the Scale plan Routing & Regions: How global routing works with custom domains Troubleshooting: General connection debugging --- # Drizzle URL: https://pgbeam.com/docs/drizzle Description: Connect Drizzle ORM to your PostgreSQL database through PgBeam for connection pooling, caching, and global routing. Connect your Drizzle ORM application to PgBeam by updating the connection string. No changes to your schema definitions, table declarations, or queries are required. ## Setup ## Update your environment ## Configure the database client ## Run a test query If this returns results, Drizzle is connected through PgBeam. ## Connection pool sizing PgBeam handles upstream connection pooling, so the `pg` pool on your application side should be small. A pool size of 3-5 per application instance is typically sufficient. Deployment type Recommended `max` pool size Single server 5-10 Multiple replicas/pods 3-5 per instance Serverless (Lambda) 1-2 With PgBeam in transaction pool mode, each Drizzle connection only holds an upstream connection for the duration of a transaction. This means a small local pool can handle high concurrency. ## Drizzle Kit migrations Run Drizzle Kit migrations directly against your origin database, not through PgBeam. Migrations may use session features that behave differently through a connection pool. The same applies to `drizzle-kit push` for development: ## Caching with Drizzle ## Query builder queries (recommended) For standard Drizzle query builder queries (`db.select()`, `db.query`, etc.), PgBeam automatically tracks the generated SQL shapes. Enable caching for these through Cache Rules in the dashboard, with no code changes needed. ## Raw queries with annotations Use Drizzle's `sql` template for fine-grained cache control: ## Read replicas with Drizzle Route read queries to replicas using the `/* @pgbeam:replica */` annotation: Standard query builder calls always go to the primary database. To use replica routing, use raw SQL with the annotation. See Read Replicas for details on replica setup. ## Debugging Enable PgBeam debug output to verify caching and routing: ## Common issues Issue Cause Fix "Too many connections" errors `pg` pool too large Set `max: 5` in Pool config Migrations fail through PgBeam Session features not available Run migrations against origin directly Stale data after writes Cache returning old results Use `noCache` annotation or adjust TTL ## Further reading Connection Pooling: Pool modes and sizing guidance Caching: TTL, SWR, cache rules, and SQL annotations Read Replicas: Replica setup and routing --- # Error Codes URL: https://pgbeam.com/docs/error-codes Description: SQLSTATE error codes returned by PgBeam, what causes them, and how to resolve each one. PgBeam returns standard PostgreSQL SQLSTATE error codes. This reference covers every PgBeam-specific error, what triggers it, and how to fix it. ## Quick reference SQLSTATE Situation Message `08004` Unknown project `project not found for hostname ...` `08004` Organization suspended `organization suspended — update payment at dash.pgbeam.com` `08004` IP not allowed `connection rejected: IP not in allowlist` `08004` Auth rate limited `too many authentication attempts` `08006` Upstream auth failure Forwarded from upstream `08006` Circuit breaker open `upstream unavailable (circuit breaker open)` `53300` Connection limit exceeded `too many connections for project` `53400` Query rate limit exceeded `query rate limit exceeded` ## `08004`: Connection rejected SQLSTATE `08004` means PgBeam rejected the connection before it reached the upstream database. The three causes are distinct: ## Project not found **Cause:** The hostname in the connection string does not match any project. This usually means a typo in the hostname or a deleted project. **Fix:** Verify the hostname in your `DATABASE_URL` matches the project hostname shown in the dashboard Check that the project has not been deleted If using a custom domain, confirm the domain is verified. See Custom Domains ## Organization suspended **Cause:** The organization's billing is inactive. This happens when a payment fails, the trial expires without a payment method on file, or an owner manually cancels the subscription. **Fix:** Log in to dash.pgbeam.com and go to **Settings > Billing** Update the payment method or reactivate the subscription Connections resume immediately after billing is restored ## IP not allowed **Cause:** The project has an IP allowlist configured and the client's source IP does not match any of the allowed CIDR ranges. The connection is rejected before authentication. **Fix:** Check the project's IP allowlist in **Settings > Security** in the dashboard Add the client's IP address or CIDR range to the allowlist If connecting from a cloud environment, make sure the NAT gateway or egress IP is included. Container and serverless platforms often use shared egress IPs that differ from the instance's private IP To disable the allowlist entirely, set it to an empty array ## Auth rate limited **Cause:** Too many failed authentication attempts from the same IP address in a short period. PgBeam rate-limits auth attempts per IP to protect the upstream database from brute-force attacks. **Fix:** Verify your credentials are correct by connecting directly to the origin database Wait for the rate limit window to expire (typically a few minutes) If the issue persists, check for misconfigured clients that are retrying with wrong credentials in a loop ## `08006`: Connection failure SQLSTATE `08006` means PgBeam accepted the connection but could not complete the upstream handshake. ## Upstream auth failure **Cause:** The credentials were forwarded to the origin database and it rejected them. PgBeam passes this error through as-is. **Fix:** Connect directly to the origin database with the same username and password to confirm they work Verify the database name in the PgBeam project configuration matches the actual database Check that the user has `CONNECT` permission on the database If the origin uses `pg_hba.conf` rules, confirm the PgBeam IP range is allowed ## Circuit breaker open **Cause:** The origin database failed 3 consecutive connection attempts. PgBeam opens a circuit breaker to stop sending traffic to an unhealthy upstream. The breaker probes for recovery every 5 seconds, backing off exponentially up to 60 seconds. **Fix:** Check the health of your origin database. Can you connect to it directly? Verify network connectivity between PgBeam and the origin (firewall rules, security groups, IP allowlists) Check if the origin has hit its own connection limit (`max_connections` in PostgreSQL) Wait for the circuit breaker to probe and recover automatically, or restart the origin database if it is down See Resilience for details on circuit breaker behavior. ## `53300`: Too many connections **Cause:** The project has reached its concurrent connection limit. Each plan tier has a maximum number of simultaneous connections: Plan Connection limit Starter 20 Pro 100 Scale 500 **Fix:** **Reduce client-side pool size.** If you are running multiple application instances, each with a pool of 20 connections, they add up quickly. With PgBeam handling upstream pooling, a client-side pool of 3-5 per instance is usually sufficient. **Switch to transaction pool mode.** Session mode (the default) holds an upstream connection for the entire client session. Transaction mode releases it after each transaction, dramatically improving connection reuse. See Connection Pooling. **Close idle connections.** Check for long-lived idle connections from monitoring tools, migration scripts, or dev environments that hold connections open unnecessarily. **Upgrade your plan** if the workload has genuinely outgrown the current tier. ## `53400`: Query rate limit exceeded **Cause:** The project exceeded its queries-per-second (QPS) limit: Plan QPS limit Starter 10 Pro 50 Scale 250 **Fix:** **Enable caching** for frequently repeated reads. Cached queries do not count against the QPS limit at the upstream. See Caching. **Reduce query frequency.** Batch reads where possible, or add application-level deduplication for concurrent identical queries. **Upgrade your plan** for a higher QPS allowance. ## Handling errors in application code Most PostgreSQL drivers expose the SQLSTATE code programmatically. Use it to distinguish PgBeam-specific errors from upstream database errors: ## Further reading Troubleshooting: Step-by-step debug workflows for common failures Resilience: Circuit breaker states, scale-to-zero, and recovery behavior Plans & Limits: Connection, QPS, and query quotas per plan tier --- # Honeytokens URL: https://pgbeam.com/docs/honeytokens Description: Register decoy relations that no legitimate agent should ever touch. An agent query that references one is blocked and recorded as a canary_tripped event, with an optional automatic kill. A honeytoken is a decoy (canary) relation. No legitimate agent has any reason to read it, so a query that references one is a strong signal of a misused credential, a prompt-injected agent, or an over-broad policy. PgBeam matches every agent statement against the project's honeytokens before it reaches the database. A match blocks the statement (fail closed), records a dedicated `canary_tripped` audit event, fires the `canary_tripped` webhook, and raises an anomaly alert. If the honeytoken's action is `kill`, the tripping credential is also disabled through the kill-switch. Detection rides the same static parse-tree analysis as the table allowlist, so a decoy reached through a JOIN, subquery, CTE, or alias trips exactly like a direct read. There is no second enforcement path to bypass. ## Register a honeytoken Create a honeytoken from the dashboard under Configure, Security, from the CLI, or through the API. Each entry is a relation (an optional schema plus a required name) and an action. `update` replaces the whole record, so pass the relation as well as the action. The commands act on the linked project; pass `--project` to target another one. The equivalent REST call is: The relation does not have to exist. A decoy table that is never used by your application is the cleanest signal: any access to it is unauthorized by definition. The relation is matched with the same normalization the allowlist uses, so `customer_ssns` (bare) and `public.customer_ssns` match the same table. ## Actions Action Effect on a trip `audit_only` Block the statement, record the `canary_tripped` audit event, fire the webhook, raise an alert. `kill` Everything `audit_only` does, and disable the tripping credential through the kill-switch. Either way the statement is blocked with SQLSTATE `42501` and never runs against your database. ## What happens on a trip The statement is blocked before it reaches the database, with an LLM-readable reason. A `canary_tripped` audit event is written to the tamper-evident audit log, carrying the credential, session, and normalized SQL. The `canary_tripped` webhook event is delivered to any subscribed endpoint. A critical anomaly alert is raised (deduped per credential per hour), visible in the Anomalies view. For a `kill` honeytoken, the credential is disabled and every live session on it is terminated within seconds. ## Invisible by design Honeytokens are excluded from discovery so an agent cannot learn which relations to avoid: They are hidden from the MCP `schema_catalog` and `list_tables` output, including foreign keys that reference them. The auto-policy recommender never adds a honeytoken to a derived allowlist, even if a credential's real traffic touched one. ## Notes Honeytokens apply to agent credentials and to policy-enforced passthrough connections. Direct, unenforced connections are not in the agent gateway path. A honeytoken always blocks, even if the same relation was mistakenly added to the allowlist. Detection wins. --- # How It Works URL: https://pgbeam.com/docs/how-it-works Description: How PgBeam enforces agent policy in the PostgreSQL wire protocol, between an AI agent and your database, with no code changes and any Postgres host. PgBeam sits in the wire between an AI agent and your database. The agent connects to PgBeam, not to Postgres directly. Every statement the agent sends is parsed, checked against the policy attached to its credential, and only forwarded if it is allowed. Enforcement happens at the PostgreSQL wire protocol, so it works with RDS, Aurora, self-hosted Postgres, or any managed provider, with no extension to install and no change to your schema. ## The path of a query The agent sends a statement over its scoped connection string or the hosted MCP endpoint. PgBeam authenticates the agent credential and resolves the policy attached to it. PgBeam parses the statement and checks it: access mode (read-only or read-write), table allowlists, and statement type. If the statement is blocked, PgBeam returns a PostgreSQL `ErrorResponse` with an LLM-readable reason. The query never reaches your database. If the statement is allowed, PgBeam forwards it upstream using your stored database credentials, applies masking to the result, counts it against the budget, and records it in the audit log. ## Why the wire, not the database Role grants and row-level security live inside one database. They cannot mask a column on the way out, return an LLM-readable reason, cap a query budget, or give you a single audit trail across every database. PgBeam enforces in the wire protocol, so the same policy engine reaches every Postgres host you connect, including ones a database vendor cannot reach because they only guard their own hosting. ## Two front doors, one policy engine You can hand an agent either surface. Both are backed by the same policy. A **scoped connection string** for any PostgreSQL driver, ORM, or framework. See Connection string. A **hosted MCP endpoint** for Claude Code, Cursor, or any MCP client. See Hosted MCP. ## What you control per credential Control What it does Access mode Read-only or read-write. See Read-only. Table allowlists Allow the exact relations. See Allowlists. PII masking Redact, null, or hash columns in flight. See Masking. Query budgets Cap queries per window and rows per result. See Budgets. Kill-switch Stop one agent or every agent instantly. See Kill-switch. Audit trail Record every statement and decision. See Audit log. ## Honest limits PgBeam fails closed for agent credentials. Unparseable SQL, unknown statement types, `COPY`, and multi-statement batches containing any blocked statement are rejected. Relation allowlists do not see through views. Allowlist the views you want the agent to read. `SET search_path` is blocked for agent credentials to prevent allowlist evasion. Binary-format result columns are masked to `NULL`; text-format columns get a redaction token. See Masking for the semantics. ## Next Quickstart: connect an agent in two minutes. Policies: the full policy model. Agent credentials: scoped, revocable access. --- # Getting Started URL: https://pgbeam.com/docs Description: Give an AI agent safe, scoped, audited access to your Postgres. Enforcement is in the wire protocol, so it works with any Postgres and no code changes. PgBeam is the safe Postgres gateway for AI agents. You hand an agent a scoped connection string or a hosted MCP endpoint instead of a superuser one, and PgBeam enforces what it can do: read-only access, table allowlists, PII masking, query budgets, and a kill-switch. Every query is audited. Enforcement happens at the PostgreSQL wire protocol, so it works with RDS, Aurora, self-hosted, or any managed Postgres, with no extension to install and no change to your schema. Issue a scoped credential, attach a read-only policy, and point your agent at it. No SDK, no protocol shim, no application rewrite. Start with the Quickstart. ## Connect an agent Give an agent safe, read-only access in two minutes. Paste one URL into Claude Code, Cursor, or any MCP client. Ten tools: policy-enforced briefing, query, validate\_sql, list\_tables, describe\_table, explain, schema\_catalog, and my\_permissions, plus search\_docs and read\_doc. A scoped Postgres URL for any driver, ORM, or agent framework. Enforced from the first query. Enforcement in the wire protocol, between the agent and your database. ## The policy you control Block every write and DDL. Reads pass, writes are rejected at the wire. Allow the exact schemas and tables the agent should touch. Redact, null, or hash sensitive columns in flight. The agent never sees raw values. Cap queries per window and rows per result. Runaway loops hit a ceiling. Stop one agent or every agent instantly. No credential rotation. Every statement recorded with its decision, rows, bytes, and latency. ## A real proxy underneath The gateway runs on a globally distributed wire-protocol proxy. Agent traffic gets connection pooling, query caching, replica routing, and edge latency for free. These are supporting features now, not the headline. Absorb the connections agents leak without wiring PgBouncer into every environment. Absorb the questions agents re-ask, with TTL and stale-while-revalidate controls. Route selected reads to replicas instead of treating every query the same. ## How do you connect your own application? The pages above cover giving an **agent** safe access. PgBeam also sits in front of your **own application** for pooling, caching, replicas, and routing. The setup below is that path: point your app at a PgBeam hostname and keep speaking normal PostgreSQL. Your application's passthrough connection is never subject to agent policies. ## Prerequisites Before you begin, you need: A PostgreSQL database reachable from the internet The connection details for that database: host, port, username, password, and database name ## Setup ## Create an account Sign up at dash.pgbeam.com. New accounts start on the Starter plan, which includes a 14-day trial. A default organization is created for you automatically. ## Create a project Create a project in the dashboard. Each project gets a hostname like `abc.proxy.pgbeam.app`. That hostname is what your application will connect to. ## Add your origin database Use **Add Database** in the dashboard and enter the connection details for the database PgBeam should forward traffic to. Field Description Example **Host** Origin database hostname `db.example.com` **Port** PostgreSQL port `5432` **Database name** Database to connect to `mydb` **SSL mode** TLS mode used for the upstream connection `verify-full` `verify-full` is the right default for most managed databases. Only relax it if your provider does not give you a certificate chain your client can verify. PgBeam stores the origin database credentials you enter here. Application user credentials are still checked by the origin database at connection time. ## Replace the host in your connection string Keep the username, password, port, and database name. The hostname is the only required change. ## Run a query At this point your app should already be talking through PgBeam: If that works, the plumbing is done. Pooling and observability are already in the path. Caching is available when you are ready to turn it on. ## When should you turn on caching? Caching starts off disabled for new databases. That is the safer default. Once traffic is flowing, you can enable it for stable reads that benefit from reuse. Open your database in the dashboard and go to **Cache Rules**. PgBeam tracks query shapes automatically, so you can enable caching on the high-frequency reads that are worth it. See the Caching guide for TTL, SWR, bypass rules, and cache annotations. ## Which clients are supported? PgBeam works with any PostgreSQL-compatible client. The docs include concrete setup guides for the tools people ask about most often: Language Drivers and ORMs TypeScript Prisma, Drizzle, Sequelize, TypeORM Python psycopg, SQLAlchemy Go pgx Java JDBC, HikariCP, Spring Boot ## Prefer the terminal? The PgBeam CLI covers the same setup flow: ## Where should you go next? Framework-specific setup instructions and pool sizing guidance. Learn when cache helps, when it bypasses, and how to turn it on safely. Manage PgBeam from the terminal and script the control plane. Call the same REST API used by the dashboard and generated SDK. Understand routing, relay, pooling, and failure behavior. --- # Insights URL: https://pgbeam.com/docs/insights Description: Query-level analytics for a project. Top query shapes by call count, with cache hit rate and latency for each, plus aggregate cache and latency summaries. Insights shows what your project's traffic actually looks like. It groups statements by normalized shape, ranks them by call count, and reports the cache hit rate and latency for each shape. Alongside the per-query breakdown it gives you two aggregate summaries: overall cache performance and overall latency for the window you pick. Use it to find the queries worth caching, spot a shape whose latency has crept up, and see how much the cache is saving you. ## Read insights Open the **Observability** page for a project. It shows the cache hit rate, average latency, and P99 latency for the selected window, then a sortable table of the top query shapes. Switch the time range between 1h, 6h, 24h, and 7d. ## Time range and limit Two query parameters shape the response: Parameter Values Default Description `range` `1h`, `6h`, `24h`, `7d` `24h` Time window the metrics are computed over. `limit` `1` to `100` `20` Maximum number of top query shapes to return. The CLI exposes `--range`; the dashboard exposes the same windows as buttons. ## What you get back The response has three parts: a list of top query shapes, a cache summary, and a latency summary. ## Top queries Each entry in `queries` is one normalized query shape, so `WHERE id = 1` and `WHERE id = 2` count as the same shape. Entries are ranked by call count. Field Description `query_hash` Hash of the normalized SQL pattern. `query_pattern` The normalized SQL, truncated to 500 characters. `total_count` Executions in the time range. `total_cache_hits` Cache hits attributed to this shape. `total_cache_misses` Cache misses attributed to this shape. `avg_latency_ms` Average latency for this shape, in milliseconds. `p99_latency_ms` P99 latency for this shape, in milliseconds. ## Cache summary Aggregate cache performance across all queries in the window. Field Description `total_hits` Total cache hits in the window. `total_misses` Total cache misses in the window. `hit_rate` Hit rate as a fraction from `0.0` to `1.0`. ## Latency summary Aggregate latency across all queries in the window. Field Description `avg_ms` Average latency in milliseconds across queries. `p99_ms` P99 latency in milliseconds across queries. ## How to read it A shape with a high `total_count` and a low `total_cache_hits` is a caching opportunity. Add a cache annotation and watch the hit rate climb on the next scan. A shape whose `p99_latency_ms` is far above its `avg_latency_ms` has a tail worth investigating: a missing index, a lock, or an occasional large result. A `hit_rate` that drops after a deploy usually means a query shape changed and the old cache entries no longer match. ## Related Caching: the feature these hit-rate numbers measure. Audit log: per-statement detail behind the aggregates. Anomaly detection: alerts when a credential's traffic drifts from its baseline. --- # IP Filtering URL: https://pgbeam.com/docs/ip-allowlist Description: Restrict database connections to specific IP addresses or CIDR ranges using per-project IP filtering with optional labels. IP filtering lets you restrict which client IP addresses can connect to a project through PgBeam. When enabled, connections from IPs outside the allowlist are rejected before authentication: they never reach the upstream database. ## How it works Each project has an optional list of CIDR filtering rules. When the list is non-empty, PgBeam checks every incoming connection's source IP against the rules during the TLS handshake, before any PostgreSQL protocol exchange. Filter state Behavior Empty (default) All IPs are allowed One or more CIDR rules Only matching IPs are allowed; others are rejected Rejected connections receive a FATAL error and the connection is closed immediately: ## Configure IP filtering You can manage IP filtering from the dashboard, API, or CLI. Each entry consists of a CIDR range and an optional label. Use `/32` for a single IPv4 address or `/128` for a single IPv6 address. Navigate to your project and go to **Settings > Security**. Toggle IP filtering on, then add CIDR blocks with optional labels. Changes take effect within seconds across all data plane regions. To disable IP filtering, set it to an empty array: ## Limits Maximum **50 CIDR entries** per project Both IPv4 and IPv6 CIDR notation are supported Each entry supports an optional human-readable label (max 100 characters) A plain IP without prefix length defaults to `/32` (IPv4) or `/128` (IPv6) Changes propagate to all data plane regions within seconds via the config streaming channel ## Common patterns ## Allow a single office IP ## Allow a VPC range and a developer IP ## Allow IPv6 ranges Make sure to include the IP ranges of all environments that connect through PgBeam: production servers, CI/CD pipelines, developer machines, and any monitoring tools. Forgetting an IP range will block those connections. ## Interaction with other features IP allowlisting is checked **before** authentication, connection pooling, and all other proxy features. The evaluation order for an incoming connection is: TLS handshake and SNI-based project lookup **IP allowlist check** (if configured) Authentication (credentials forwarded to upstream) Connection pooling and query relay This means: Blocked IPs never consume a connection slot Blocked IPs never trigger auth rate limiting The upstream database never sees traffic from disallowed IPs ## Further reading Error Codes: SQLSTATE `08004` handling guidance Troubleshooting: Debug connection rejections Resilience: Circuit breakers and connection lifecycle --- # JDBC URL: https://pgbeam.com/docs/jdbc Description: Connect Java applications to PgBeam using JDBC, HikariCP, and Spring Boot for connection pooling, caching, and global routing. Connect your Java application to PgBeam by updating the JDBC connection URL. This guide covers plain JDBC, HikariCP connection pooling, and Spring Boot configuration. ## Setup ## Connection pool sizing PgBeam manages upstream connection pooling, so keep HikariCP's pool small: Deployment type Recommended `maximumPoolSize` Single instance 5-10 Multiple instances behind LB 3-5 per instance Batch processing 2-5 The default HikariCP pool size is 10, which is already reasonable with PgBeam. For deployments with many instances, reduce to 3-5 per instance to avoid hitting PgBeam's connection limit. ## HikariCP recommended settings ## SSL / TLS The PostgreSQL JDBC driver connects to PgBeam over TLS. PgBeam's certificate is publicly trusted and works with all standard Java TLS configurations. To explicitly enable SSL: For Spring Boot: ## Caching ## Automatic caching via cache rules For JPA/Hibernate queries and Spring Data repositories, PgBeam automatically tracks the generated SQL shapes. Enable caching for specific shapes through Cache Rules in the dashboard, with no code changes needed. ## SQL annotations for fine-grained control With Spring's `JdbcTemplate`: ## Read replicas Route read queries to replicas using the `/* @pgbeam:replica */` annotation: See Read Replicas for replica setup and routing details. ## Error handling JDBC exposes PostgreSQL SQLSTATE codes through `SQLException.getSQLState()`: See Error Codes for the full reference. ## Migrations Run migrations directly against your origin database: Do not run Flyway or Liquibase migrations through PgBeam. Migration tools use advisory locks and session-level features that should bypass the proxy. ## Debugging Enable debug mode to see cache and routing details: To capture NOTICE messages in JDBC, register a `NoticeListener` (pgJDBC) or check your logging framework's PostgreSQL driver output. ## Common issues Issue Cause Fix "too many connections" HikariCP pool too large Reduce `maximumPoolSize` to 3-5 SSL handshake errors Missing `ssl=true` in URL Add `?ssl=true&sslmode=require` Stale data after writes Cache returning old results Use `noCache` annotation or adjust TTL Migrations fail through PgBeam Advisory locks not supported Run migrations against origin directly ## Further reading Connection Pooling: Pool modes, sizing, and lifecycle Caching: TTL, SWR, cache layers, and cache rules Error Codes: SQLSTATE reference for PgBeam errors --- # Kill-switch URL: https://pgbeam.com/docs/kill-switch Description: Stop one agent or every agent on a project instantly. The next statement is refused, with no credential rotation. The kill-switch stops an agent now. Trip it on a single credential to cut off one agent, or at the project level to stop every agent at once. The next statement on a killed credential is refused. There is no credential rotation and no change to your database. ## Trip the kill-switch On the **Credentials** tab, select a credential and disable it. To stop every agent at once, engage the project-level kill-switch in the project settings. Reverse either one by sending `{"status": "active"}` to the credential or `{"agents_disabled": false}` to the project. ## How it takes effect The kill state streams to the data planes and applies on the next statement. A killed agent gets a clear error over a connection string, and a `401` over the hosted MCP endpoint. ## Kill-switch vs revoke Action Effect Reversible Kill-switch Pauses access immediately. Credential and policy are preserved. Yes Revoke Removes the credential entirely. No Use the kill-switch when you want to stop an agent now and decide later. Use revoke when the credential should be gone for good. When an organization-level budget ceiling is breached, the control plane can trip the kill-switch automatically. See Budgets. ## Related Agent credentials Budgets Audit log --- # Local policy testing URL: https://pgbeam.com/docs/local-testing Description: Test allowlists, masking, row filters, and statement rules against a local or dev database with the pgbeam-dev tool, before a policy reaches prod. `pgbeam-dev` runs the PgBeam policy engine on your machine. Write a policy as a JSON or YAML file, evaluate statements against it offline, or stand up a local wire-protocol gateway in front of a dev database and point your agent at it. Nothing is deployed and no PgBeam account is involved; when the policy behaves the way you want, save the same file through the API, the dashboard, or the IaC providers. ## Who this is for `pgbeam-dev` lives in the PgBeam source tree, which is not public. It is a tool for teams working with that source: self-hosted and enterprise deployments set up with the PgBeam team, and contributors. If that is you, run it from the repository root as a Go program: A prebuilt binary distribution is planned but not available yet. If you are on the hosted platform without source access, the policy what-if and replay endpoints cover the same test-before-rollout need against your real traffic, no local tooling required. Both modes run the same code the platform runs. `check` uses the engine behind the policy what-if endpoint, and `serve` runs the production proxy's wire path with a static local config. There is no separate local implementation that could drift from real enforcement. ## Policy file The file shape is the API's `PolicyProfileInput` schema, the same body `POST /v1/projects/{id}/policies` accepts, validated with the same validators. Unknown fields are rejected. ## Check statements offline Prints a verdict per statement: `allow`, `block` with the rule and an actionable hint, `mask` with the masked output columns, or `row-filter` with the injected predicate and the rewritten SQL. Add `-json` for a machine readable report, or `-file queries.sql` (or `-file -` for stdin) to evaluate a whole file of statements. The exit code is 1 when any statement is blocked, which makes `check` a CI gate for policy-as-code repositories: keep the policy file and the queries your agent is expected to run in the repo, and fail the build when a policy change would break them. ## Run a local gateway The gateway listens on `127.0.0.1:6432` (change with `-listen`) and prints a connection string for a local `agent_dev` credential. Connect any client, ORM, or agent to it and every statement is enforced exactly like production: blocked statements get the same LLM-readable errors, masked columns come back redacted, row filters are injected before the statement reaches your dev database. Each decision is logged to stdout. Local limits, by design: no TLS (loopback only), approvals fail closed (no reviewer exists locally), `write_mode: sandbox` writes are rejected (no instant branches), budgets reset on restart, and the query cache is disabled so every statement hits the database. The tool's README (`backend/tools/pgbeam-dev/README.md` in the source tree) has the full flag reference. --- # PII Masking URL: https://pgbeam.com/docs/masking Description: Redact, null, or hash sensitive columns in agent results. Applied in flight, so your app sees real values and the agent never does. Masking rewrites sensitive column values in an agent's results before they leave the wire. You name the columns to protect and choose how to mask each one. Your application keeps reading the real values on its own connection. The agent receives masked data it can still join and group on, but never the raw value. ## Define masking rules In the dashboard, add masking rules on the policy profile under **Masking**. ## Mask kinds Kind Text-format result Binary-format result Use it for `redact` A fixed token, e.g. `[redacted]` `NULL` Free-text fields the agent must not read. `hash` SHA-256 hex of the value `NULL` Joinable identifiers (email, user key). `null` Empty / `NULL` `NULL` Columns the agent should ignore entirely. `hash` keeps the same input mapping to the same output, so an agent can still join and group on the column without ever seeing the cleartext. ## When masking applies Masking is applied at serve time on the result path, for agent sessions only. It runs whether the result comes from your database or from PgBeam's cache: the cache keeps raw bytes, and each connection's policy decides what it sees. Your application's passthrough connection is never masked. Binary-format result columns are masked to `NULL` to stay type-safe; text-format columns get a redaction token or hash. When a query computes an expression over a masked column (for example `lower(email)`), the result cannot be proven to preserve the original value, so PgBeam masks that output column to `NULL` rather than returning the computed value. This follows the value through a subquery or CTE, so an aggregate over a derived column (for example `SELECT sum(n) FROM (SELECT length(email) AS n FROM users) t`) is masked too. Allowlist the columns you expose and mask the ones you must protect. ## Combine with allowlists Masking and allowlists work together. Allow a column so the agent can join and group on it, and mask it so the agent never reads the raw value. ## Related Policies Allowlists Audit log --- # Hosted MCP server URL: https://pgbeam.com/docs/mcp Description: A hosted MCP endpoint that gives AI agents policy-enforced database tools. Paste one URL into Claude Code, Cursor, or any MCP client. No server to run. The hosted MCP endpoint is a remote Model Context Protocol server that exposes policy-enforced database tools to an AI agent. You paste one URL into your MCP client, and the agent gets `briefing`, `query`, `validate_sql`, `list_tables`, `describe_table`, `explain`, `schema_catalog`, and `my_permissions`, plus `search_docs` and `read_doc` for looking up how PgBeam works. Every database call runs through the same policy engine as a scoped connection string, so the agent is held to the same guardrails. There is nothing to install and no server to run. This endpoint gives an agent **query access to your database**. The separate management MCP administers your PgBeam account (projects, policies, credentials). Different URL, different tools. ## Connect a client The endpoint is served on your project's own host, `https://.proxy.pgbeam.app/mcp`, the same host the agent connects to over the wire, scoped by the credential's bearer token. The exact URL and the `pba_…` token are shown in the **Credentials** tab and in the credential create response; copy them from there. Add it with the CLI: Or write it directly to `.mcp.json`: Claude Desktop's config file takes local `command`/`args` servers only, so it reaches a remote endpoint through the `mcp-remote` bridge rather than a `url` entry. Add this to `claude_desktop_config.json`, then restart Claude Desktop: The file lives at one place per machine: OS Path macOS `~/Library/Application Support/Claude/claude_desktop_config.json` Windows `%APPDATA%\Claude\claude_desktop_config.json` It holds every MCP server you have, so merge the `pgbeam` entry into the existing `mcpServers` object instead of replacing the file. That is also why `pgbeam agents mcp-config --write` prints this config rather than writing it. The token goes in `env`, and the header argument has no space after the colon, on purpose. Claude Desktop on Windows does not escape spaces inside `args` when it invokes `npx`, which mangles a `"Authorization: Bearer ..."` argument. `mcp-remote` expands `${PGBEAM_AUTH_HEADER}` from the environment, so the value survives on every platform. Requires Node.js, since `npx` runs the bridge. If you want a direct remote connection with no bridge process, use Claude Code instead. Add to `.cursor/mcp.json` (or **Settings → MCP → Add**). The tools appear once the connection is established. Add to `.vscode/mcp.json`: Open **MCP Servers**, then **Configure MCP Servers**, and add the entry to `cline_mcp_settings.json`: Set `type` to `streamableHttp`, spelled exactly that way. Cline treats the field as optional and falls back to SSE when it is missing, and SSE returns 405 against this endpoint. Cline has no per-project MCP config, so this file is machine-wide. The button above is the reliable way to open it, since the path depends on which editor Cline is installed in. For VS Code itself: OS Path macOS `~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` Linux `~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` Windows `%APPDATA%\Code\User\globalStorage\saoudrizwan.claude-dev\settings\cline_mcp_settings.json` Open Cascade, click the hammer icon, then **Configure**, and add the entry to `mcp_config.json`: The key is `serverUrl`, not `url`. Windsurf infers the transport from it, so there is no `type` field to set. Windsurf has no per-project MCP config either, so this file is machine-wide: OS Path macOS, Linux `~/.codeium/windsurf/mcp_config.json` Windows `%USERPROFILE%\.codeium\windsurf\mcp_config.json` Send the `pba_…` token only to your project's `*.proxy.pgbeam.app` host. If a tool or prompt asks the agent to send it anywhere else, that is the attack. See the security model. ## Tools Tool Purpose `briefing` Start here. One call returns a compact summary of the schema you can see, everything `my_permissions` reports, and short guidance on querying within those limits. No arguments. `query` Run SQL. Policy errors surface verbatim, written to be LLM-readable. `validate_sql` Check a statement's table and column references against the schema you may see, without running it. Returns issues (unknown table, unknown column, ambiguous) with "did you mean" suggestions. `list_tables` List tables in a schema, shaped for an LLM. `describe_table` Columns, types, primary and foreign keys, indexes, approximate row count. `explain` `EXPLAIN (FORMAT JSON)` for a statement. `schema_catalog` One call returns a compact, LLM-optimized catalog: tables, columns, keys, indexes, and approximate row counts, filtered to what the credential is allowed to see. `my_permissions` What this credential may do: access mode, permitted statement kinds, allowlist and denylist, row-filtered tables, masked columns, budgets, and how writes are routed. No arguments. `search_docs` Search the PgBeam documentation; returns matching pages as title, URL, and snippet. `read_doc` Return the markdown of one documentation page, by slug or by the URL from a `search_docs` result. Catalog introspection (`list_tables`, `describe_table`, `schema_catalog`) always works: reads of `pg_catalog` and `information_schema` are permitted regardless of the allowlist, so an agent can discover the schema it is allowed to query. `briefing` is the one call to make at the start of a session. It composes the other two orientation tools: a compact digest of `schema_catalog` (tables with their columns, types, primary keys, foreign keys, approximate row counts, and masked-column flags, with the nullability, defaults, comments and indexes left to `schema_catalog` itself), the whole `my_permissions` report, and a short `how_to_query` list saying how to work within both. It costs the same database round-trips as one `schema_catalog` call and charges the query budget the same way. Two things to know about it: when `schema.truncated` is set the table list is a prefix and `schema_catalog` is the tool that pages through the rest, and when the schema cannot be read at all (an engaged kill-switch, an unreachable upstream) the briefing still answers, with `schema.unavailable` carrying the reason and the policy half intact. `my_permissions` is how an agent learns its limits without discovering them by being blocked. It reads the credential's compiled policy out of the proxy's own streamed state, so it costs no database round-trip, and it reports the effective policy rather than the raw record: a statement kind listed as allowed is one the policy engine itself was asked about, and the `always_blocked` list carries the safety floor no policy can switch off (DO blocks, `search_path` changes, whereless writes, `DROP`/`TRUNCATE`, the dangerous-function families). Two things it never returns: your honeytokens, because a decoy an agent can enumerate has stopped being a decoy, and the text of a row-filter predicate, though the filtered table is named. The docs tools (`search_docs`, `read_doc`) are read-only and not scoped to your database. They let the agent answer its own questions about PgBeam, for example why a query was blocked or how masking and budgets behave, without leaving the session. ## Enforcement is identical to the connection string The MCP endpoint executes SQL as a PostgreSQL wire client through the nearest data plane, using the agent credential. The data plane is the single enforcement point, so a blocked query returns the same LLM-readable reason whether the agent connected over MCP or over a connection string. Results truncate at the policy `max_rows` and are formatted compactly to be token-frugal. A truncated result says so. When the policy `max_rows` cap or the endpoint's own 1000-row ceiling withholds rows, the `query` result carries `"truncated": true` and a `notices` list naming the cap that fired, so an agent can tell a short answer from a complete one instead of reporting the prefix as the total. The same signal reaches a connection-string client as a PostgreSQL `NOTICE`. ## Errors an agent will see All of these come back as **tool-result errors** (the MCP endpoint authenticates each tool call, so failures are reported in the result rather than as an HTTP status): A blocked statement returns the policy reason in the tool result, so the agent can correct itself and retry within the rules. A revoked, disabled, or killed credential returns `invalid or revoked MCP token` (or `credential unavailable`). An exhausted budget returns a clear message naming the window and reset time. ## Related Connection string: the other front door. Policies: what the tools are enforced against. Agent credentials: issue and revoke MCP tokens. --- # Organizations URL: https://pgbeam.com/docs/organizations Description: Manage teams, invite members, assign roles, and control access across projects. Organizations are the top-level container in PgBeam. Every project, database, billing subscription, and usage quota belongs to an organization. Team members access shared resources through their organization membership. ## How organizations work When you sign up, PgBeam creates a default organization for you. You can create additional organizations to separate workloads. For example, one for production and one for staging, or separate organizations for different clients. Each organization has: A **slug** that appears in dashboard URLs (e.g., `dash.pgbeam.com/my-team/projects`). The slug is set at creation and cannot be changed. A **billing subscription**: each organization has its own plan, payment method, and invoice history. **Shared quotas**: all projects within the organization share the same query, connection, and data transfer limits. ## Create an organization Click the organization switcher in the top navigation bar and select **Create Organization**. Enter a name and slug. ## Invite members ## Open member settings Go to **Settings > Members** in the dashboard. ## Send an invitation Click **Invite**, enter the recipient's email address, and select a role. The invited user receives an email with a link to accept and join the organization. ## Manage pending invitations Pending invitations appear in the Members list. You can resend or revoke an invitation at any time before it is accepted. ## Roles and permissions PgBeam uses three roles with progressively broader access: Role Projects & databases Members Billing & plan Delete org **Member** View and use No No No **Admin** Full CRUD Invite and remove (except owners) View No **Owner** Full CRUD Full control Full control Yes Every organization must have at least one owner. The last owner cannot be removed or downgraded. Transfer ownership to another member first. ## When to use each role Scenario Recommended role Developer who needs to query through PgBeam and view dashboards Member Team lead who manages project configuration and invites teammates Admin Engineering manager or account holder who controls billing Owner ## Team seats Each plan includes a set number of team seats. Additional seats can be added at $10/month each. Plan Included seats Max with add-ons Starter 1 Unlimited Pro 3 Unlimited Scale 5 Unlimited Additional seats are billed immediately and prorated for the current billing period. Removing a seat takes effect at the end of the billing period. ## Shared quotas All projects within an organization share the organization's plan quota. There are no per-project sub-limits: usage from every project counts toward the same pool. Quota What it covers **Queries/day** Total queries across all projects, reset at midnight UTC **Data transfer** Total bytes transferred per billing month **Connections** Total concurrent connections across all projects **Projects** Maximum number of projects in the organization **Databases** Maximum number of database registrations **Query shapes** Maximum number of distinct query fingerprints tracked Monitor usage from **Settings > Billing** in the dashboard, or programmatically: ## Switch organizations If you belong to multiple organizations, switch between them in the dashboard using the organization switcher in the top navigation bar. In the CLI: ## Transfer ownership To transfer ownership of an organization: Ensure the target member already belongs to the organization Go to **Settings > Members** and change their role to **Owner** Optionally downgrade your own role to Admin or Member Ownership transfers are immediate. The new owner gains full control over billing, plan changes, and the ability to delete the organization. ## Delete an organization Only owners can delete an organization. Deleting an organization: Terminates all active connections immediately Cancels the billing subscription Removes all projects, databases, cache rules, and custom domains Revokes all organization API keys Removes all member associations Organization deletion cannot be undone. Export any configuration or data you need before proceeding. ## Further reading Plans & Limits: Quota details and overage billing for each tier API Keys: Organization-scoped keys for CI/CD and automation SSO: Enterprise single sign-on for organization authentication --- # pgx URL: https://pgbeam.com/docs/pgx Description: Connect Go applications using pgx to PgBeam for connection pooling, caching, and global routing. Connect your Go application to PgBeam by updating the connection string. pgx is the most widely used PostgreSQL driver for Go and works with PgBeam without any code changes. ## Setup ## Set the connection string ## Connect with pgxpool ## Reduce pool size PgBeam handles upstream pooling, so reduce `pgxpool`'s pool: ## Pool sizing Since PgBeam manages upstream connections, keep your client-side pool small: Deployment type Recommended `MaxConns` Single binary / single pod 5-10 Multiple pods behind LB 3-5 per pod Short-lived CLI tools 1-2 With PgBeam in transaction pool mode, upstream connections are released after each transaction. A `MaxConns` of 5 per pod handles high concurrency without pressuring the upstream database. ## TLS pgx uses TLS by default when connecting to PgBeam. No additional configuration is needed. PgBeam's `*.proxy.pgbeam.app` certificate is publicly trusted and works with all standard Go TLS configurations. If you need to verify the TLS connection explicitly: ## Caching ## Automatic caching via cache rules For standard queries, PgBeam tracks the SQL shapes flowing through your project. Enable caching for specific shapes through Cache Rules in the dashboard. No code changes needed. ## SQL annotations for fine-grained control Use SQL comments for per-query cache control: ## Read replicas Route read queries to replicas using the `/* @pgbeam:replica */` annotation: See Read Replicas for replica setup and health check details. ## Error handling PgBeam returns standard PostgreSQL SQLSTATE codes. Use `pgconn.PgError` to handle PgBeam-specific errors: See Error Codes for the full reference. ## Migrations Run migrations directly against the origin database: This applies to all migration tools: golang-migrate, goose, atlas, or custom migration scripts. ## Debugging Enable debug mode to see cache and routing details: ## Common issues Issue Cause Fix "too many connections" `MaxConns` too high Reduce to 3-5 per pod Prepared statement errors Using transaction pool mode Use session pool mode, or avoid `Prepare()` Connection refused on startup Cold start after inactivity Normal: first connection is slower ## Further reading Connection Pooling: Pool modes, sizing, and lifecycle Caching: TTL, SWR, cache layers, and cache rules Error Codes: SQLSTATE reference for PgBeam errors --- # Plans and Limits URL: https://pgbeam.com/docs/plans Description: Plan tiers, feature comparison, per-plan quotas, overage billing, rate limits, and default settings. PgBeam offers three self-serve plans. New signups start on **Starter** with a 14-day trial. No credit card required. All limits apply per **organization**. Projects within an organization share the same quotas. ## Plan comparison Starter Pro Scale **Monthly price** $9/mo $29/mo $99/mo **Annual price** $90/yr $290/yr $990/yr **Queries/day** 50K 250K 2M **Data transfer/mo** 10 GB 50 GB 200 GB **Projects** 5 20 100 **Databases** 3 10 50 **Connections** 20 100 500 **QPS** 10 50 250 **Team seats** 1 3 5 **Query shapes** 100 1,000 10,000 **Custom domains** No No Yes **SSO (SAML/OIDC)** No No Yes ## Which plan to choose **Starter** is for individual developers and small projects. It gives you enough headroom to run a production workload with moderate traffic. The 14-day trial lets you evaluate PgBeam without entering payment details. **Pro** is for growing teams and production workloads. The higher QPS and connection limits handle multi-service architectures and busier applications. Three included team seats cover a small engineering team. **Scale** is for teams that need enterprise features: custom domains, SSO, and significantly higher quotas. If you have multiple services, high traffic, or compliance requirements, Scale is the right fit. ## Quota details ## Queries/day Total queries executed across all projects in the organization, counting every SQL statement that passes through PgBeam. Cache hits count as queries (they still flow through PgBeam), but they do not generate upstream database load. The daily counter resets at **midnight UTC**. ## Data transfer Total bytes transferred between PgBeam and your application (egress) per billing month. This does not include traffic between PgBeam and your upstream database. ## Connections Maximum number of **concurrent** connections across all projects. Each open connection from your application to PgBeam counts as one connection, regardless of pool mode. Using transaction pool mode helps reduce upstream connections but does not change the client-side connection count. ## QPS (queries per second) Maximum queries per second per project. When exceeded, PgBeam returns SQLSTATE `53400` (`query rate limit exceeded`). The rate limit is enforced per project, not per organization. ## Query shapes Maximum number of distinct query fingerprints that PgBeam tracks for cache rules and query insights. A query shape is the normalized SQL template with parameter values removed (e.g., `SELECT * FROM users WHERE id = $1`). ## 14-day trial New accounts on the Starter plan get a 14-day trial with full Starter features: No credit card required to start All Starter quotas and limits apply **Overage billing is not active** during the trial: queries exceeding the daily limit are blocked until the next UTC day Add a payment method at any time to convert to a paid subscription and enable overage billing After 14 days without a payment method, the organization is suspended. Projects and configuration are preserved. Add a payment method to reactivate. ## Overage billing Paid subscribers (with an active payment method) use **overage billing** instead of hard caps. This keeps your traffic flowing when usage spikes, rather than blocking queries at the plan limit. Overage type Rate Query overage $0.10 per 1,000 queries Data transfer $0.20 per GB Additional seats $10.00 per seat/month You can set a monthly spend limit to cap overage charges. When the limit is reached, additional queries are blocked until the next billing period. Configure spend limits in **Settings > Billing** in the dashboard. ## Overage billing examples Scenario Overage cost Starter plan, 60K queries in a day (10K over limit) $1.00 Pro plan, 70 GB data transfer in a month (20 GB over limit) $4.00 Scale plan, 2 additional team seats $20.00/month ## Annual billing Prepay annually for a discount equivalent to two months free: Plan Monthly Annual You save Starter $9/mo $90/yr $18/yr Pro $29/mo $290/yr $58/yr Scale $99/mo $990/yr $198/yr Switch to annual billing from **Settings > Billing** in the dashboard. ## Upgrades and downgrades Upgrades take effect **immediately**. Your new plan limits apply right away, and billing is prorated for the remainder of the current period. You keep all existing projects, databases, and configuration. Higher limits are available immediately. Downgrades take effect at the **end of the current billing period**. Until then, you retain your current plan's limits. Before the downgrade takes effect, make sure your usage fits within the lower plan's limits: Reduce the number of projects and databases if they exceed the new plan's maximums Remove team members if you exceed the new plan's seat count Custom domains and SSO are disabled when downgrading from Scale ## Cancellation Cancelling the subscription suspends the organization but does not delete anything: Active connections are terminated New connections are blocked Projects, database registrations, and cache rules remain in place API keys are preserved but non-functional Reactivation is possible at any time: add a payment method to resume ## Rate limits Limit Value QPS per project Plan tier (10 / 50 / 250) Auth attempts per IP Rate-limited per IP address API requests Standard REST rate limits per key When a rate limit is exceeded, PgBeam returns SQLSTATE `53400` for query limits or HTTP 429 for API limits. See Error Codes for handling guidance. ## Default settings New databases and projects start with these defaults: ## Cache defaults Setting Default Description TTL 60s How long cached results are considered fresh SWR 30s Stale-while-revalidate window after TTL Max entries 10,000 Maximum cached query results per project Enabled `false` Caching is off by default for new databases ## Connection pooling defaults Setting Default Description Pool mode Session No connection reuse between clients SSL mode `verify-full` Full TLS verification for upstream ## Enterprise For organizations with requirements beyond the Scale plan (custom quotas, SLAs, dedicated support, or volume pricing), contact sales\@pgbeam.com. ## Further reading Organizations: How quotas, seats, and billing work at the org level Connection Pooling: Pool mode selection and sizing guidance Caching: Cache defaults and how to tune TTL/SWR Error Codes: Rate limit error codes and handling --- # Policies URL: https://pgbeam.com/docs/policies Description: A policy profile is the named bundle of rules PgBeam enforces for an agent credential. Access mode, allowlists, masking, budgets, and timeouts. A policy profile is a named bundle of rules attached to one or more credentials. It is the single place you decide what a principal can do: read-only or read-write, which tables it can touch, which rows it can see, which columns are masked, and how much it can run. Policies stream to the data planes and hot-reload, so a change takes effect on the next query without restarting anything. Policies apply to agent credentials and to human credentials alike. Every rule below works the same whether an AI agent or a person runs the statement. See human and passthrough connections for applying policies beyond per-agent credentials. ## What a policy contains Rule What it controls Page Access mode Read-only or read-write, plus per-statement-type rules. Read-only Table allowlist The schemas and tables the principal may read or write. Allowlists Row filters A `WHERE` predicate that scopes a table to a slice of rows. Row-level policies Masking rules Columns redacted, nulled, or hashed in flight. Masking Query budgets Queries per window, max rows per result, statement timeout. Budgets Write row cap Hard cap on rows a single write may affect (over-cap writes roll back and block). Budgets Approvals Hold writes or DDL until a human approves them. Approvals Migration linting Warn or block dangerous DDL (locks, rewrites, unsafe drops). Safe migrations Sandbox target Route writes to a throwaway branch or roll them back. Sandbox writes ## Create and attach a policy Go to **Policies**, create a profile, set the rules, then attach it to one or more agents from the **Credentials** tab. ## Enforcement model PgBeam parses every statement a principal sends and checks it against the attached policy before forwarding it. Enforcement fails closed: unparseable SQL, unknown statement types, `COPY`, and multi-statement batches containing any blocked statement are rejected with an LLM-readable reason. Policy changes stream to the data planes and apply on the next query. You do not need to rotate the credential or reconnect the principal. ## Test a policy before you roll it out Two preview tools evaluate statements through the same engine the proxy enforces, so their verdicts match production exactly. Neither one connects to your database. **What-if (single statement).** Paste a statement and see the decision this policy would make: allow, block, mask, or row-filter, with the rule, the reason, and any rewritten SQL. In the dashboard the what-if box sits inside the policy editor and evaluates your unsaved draft. From the CLI: **Traffic replay (recorded history).** Replay your recent agent traffic from the audit log against a draft or saved policy and see what would change before you save it: which queries that ran would now be blocked, which blocked queries would now be permitted, and which results would be masked or row-filtered. Traffic is deduplicated by normalized query shape, newest first, so one noisy query does not drown out the rest. The replay summary counts newly blocked and newly allowed queries; those are the changes to review before rollout. Stateful checks a preview cannot model (per-region budgets, approvals, write-mode routing) are reported as informational notes on each result. **Right-size from traffic (recommend a policy).** Instead of writing a policy by hand, ask PgBeam to derive one from an agent credential's real audit history. It reads the statements the credential has actually run over a lookback window (30 days by default) and produces the tightest policy that still passes all of them: a table allowlist that is the union of the relations actually referenced, a statement-kind allow set limited to the kinds observed, a downgrade to read-only when no write, sequence-mutating, or lock-taking statement was seen, and a `max_rows` ceiling sized from a high percentile (p95) of observed row counts. The recommendation is derived only from statements that legitimately executed; blocked attempts are excluded, so it never widens access to something that was already refused. The candidate is then proven safe by replaying it against that same history: a good recommendation reports zero newly blocked statements. In the dashboard the "Right-size from traffic" box sits in the policy editor. Pick a credential and a window, and the candidate loads straight into the draft form for you to review and save. It never saves on its own and never changes an existing policy. From the CLI: For testing against a local or dev database before anything reaches PgBeam at all, the `pgbeam-dev` tool evaluates a policy file offline and can run a local enforcing gateway. See local policy testing. **Lint a policy for foot-guns.** What-if and replay check a policy against statements; the linter checks the policy's own shape. `pgbeam policies lint` runs offline over a saved policy or a draft file and flags risky combinations with a fix for each: read-write with no table allowlist, writes that commit with no `max_affected_rows` and no approval, no query budget, masking with no read ceiling, masking or row-filter rules on tables the policy makes unreachable, write settings that are inert under read-only, and redundant allow and deny overlaps. Use `--strict` to fail on any warning as a CI gate. ## Human and passthrough connections A policy can bind to more than a per-agent credential. Every credential carries a `principal_type`: `agent` for an AI agent's credential, `human` for a person's. The rules are identical; the field records who is connecting so the audit log and anomaly baselines can tell agents and people apart. You can also apply policies to connections that are not per-principal credentials at all: Scope What it covers Project default policy A baseline policy applied to every connection on the project, including your application's passthrough connection. Per-database policy A policy that overrides the project default for one database. Per-credential policy The policy attached to a single agent or human credential. The most specific scope wins: a per-credential policy overrides a per-database policy, which overrides the project default. Leave the project default unset to keep passthrough connections unrestricted, the original PgBeam behavior, and opt individual credentials into policies one at a time. Set a project default policy to enforce row filters, masking, or read-only rules on every connection, not just agents. Your own application can then read through the same guardrails an agent does, scoped per database where you need a different rule. ## Related Read-only enforcement Table allowlists Row-level policies PII masking Query budgets Approvals Safe migrations Sandbox writes Kill-switch --- # Connection Pooling URL: https://pgbeam.com/docs/pooling Description: How PgBeam pools upstream PostgreSQL connections per project, keyed by user credentials, and how to choose the right pool mode for your workload. PostgreSQL creates a new OS process for every client connection. Each process consumes memory (typically 5-10 MB), and the startup cost is non-trivial. At scale, this becomes the bottleneck: not query execution, but the cost of establishing and maintaining connections. PgBeam solves this by pooling upstream connections at the proxy layer. Your application opens connections to PgBeam, and PgBeam manages a smaller set of long-lived connections to the upstream database. The result is fewer upstream connections, faster connection establishment, and better resource utilization. ## How PgBeam pooling works Each project gets its own connection pool. PgBeam uses **credential passthrough**: your application sends real database credentials, and PgBeam forwards them to the upstream. Different users connecting through the same project get separate pool entries keyed by username. This means 30 application connections can share 5 upstream connections, reducing load on PostgreSQL without changing how your application authenticates. ## Pool modes Pool modes control how upstream connections are shared between clients. New databases default to **transaction mode**, the best balance of connection reuse and compatibility for most web and serverless workloads. You configure the mode per-project from the dashboard, API, or CLI. ## Session mode Each client connection gets a **dedicated** upstream connection for its entire lifetime. No connection sharing happens between clients. **How it works:** When a client connects, PgBeam dials an upstream connection (or reuses an idle one from the same user's pool). That upstream connection stays assigned to the client until it disconnects. **Best for:** Applications that use advisory locks (`pg_advisory_lock`) Temporary tables that persist across queries `LISTEN`/`NOTIFY` for real-time notifications `SET` parameters that must persist across queries Prepared statements created with `PREPARE` **Tradeoff:** Every concurrent client requires its own upstream connection. If you have 100 concurrent clients, you need 100 upstream connections. ## Transaction mode (default) The upstream connection is held only for the **duration of a transaction**. After `COMMIT` or `ROLLBACK`, the connection is reset with `DISCARD ALL` and returned to the pool. Other clients can reuse it immediately. **How it works:** When a client starts a transaction (explicitly or implicitly via a query), PgBeam acquires an upstream connection. When the transaction ends, the connection goes back to the pool. Between transactions, the client holds no upstream connection. **Best for:** Serverless functions (Lambda, Cloud Functions, Edge Functions) High-concurrency APIs with short-lived transactions Applications where most queries are independent, stateless reads and writes **Tradeoff:** Session-level state does not persist between transactions: `SET` parameters reset after each transaction Prepared statements are discarded `LISTEN`/`NOTIFY` is not supported Advisory locks are released If your application relies on session state persisting between transactions, transaction mode will break it. Common culprits: ORMs that use prepared statements implicitly, applications that set `search_path` once at connection startup, or code that uses `pg_advisory_lock` for distributed locking. ## Statement mode The upstream connection is acquired and released **per SQL statement**. This provides the finest-grained sharing. **How it works:** Each individual SQL statement gets an upstream connection for its execution. After the statement completes, the connection is immediately returned. **Best for:** Simple, stateless read-only workloads Maximum connection reuse when every query is independent **Tradeoff:** Multi-statement transactions are not supported. Each statement runs independently, so `BEGIN`/`COMMIT` blocks cannot span multiple statements. ## Choosing the right mode If your workload uses... Use mode Advisory locks, temp tables, `LISTEN/NOTIFY`, `SET` **Session** Short transactions, serverless, high concurrency **Transaction** Single-statement reads, no transactions needed **Statement** If you are unsure, start with **transaction mode**. It offers the best balance of connection reuse and compatibility for most web applications. Only switch to session mode if you need session-level PostgreSQL features, or to statement mode if you have a purely read-only workload. ## Feature compatibility matrix Feature Session Transaction Statement Multi-statement txns Yes Yes No Prepared statements Yes No No `SET` / `SET LOCAL` Yes Within txn No `LISTEN` / `NOTIFY` Yes No No Advisory locks Yes No No Temporary tables Yes No No `COPY` operations Yes Yes No Connection reuse No Yes Yes ## Pool sizing guidance Since PgBeam handles upstream pooling, your application's client-side pool should be smaller than you might be used to. The goal is to let PgBeam multiplex; having a large client pool defeats the purpose. Deployment type Recommended client pool size Single application server 5-10 Multiple replicas / pods 3-5 per instance Serverless (Lambda, etc.) 1-2 per invocation ## Max active connections The `max_active` setting caps how many concurrent upstream connections PgBeam will open to your database for a given project. This includes both idle and in-use connections. Once the limit is reached, new requests wait in a queue until a connection is released. The default is **200**, which works well for most managed PostgreSQL providers. Lower it if your upstream database has strict connection limits (e.g., small RDS instances), or raise it for high-throughput workloads with headroom on the upstream. Configure via the dashboard pool settings, the API (`pool_config.max_active`), or the SDK. ## How to think about it **Without PgBeam:** Your application pool size needs to match the maximum concurrent queries you expect, because each query holds an upstream connection. With 4 app servers each running a pool of 20, you need the upstream database to handle 80 connections. **With PgBeam (transaction mode):** Those same 4 servers can each use a pool of 5. PgBeam multiplexes 20 client connections into a smaller number of upstream connections, because most connections are idle between transactions. ## Connection lifecycle ## Pool acquire When a client connects, PgBeam looks for an idle upstream connection in the pool keyed by the client's username. If one is available, it is assigned immediately. If not, PgBeam dials a new connection to the upstream database. Your credentials are forwarded to the upstream for authentication. PgBeam does **not** store user passwords. Credentials are passed through transparently. ## Pool release When the client disconnects (or the transaction ends, in transaction mode): If session state was modified (via `SET`, `PREPARE`, `CREATE TEMP TABLE`, etc.), PgBeam sends `DISCARD ALL` to reset it. Clean sessions skip this step. The connection is returned to the pool for reuse Connections in an error state or mid-transaction are closed instead ## Idle connection cleanup Idle upstream connections are held for a period before being closed. This avoids the overhead of re-establishing connections for workloads with regular traffic patterns, while freeing resources during quiet periods. ## Changing pool mode Navigate to your project **Settings** and select the desired pool mode from the dropdown. Changing pool mode takes effect for **new connections only**. Existing connections continue to use the previous mode until they disconnect. To apply the change to all connections, restart your application or wait for existing connections to cycle. ## Common pooling patterns ## Serverless with transaction mode Serverless functions create a new database connection on every invocation. With PgBeam in transaction mode, these short-lived connections are efficiently multiplexed: each function invocation acquires an upstream connection only for the duration of its query, then releases it. ## Multi-tenant with separate credentials If your application connects with different database users per tenant, PgBeam automatically creates separate pool entries for each user. This provides connection isolation between tenants without configuring separate projects. ## Migrations and DDL Run migrations directly against the origin database, not through PgBeam. Migrations often use session-level features (advisory locks for migration locking, temporary tables, long-running transactions) that may not work correctly through a connection pool. ## Further reading Plans & Limits: Connection limits per plan tier Troubleshooting: Debugging `53300` (too many connections) Resilience: Connection reset, circuit breakers, and recovery --- # Prisma URL: https://pgbeam.com/docs/prisma Description: Connect Prisma to your PostgreSQL database through PgBeam for connection pooling, caching, and global routing. Connect your Prisma application to PgBeam by updating the `DATABASE_URL` environment variable. No changes to your Prisma schema, queries, or application code are required. ## Setup ## Update your connection string Point `DATABASE_URL` at your PgBeam project hostname: ## Verify your schema No changes needed to `schema.prisma`. The `postgresql` provider works as-is: ## Reduce Prisma's connection pool size PgBeam handles connection pooling at the proxy layer, so Prisma does not need a large local pool. Append `connection_limit` to your connection string: ## Run a test query If this returns results, Prisma is connected through PgBeam. ## Connection pool sizing By default, Prisma creates a pool of `num_cpus * 2 + 1` connections. Since PgBeam manages upstream pooling, you should reduce this to avoid holding unnecessary upstream connections: Deployment type Recommended `connection_limit` Single server 5-10 Multiple replicas/pods 3-5 per instance Serverless (Lambda) 1-2 With PgBeam in transaction pool mode, Prisma connections are multiplexed upstream. A pool of 5 per instance is sufficient for most workloads, even at high concurrency. New PgBeam databases default to **transaction** pool mode, where session state (including prepared statements) is reset between transactions. Prisma uses prepared statements by default, which can surface as `prepared statement "s0" already exists` / `does not exist` errors under a transaction-mode pooler. Treat PgBeam like PgBouncer in transaction mode: tell Prisma not to keep prepared statements across pooled connections by adding `pgbouncer=true` to the connection string. Or switch the project to **session** pool mode if you rely on session-level features. See Connection Pooling. ## Prisma Migrate Run Prisma migrations directly against your origin database, not through PgBeam. Migrations use advisory locks and other session features that should bypass the proxy. Set a separate environment variable for migrations or override inline: This applies to both `prisma migrate deploy` (production) and `prisma migrate dev` (development). ## Caching with Prisma ## Prisma Client queries (recommended) For standard Prisma Client queries (`findMany`, `findUnique`, etc.), PgBeam automatically tracks the generated SQL shapes. Enable caching for these shapes through Cache Rules in the dashboard. No code changes needed. ## Raw queries with annotations For Prisma raw queries, you can use inline SQL annotations for fine-grained cache control: ## Read replicas with Prisma Route read queries to replicas using the `/* @pgbeam:replica */` annotation in raw queries: Standard Prisma Client queries (`findMany`, etc.) always go to the primary database. To use replica routing, use raw queries with the annotation. See Read Replicas for details on replica setup and routing behavior. ## Debugging Enable PgBeam debug output to verify caching and routing behavior from within Prisma: ## Common issues Issue Cause Fix "Too many connections" on startup Prisma pool too large Add `?connection_limit=5` to `DATABASE_URL` Prepared statement errors Using transaction pool mode Switch to session pool mode, or avoid prepared statements Migrations fail through PgBeam Advisory locks not supported in transaction mode Run migrations against origin directly Stale data after writes Cache returning old results Use `noCache` annotation or disable cache for that query shape ## Further reading Connection Pooling: Pool modes and sizing guidance Caching: How PgBeam caching works, TTL, and SWR Read Replicas: Replica setup and routing --- # psycopg URL: https://pgbeam.com/docs/psycopg Description: Connect Python applications using psycopg to PgBeam for connection pooling, caching, and global routing. Includes SQLAlchemy integration. Connect your Python application to PgBeam by updating the connection string. This guide covers psycopg 3, psycopg connection pools, and SQLAlchemy integration. ## Setup ## Set the connection string ## Connect with psycopg ## Set up connection pooling (recommended) Use psycopg's built-in pool with a small pool size: ## Pool sizing PgBeam handles upstream connection pooling, so keep your application-side pool small: Deployment type Recommended `max_size` Single process (Gunicorn) 5-10 Multiple workers 2-3 per worker Serverless (Lambda) 1-2 With PgBeam in transaction pool mode, each psycopg connection only holds an upstream connection during active transactions. A small pool handles high concurrency efficiently. ## SQLAlchemy integration psycopg works as the default PostgreSQL driver for SQLAlchemy. Update your engine configuration to point at PgBeam: Set `max_overflow=0` to prevent SQLAlchemy from creating connections beyond the pool size. PgBeam handles overflow at the proxy level. ## Caching ## Automatic caching via cache rules For ORM queries (SQLAlchemy, Django ORM), PgBeam tracks the SQL shapes automatically. Enable caching for specific shapes through Cache Rules in the dashboard. ## SQL annotations for fine-grained control ## Read replicas Route reads to replicas with the `/* @pgbeam:replica */` annotation: Standard ORM queries always go to the primary. For replica routing with SQLAlchemy, use `text()` or raw SQL execution. See Read Replicas for replica setup and routing details. ## Error handling psycopg maps PostgreSQL SQLSTATE codes to specific exception classes: See Error Codes for the full reference. ## Django integration Django uses psycopg as its default PostgreSQL backend. Update `DATABASES` in `settings.py`: ## Migrations Run migrations directly against your origin database: ## Debugging Enable debug mode to see cache and routing details: ## Common issues Issue Cause Fix "too many connections" Pool too large Set `max_size=5` in ConnectionPool `OperationalError` on connect Cold start after inactivity Normal: first connection is slower Stale data after writes Cache returning old results Adjust TTL or use `noCache` annotation ## Further reading Connection Pooling: Pool modes, sizing, and lifecycle Caching: TTL, SWR, cache layers, and cache rules Error Codes: SQLSTATE reference for PgBeam errors --- # Pulumi URL: https://pgbeam.com/docs/pulumi Description: Manage PgBeam projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, self host enrollments, and honeytokens as infrastructure using Pulumi and the @pgbeam/pulumi package. Manage your PgBeam infrastructure as code with Pulumi. The `@pgbeam/pulumi` package provides native Pulumi resources for projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, self host enrollments, and honeytokens. ## Setup ## Install the package ## Configure credentials Set your PgBeam API key via Pulumi config or environment variable: ## Create a project ## Deploy Pulumi creates the PgBeam project and its primary database atomically. The `proxyHost` output gives you the PgBeam proxy endpoint to use in your application connection string. ## Resources **Approval and anomaly rules are not yet managed as code.** Policy profiles and honeytokens are managed resources, so the enforcement rules and the decoys live in your reviewed IaC flow and are covered by drift detection. Approval rules and anomaly rules are not: the API exposes them only as events to review after the fact (approve/reject, ack/resolve), so there is nothing to declare yet. Those two still live outside IaC. ## Project Manages a PgBeam project with a primary database. **Outputs:** `proxyHost`, `queriesPerSecond`, `burstSize`, `maxConnections`, `databaseCount`, `activeConnections`, `createdAt`, `updatedAt`, `primaryDatabaseId` ## Database Manages an upstream database connection within a PgBeam project. **Outputs:** `connectionString`, `createdAt`, `updatedAt` ## Replica Manages a read replica for a PgBeam database. Replicas are immutable; any property change triggers replacement. **Outputs:** `createdAt`, `updatedAt` ## CustomDomain Manages a custom domain for a PgBeam project. CustomDomains are immutable; any property change triggers replacement. **Outputs:** `verified`, `verifiedAt`, `tlsCertExpiry`, `dnsVerificationToken`, `dnsInstructions`, `createdAt`, `updatedAt` ## CacheRule Manages a per-query cache rule. Deletion disables caching (soft-delete). **Outputs:** `queryHash`, `normalizedSql`, `queryType`, `callCount`, `avgLatencyMs`, `p95LatencyMs`, `avgResponseBytes`, `stabilityRate`, `recommendation`, `firstSeenAt`, `lastSeenAt` ## SpendLimit Manages the monthly spend limit for an organization. **Outputs:** `orgId`, `plan`, `billingProvider`, `subscriptionStatus`, `currentPeriodEnd`, `enabled`, `customPricing`, `spendCapped`, `spendCappedAt`, `limits`, `createdAt`, `updatedAt` ## AgentCredential Manages a scoped agent credential (a PgBeam-issued Postgres login plus a hosted MCP token) for an AI agent. The connection string and MCP token are one-time secrets returned only at creation and exposed as sensitive computed outputs; they cannot be retrieved again. To rotate the secrets, taint/replace the resource (or use the rotate endpoint out of band). **Outputs:** `pgUsername`, `authMethod`, `lastUsedAt`, `createdAt`, `updatedAt`, `connectionString`, `mcpUrl`, `mcpToken` ## PolicyProfile Manages a policy profile: a named bundle of agent-gateway enforcement rules (access mode, table allow/deny lists, statement-kind rules, PII masking rules, per-relation row filters, query/egress budgets, write mode, approvals, and migration safety) attached to agent credentials and enforced in the PG wire protocol. Nested-list fields (masking\_rules, row\_filters) and the nested statement\_rules object are expressed as structured config. **Outputs:** `createdAt`, `updatedAt` ## WebhookEndpoint Manages a webhook endpoint that receives project audit and anomaly event deliveries. The signing secret is write-only and never returned by the API. **Outputs:** `createdAt`, `updatedAt` ## SelfHostEnrollment Manages a self-host (BYOC) enrollment: a token a self-hosted proxy uses to authenticate to the control plane's config/audit stream. The token is a one-time secret returned only at creation and exposed as a sensitive computed output; it cannot be retrieved again. To rotate the token, replace the resource. Deletion revokes the enrollment. SelfHostEnrollments are immutable; any property change triggers replacement. **Outputs:** `createdBy`, `createdAt`, `lastSeenAt`, `revokedAt`, `token` ## Honeytoken Manages a honeytoken: a decoy (canary) relation that no legitimate query should ever touch. Any agent statement referencing it is blocked and recorded as a canary\_tripped audit event; the kill action additionally disables the tripping credential via the kill-switch. The relation does not have to exist in the upstream database: enforcement is by name, in the wire protocol, before the statement reaches Postgres. **Outputs:** `createdAt`, `updatedAt` ## Configuration Setting Source Description `pgbeam:apiKey` Pulumi config API key (recommended: use `--secret`) `pgbeam:baseUrl` Pulumi config API base URL (default: `https://api.pgbeam.com`) `PGBEAM_API_KEY` Environment Fallback API key `PGBEAM_API_URL` Environment Fallback base URL Config resolution order: `configure()` call > Pulumi stack config > environment variables. ## Replacement vs update Some property changes trigger resource replacement (delete + create) rather than in-place updates: Resource Replacement triggers Project `orgId`, `cloud`, `selfHosted` Database `projectId` Replica Any property change (immutable) CustomDomain Any property change (immutable) CacheRule `projectId`, `databaseId`, `queryHash` SpendLimit `orgId` AgentCredential `projectId`, `policyProfileId`, `name`, `principalType`, `expiresAt` PolicyProfile `projectId` WebhookEndpoint `projectId` SelfHostEnrollment Any property change (immutable) Honeytoken `projectId` ## Further reading Connection Pooling: pool modes and sizing Caching: query caching and SWR Read Replicas: replica routing Custom Domains: DNS setup and verification API Keys: managing API credentials Plans: plan limits and pricing --- # Query Timeout URL: https://pgbeam.com/docs/query-timeout Description: Set per-database query timeouts to prevent long-running queries from holding connections and exhausting resources. Query timeout lets you set a maximum execution time for queries on a per-database basis. When enabled, PgBeam sends `SET statement_timeout = ` to the upstream database after acquiring a connection, ensuring no single query runs longer than the configured limit. ## How it works The timeout is applied at the database level, not the project level. Each database registered in a project can have its own timeout value. Setting Behavior `0` (default) Disabled: no timeout override, upstream default applies `1` to `300000` (ms) PgBeam sets `statement_timeout` on each upstream connection When a query exceeds the timeout, PostgreSQL cancels it and returns: This is a standard PostgreSQL error. Your application handles it the same way regardless of whether PgBeam or a direct connection set the timeout. ## Configure the timeout Navigate to your project, select a database, and go to **Settings**. Set the **Query timeout** value in milliseconds. ## Choosing a timeout value Workload Suggested timeout Why Web app (API responses) 5,000-15,000 ms Users won't wait longer than a few seconds Background jobs 60,000-300,000 ms Longer queries are expected but should still bound Analytics / reporting 300,000 ms (max) Complex aggregations need more time Mixed (OLTP + occasional report) 30,000 ms Balanced default for most applications If your application already sets `statement_timeout` in its connection initialization, PgBeam's setting will override it for the duration of the pooled connection. The application-level timeout is restored when the connection is returned to the pool and reset with `DISCARD ALL`. ## Interaction with connection pooling In **transaction mode**, `statement_timeout` is set each time PgBeam acquires an upstream connection for a client. When the transaction ends and the connection is returned to the pool, `DISCARD ALL` resets it. In **session mode**, the timeout is set once when the upstream connection is first established for the client session. ## Further reading Connection Pooling: Pool modes and connection lifecycle Error Codes: SQLSTATE reference Troubleshooting: Debug slow queries --- # Quickstart URL: https://pgbeam.com/docs/quickstart Description: Connect an AI agent to your Postgres safely in two minutes. Issue a scoped credential, attach a read-only policy, and watch the audit log. This guide gives an AI agent safe, read-only access to your database through PgBeam. The agent gets a scoped credential and a hosted MCP URL. It never sees your real database credentials, and you can revoke its access with one click. You need a PostgreSQL database reachable from the internet and its connection details (host, port, user, password, database name). Sign up at dash.pgbeam.com with email and password, or with Google, GitHub, or Vercel; new accounts start on a 14-day trial. To use the CLI, create an API key under **Settings > Account > API Keys** (personal) or **Settings > Organization > API Keys** (organization) and authenticate with it (the CLI does not do browser sign-in). ## Add your database Create a project and register your origin database in the dashboard, or use the CLI. `projects create` makes the project and its primary database in one atomic call, so pass the connection details inline: PgBeam stores these credentials and uses them to reach your database upstream. The agent never receives them. To attach more databases later (for example a read replica), use `pgbeam db add` with `--name ` and its own `--username`/`--password`. ## Create a read-only policy A policy profile defines what the agent may do. Create a read-only one and note the `pol_…` id it prints; you'll attach the credential to it next. ## Issue a scoped agent credential Pass the policy id from the previous step to `--policy`: This returns two things the agent can use: See Agent credentials for the full surface. ## Connect the agent over MCP `agents create` already printed a ready-to-paste config for your client (pass `--client claude-desktop`, `cursor`, `vscode`, `cline`, `windsurf`, or `all` to pick the host). For Claude Code it looks like this: Need to regenerate it later (e.g. after rotating the token), or write it straight to the client's config file? Claude Desktop, Cline, and Windsurf keep one config file per machine instead of one per project, so `--write` prints those with their per-OS path rather than overwriting a file that holds your other MCP servers. Claude Desktop also reaches a remote endpoint through an `mcp-remote` bridge. See Hosted MCP for each config and where its file lives. The dashboard credential reveal renders the same blocks for Claude Code, Cursor, and VS Code. The agent now has ten tools: `briefing`, `query`, `validate_sql`, `list_tables`, `describe_table`, `explain`, `schema_catalog`, and `my_permissions`, every call enforced against the policy, plus `search_docs` and `read_doc` for looking up the PgBeam docs. Prefer a connection string? See Connection string. ## Watch the audit log Every statement the agent runs is recorded with its decision, rows, bytes, and latency. Open the **Audit** tab in the dashboard, or: A read-only policy blocks writes and DDL automatically. The blocked statement never reaches your database, and the agent receives an LLM-readable reason. ## What to tighten next The read-only policy is a safe default. Narrow it further as you go: Allowlists: restrict to the exact tables. Masking: hash or redact PII the agent should never read. Budgets: cap queries per window and rows per result. Kill-switch: cut an agent off mid-session. --- # Read-only Enforcement URL: https://pgbeam.com/docs/read-only Description: Block every write and DDL statement for an agent credential. Reads pass, writes are rejected in the wire protocol before they reach your database. Read-only is the safest access mode for an agent. With it, PgBeam allows reads and rejects every `INSERT`, `UPDATE`, `DELETE`, and DDL statement before it reaches your database. The agent receives an LLM-readable reason, so it can adjust instead of failing blind. ## Turn it on A credential's policy is fixed at creation. To move an existing credential to a different policy, rotate or re-issue it against the new profile. In the dashboard, set **Access mode** to **Read-only** on the policy profile. ## What is allowed and blocked Statement Read-only `SELECT` Allowed `WITH … SELECT` (read-only CTE) Allowed `EXPLAIN` of a read Allowed `INSERT` / `UPDATE` / `DELETE` Blocked `CREATE` / `ALTER` / `DROP` / `TRUNCATE` Blocked `COPY` Blocked Data-modifying CTE (`WITH … UPDATE`) Blocked `SELECT … INTO t` (creates a table) Blocked `EXPLAIN ANALYZE` (runs the statement) Blocked `SELECT … INTO t` and `CREATE TABLE t AS SELECT …` are the same statement in Postgres, so both are blocked. `EXPLAIN ANALYZE` runs the statement it is given rather than only planning it, so it is blocked whenever the statement underneath it writes or creates a table. A plain `EXPLAIN` of a read executes nothing and stays allowed. ## What the agent sees A blocked write comes back as a Postgres error (SQLSTATE `42501`): The error is written to be read by an LLM, so an agent can correct its plan and retry within the rules. ## Fails closed A multi-statement batch is rejected if any statement in it would be blocked. Unparseable SQL and unknown statement types are rejected too. This prevents an agent from slipping a write past the parser. Read-only is the right default. When an agent genuinely needs to write, read-write mode with a tight allowlist is one option. Sandbox writes let an agent write freely against an isolated, throwaway branch without touching production, and approvals hold a production write until a human signs off. ## Related Policies Allowlists Audit log --- # Read Replicas URL: https://pgbeam.com/docs/replicas Description: Distribute read load across PostgreSQL replicas with per-query SQL annotations and automatic health management. Read replicas let you distribute read traffic across multiple database instances. Instead of sending every query to a single primary, you can route eligible reads to replicas, reducing load on the primary and improving read throughput for heavy workloads. PgBeam supports two routing modes: **per-query annotations** and **auto read routing**. With annotations, you explicitly mark queries that should go to a replica using a SQL comment. With auto read routing, PgBeam automatically sends all SELECT queries to replicas without annotations. You choose the mode that fits your consistency requirements. ## When to use read replicas Read replicas are a good fit when: Your primary database is CPU or connection constrained by read traffic You have analytics or reporting queries that can tolerate slightly stale data You want to separate OLTP traffic (primary) from heavier read patterns (replica) You are running dashboards or background jobs that do not need real-time data Read replicas are **not** a good fit when: Every read must see the latest committed write (no replication lag tolerance) Your bottleneck is write throughput, not read throughput You have very few distinct queries that would benefit from routing ## Add a replica Register one or more read replicas for a database. Each replica needs its own connection details. PgBeam connects to it independently from the primary. Navigate to your project, select a database, and click **Add Replica**. Enter the replica's connection details: host, port, database name, and SSL mode. You can add multiple replicas. PgBeam distributes annotated reads across all healthy replicas using round-robin. ## Route queries to replicas Annotate individual queries with `/* @pgbeam:replica */` to route them to a replica: PgBeam strips the annotation before forwarding the query, so the upstream database never sees the comment. ## Routing rules Query type Where it goes Read with `@pgbeam:replica` Round-robin across healthy replicas Read without annotation Primary database Write (`INSERT`/`UPDATE`/`DELETE`) Primary database Any query inside a transaction Primary database ## Why annotations are the default Automatic read/write splitting is convenient but introduces a subtle problem: **replication lag**. If your application writes a row and immediately reads it back, an automatic splitter might route the read to a replica that hasn't received the write yet, returning stale or missing data. Annotations are the default because they ensure you make a conscious decision about which queries can tolerate lag. Queries where consistency matters stay on the primary by default. ## Auto read routing For workloads where most reads can tolerate replication lag, you can enable **auto read routing** on a per-database basis. When enabled, PgBeam automatically routes all SELECT queries to replicas without requiring the `@pgbeam:replica` annotation. Navigate to your project, select a database, and go to **Settings**. Enable **Auto read routing**. ## Requirements At least one replica must be configured on the database Disabled by default to preserve backwards compatibility ## What changes with auto read routing Query type Without auto routing With auto routing `SELECT` without annotation Primary database Round-robin across replicas `SELECT` with `@pgbeam:replica` Round-robin across replicas Round-robin across replicas `INSERT` / `UPDATE` / `DELETE` Primary database Primary database Any query inside a transaction Primary database Primary database ## When to use auto read routing Auto read routing is a good fit when: The majority of your reads can tolerate replication lag You want the simplicity of automatic routing without annotating every query Your workload is read-heavy and you want to offload the primary It is **not** a good fit when: Many reads require read-your-writes consistency You need fine-grained control over which queries go to replicas Replication lag is unpredictable and varies significantly With auto read routing enabled, a `SELECT` immediately after an `INSERT` may return stale data if the replica hasn't caught up. For read-after-write consistency, wrap both statements in a transaction. Queries inside transactions always go to the primary. ## ORM and driver examples Most ORMs support raw SQL or template literals where you can include the annotation: ## Combining replicas with caching Replica routing and caching can work together. A query can be both replica-routed and cached: The evaluation order is: PgBeam checks the cache first On a cache miss, the query is routed to a replica (if annotated) or the primary The result is cached for future requests This means cache hits are served from the local data plane without contacting any upstream at all: not the primary and not the replica. ## Testing and debugging Use debug mode to verify which upstream handled each query: The `NOTICE` output reports the cache status for the query: `hit`, `miss`, or a stale hit (with `age`, `ttl`, and `swr` on a hit). A replica-routed read is not cached, so it shows as a `miss`. ## Health checks and failover PgBeam runs background health checks against each replica independently. The health check system is automatic. There is nothing to configure. Event What PgBeam does Replica health check fails Replica is removed from rotation Replica recovers Re-added to rotation after consecutive successes All replicas are unhealthy Annotated reads fall back to the primary database This means replica failures are transparent to your application. A `/* @pgbeam:replica */` query always succeeds. It just falls back to the primary if no healthy replica is available. ## Replication lag considerations PostgreSQL streaming replication is asynchronous by default. This means there is always some delay (typically milliseconds, but potentially seconds under load) between a write on the primary and the same data appearing on a replica. **Queries safe for replica routing:** Product catalogs, blog posts, static content lookups Analytics and reporting queries Search results, recommendations, leaderboards Configuration and feature flag reads **Queries that should stay on the primary:** Reading data immediately after writing it ("read-your-writes") Queries used in transactional flows where consistency is critical Real-time balance checks, inventory counts, or seat availability ## Limitations Without auto read routing enabled, replica routing only applies to queries with the `/* @pgbeam:replica */` annotation. Queries inside transactions always go to the primary, even if annotated or with auto read routing enabled. This prevents split-brain reads within a transaction. All replicas receive equal traffic via round-robin. Weighted routing is not supported. PgBeam does not provision or manage replicas. You create them in your database provider and register them in PgBeam. ## Further reading Caching: Combine replica routing with query caching Routing & Regions: How global routing interacts with replica routing Resilience: Health check details and failover behavior --- # Resilience URL: https://pgbeam.com/docs/resilience Description: How PgBeam keeps database connections reliable with circuit breakers, scale-to-zero, health checks, fail-open caching, and upstream TLS. PgBeam is designed to keep your application connected even when things go wrong upstream. Every resilience feature is automatic. There is nothing to configure or enable. ## Circuit breaker Each project maintains a per-upstream circuit breaker that protects a failing database from being overwhelmed with connection attempts. ## States State Behavior **Closed** Normal operation. All connections flow to the upstream database. **Open** Triggered after 3 consecutive connection failures. New connections are rejected with SQLSTATE `08006`. **Half-open** After a cooldown period, PgBeam sends a single probe connection to test recovery. ## Recovery flow The initial cooldown is 5 seconds. Each failed probe doubles the cooldown, up to a maximum of 60 seconds. A successful probe immediately closes the circuit and restores normal traffic. ## What your application sees When the circuit is open, PgBeam returns: Your application should treat this as a transient failure and retry with backoff. See Error Codes for handling guidance. ## Why circuit breakers matter Without a circuit breaker, a failing database receives a flood of connection attempts from every client. This makes recovery harder: the database has to handle both its existing problem and a thundering herd of reconnections. The circuit breaker gives the upstream breathing room to recover. ## Scale-to-zero Projects with no active connections for 5 minutes enter a **parked** state. This is transparent to your application. The first new connection triggers a cold start that re-initializes the project. ## What gets suspended Resource Parked behavior Connection pools Drained and released Health checks Paused Rate limiters Reset Cache entries Local cache evicted; shared regional cache retained Project config Stays in memory for fast resume ## Cold start latency The cold start adds latency to the first connection. It includes: Re-initializing the connection pool Dialing the first upstream connection Resuming health checks Subsequent connections within the same session are unaffected. Scale-to-zero only applies to the data plane resources. Your project configuration, databases, cache rules, and settings remain intact in the control plane at all times. ## Health checks PgBeam runs background health checks against every configured upstream database and read replica. Health checks are separate from application traffic. They run on their own schedule regardless of query volume. ## Upstream database health The data plane periodically dials a TCP connection to the upstream database to confirm it is reachable. If the check fails, PgBeam marks the upstream as degraded and may open the circuit breaker after repeated failures. ## Replica health Read replicas are checked independently. An unhealthy replica is removed from the round-robin rotation automatically. When it recovers, it is re-added without manual intervention. Event Action Replica check fails Removed from rotation. Traffic goes to remaining healthy replicas or falls back to primary. Replica recovers Re-added to rotation after consecutive successful checks. All replicas fail Annotated replica queries fall back to the primary database. ## Fail-open caching PgBeam's caching layer is designed to degrade gracefully. If the cache infrastructure has issues, queries fall through to the upstream database instead of failing. Cache layer Scope Failure behavior **L1** Per-process Process-local; failure is extremely rare **L2** Shared per region On failure, queries bypass L2 and go to upstream This means a shared cache outage results in higher upstream load (cache misses) but never in dropped queries. Your application continues to work. It just loses the caching benefit temporarily. ## Upstream TLS and SNI PgBeam connects to upstream databases over TLS and sets the TLS server name (SNI) to the upstream hostname. This is required for managed database providers that use SNI-based routing to identify the correct tenant: **Neon**: Uses SNI to route to the correct compute endpoint **Supabase**: Uses SNI for project-level routing **PlanetScale** (MySQL proxy): Similar SNI routing pattern The default SSL mode is `verify-full`, which validates the upstream certificate against the system CA bundle. Only relax this if your provider does not issue certificates from a publicly trusted CA. ## Connection reset When a connection is returned to the pool and PgBeam detects that session state was modified (via `SET`, `PREPARE`, `CREATE TEMP TABLE`, etc.), it sends `DISCARD ALL` to reset all session state: Session variables (`SET` parameters) Prepared statements Temporary tables Advisory locks Notification listeners Connections in an error state or mid-transaction are closed instead of being returned to the pool. This prevents a broken connection from being handed to the next client. ## What PgBeam does not do To set expectations clearly: **No automatic failover between primary databases.** PgBeam proxies to the upstream you configure. If you need primary failover, configure it at the database level (RDS Multi-AZ, Cloud SQL HA, etc.) and point PgBeam at the failover endpoint. **No cross-region cache replication.** Each region maintains its own cache. This is deliberate: cross-region coherence would add latency to every read. **No query rewriting or retry.** If a query fails at the upstream, PgBeam returns the error to the client as-is. It does not retry failed queries. --- # Routing & Regions URL: https://pgbeam.com/docs/routing Description: How PgBeam routes connections across global regions and caches reads close to the client, and what happens when things fail. PgBeam is a globally distributed proxy. When a client connects, it is routed to the nearest PgBeam region automatically. From there, PgBeam handles everything: TLS termination, project lookup, connection pooling, caching, and the upstream query. You do not choose a region when creating a project. Every project is accessible from every region. PgBeam picks the best path to the upstream database for you. ## Regions PgBeam runs the proxy on a global anycast network with a presence in metros worldwide. A single anycast address (`proxy.pgbeam.app`) routes each connection to the nearest metro automatically: Location Metro Ashburn, US `iad` San Jose, US `sjc` Dallas, US `dfw` Toronto, CA `yyz` São Paulo, BR `gru` London, GB `lhr` Frankfurt, DE `fra` Amsterdam, NL `ams` Stockholm, SE `arn` Tokyo, JP `nrt` Singapore `sin` Sydney, AU `syd` Anycast steers each client to the closest metro, so you do not pick one. The metro set can change as we add capacity. ## How a connection is routed Every client connection follows the same lifecycle: ## DNS resolution The client resolves `abc.proxy.pgbeam.app`. The connection is directed to the nearest PgBeam region automatically, based on the client's location. No application-level routing is involved. ## TLS handshake The client connects over TLS. PgBeam uses **SNI (Server Name Indication)** to extract the project identifier from the hostname during the TLS handshake, before any PostgreSQL protocol traffic is exchanged. ## Project lookup PgBeam resolves the full project configuration: upstream host, pool mode, cache settings, connection limits, and rate limits. Project configs are cached locally, so this lookup is fast after the first connection. ## Cache check (for queries) When caching is enabled, each incoming query is checked against the local cache **before** any upstream communication. Cache hits are returned directly, with zero upstream latency. ## Pool acquire and upstream auth PgBeam acquires an upstream connection from the per-project pool (or dials a new one). Your credentials are forwarded to the upstream database for authentication. PgBeam does not store user passwords. ## Query execution The query runs against the upstream database and results flow back to the client. When caching is enabled, eligible read results are stored in the local cache for future requests. ## Pool release When the client disconnects (or the transaction ends, in transaction mode), the upstream connection is reset with `DISCARD ALL` and returned to the pool. ## Routing across regions When your database is in a different region from the connecting client, PgBeam keeps connection pools close to the database while still serving clients from the nearest region. Clients connect to the region nearest them; PgBeam routes the query to the region nearest your database, where the pool lives. Keeping pools close to the database has two advantages: **Connection stability.** Long-lived upstream connections stay on the shortest, most stable network path to the database. **Pool efficiency.** Connections from every region share the same pool, maximizing connection reuse. ## Cache and routing interaction The cache check always happens in the region nearest the client, before any cross-region hop. This is the key performance benefit: **Cache hit:** Served from the nearest region. No cross-region hop. No upstream query. The client gets the result with local latency only. **Cache miss:** The query is routed to the region nearest the database, executed against the upstream, and the result is cached near the client for future requests. This means a client in Singapore querying a database in Virginia can get sub-millisecond response times for cached queries, despite the database being halfway around the world. ## Failover If the path to the database's region is unavailable (network partition, region outage), PgBeam falls back to connecting to the upstream database directly from the client's region. This is less efficient (no pool sharing across regions) but maintains connectivity. Failover is automatic. Your application does not need to handle it: the connection works transparently either way. ## Verify the serving region On connect, PgBeam sends the serving region as a `pgbeam.region` startup parameter (a Postgres `ParameterStatus` message). Read it from whatever your client exposes for connection parameters. With `node-postgres` / the Neon driver: libpq-based clients expose the same value through `PQparameterStatus(conn, "pgbeam.region")`. A `SHOW pgbeam.region` command that returns the region in any SQL client is planned but not available yet, so do not rely on it: `pgbeam.region` is not a real Postgres setting, so today the statement is forwarded upstream and errors. Read the `pgbeam.region` startup parameter instead. ## Read replica routing PgBeam supports two modes for routing queries to read replicas: ## Per-query annotations (default) Annotate queries with `/* @pgbeam:replica */` to send them to a replica: ## Auto read routing When enabled on a database with replicas configured, PgBeam automatically routes all SELECT queries to replicas without requiring annotations. Enable it per database in the dashboard, API, or CLI. Query type Annotation mode Auto read routing mode Read with `@pgbeam:replica` Round-robin across replicas Round-robin across replicas Read without annotation Primary database Round-robin across replicas Write (`INSERT`/`UPDATE`/`DELETE`) Primary database Primary database Inside transaction Primary database Primary database PgBeam strips annotations before forwarding. See Read Replicas for setup instructions, ORM examples, and health check details. ## Latency characteristics Understanding where latency comes from helps you optimize your setup: Scenario Typical latency What determines it Cache hit near client \< 1ms L1/L2 cache lookup Cache miss, database in same region 1-5ms Upstream query time Cache miss, database in another region 30-150ms Inter-region RTT + query Cold start (project was parked) Varies Pool re-init + first dial The biggest latency win comes from caching. A cache hit eliminates both the upstream query and any cross-region hop. ## Failure scenarios Failure PgBeam behavior A PgBeam region goes down Clients are automatically routed to the next nearest region Path to the database's region fails Fallback to a direct connection from the client's region Upstream database unreachable Circuit breaker opens after 3 failures Shared cache goes down Queries fall through to upstream (fail-open) All replicas unhealthy Replica-annotated queries fall back to primary See Resilience for detailed circuit breaker behavior and recovery. ## Further reading Connection Pooling: Pool modes, sizing, and connection lifecycle Caching: How cache lookup interacts with routing Read Replicas: Opt-in replica routing with SQL annotations Resilience: Circuit breakers, health checks, and failover --- # Row-level Policies URL: https://pgbeam.com/docs/row-level-policies Description: Scope a credential to a slice of a table with a WHERE predicate. PgBeam appends the filter to every statement so an agent or analyst only ever sees its own rows. A row-level policy attaches a `WHERE` predicate to a credential. PgBeam appends the predicate to every statement that touches the named table, so the credential reads and writes only the rows that match. Use it to scope one agent to a single tenant, an analyst to their region, or a support bot to a single customer's records, without changing your schema or your application. Row filters apply to agent credentials and to human credentials. The predicate follows the credential, not the user, so the same query returns a different slice of the table depending on who runs it. ## Define a row filter A policy carries a list of row filters, one per table. Each filter is a `WHERE` expression evaluated against that table's columns. Open the policy profile, go to **Row filters**, pick a table, and write the predicate. The dashboard validates it against the table's columns before it saves. ## How the filter is applied PgBeam parses each statement, finds the references to a filtered table, and combines your predicate with the statement's own `WHERE` clause using `AND`. The credential cannot widen its own scope: a query that asks for `tenant_id = 99` returns nothing, because the appended `tenant_id = 42` rules it out. Your predicate's column references are bound to the filtered table before the predicate is appended: PgBeam qualifies them with the query's alias for that table, or with the table name when the query gave it no alias. That is what keeps the filter attached to the right relation in a join, where another table may carry a column of the same name. Statement Effective query `SELECT * FROM orders` `SELECT * FROM orders WHERE orders.tenant_id = 42` `SELECT * FROM orders WHERE total > 100` `SELECT * FROM orders WHERE total > 100 AND orders.tenant_id = 42` `SELECT * FROM orders o JOIN customers c ON c.id = o.cust` `SELECT * FROM orders o JOIN customers c ON c.id = o.cust WHERE o.tenant_id = 42` `SELECT * FROM orders a JOIN orders b ON a.parent = b.id` `... WHERE a.tenant_id = 42 AND b.tenant_id = 42` `UPDATE orders SET status = 'x'` (read-write) `UPDATE orders SET status = 'x' WHERE orders.tenant_id = 42` `DELETE FROM orders WHERE id = 7` (read-write) `DELETE FROM orders WHERE id = 7 AND orders.tenant_id = 42` In read-write mode the filter scopes writes too: an `UPDATE` or `DELETE` can only touch rows the credential can already see. A row outside the filter is invisible, so it cannot be modified. ## Fails closed The predicate is parsed and bound against the table's real columns when you save the policy, not at query time. A predicate that references an unknown column is rejected at save. A statement that PgBeam cannot rewrite safely (an unparseable query, a construct where the filter cannot be placed) is blocked rather than forwarded unfiltered. A row filter is a SQL expression that executes upstream. Keep predicates simple and indexed (`tenant_id = 42`, `region = 'eu'`). Reference only columns on the filtered table. A sub-select inside a predicate keeps its own scope, so its column references are left as you wrote them. PgBeam validates the predicate against the schema, but it does not rewrite a slow predicate into a fast one. ## Combine with the rest of the policy Row filters stack with the other policy rules. A credential can be read-only, allowlisted to two tables, masked on a column, budgeted, and row-filtered, all at once. PgBeam applies the allowlist first (can the credential touch this table at all), then the row filter (which rows), then masking (which column values leave the wire). ## Related Policies: the bundle a row filter lives in. Allowlists: which tables a credential may touch. PII masking: redact column values the credential may read. Passthrough policies: apply row filters to human and application connections. --- # Safe Migrations URL: https://pgbeam.com/docs/safe-migrations Description: PgBeam lints DDL for the changes that lock tables or lose data. Table rewrites, ACCESS EXCLUSIVE locks, missing CONCURRENTLY, unsafe drops and type changes, NOT NULL without a default. Warn or block. A generated migration is one of the most dangerous things an agent can run. The syntax is valid, the statement succeeds, and it takes an `ACCESS EXCLUSIVE` lock on a hot table for the duration of a full rewrite. Safe migrations catch that before it reaches your database. PgBeam parses every DDL statement, checks it against a set of known-dangerous patterns, and either warns or blocks based on your policy. This runs for agent credentials and human credentials. A platform engineer's hand-written `ALTER TABLE` gets the same lint as an agent's generated one. ## What the linter flags Pattern Why it is risky Table rewrite Rewrites every row and holds a lock for the whole operation. `ACCESS EXCLUSIVE` lock on a hot table Blocks all reads and writes to the table while it runs. Missing `CONCURRENTLY` `CREATE INDEX` without `CONCURRENTLY` locks the table for writes. Unsafe drop `DROP COLUMN` / `DROP TABLE` destroys data with no undo. Unsafe type change `ALTER COLUMN ... TYPE` that forces a rewrite or can lose data. `NOT NULL` without a default Adding `NOT NULL` to an existing column rewrites and can fail mid-flight. ## Lint a migration before you run it `migrations:lint` checks a DDL script and returns findings without touching your database. Use it in CI, in a pre-commit hook, or as a tool the agent calls before it proposes a change. From the CLI: ## Warn or block at the wire The lint also runs inline when an agent or analyst issues DDL through PgBeam. Set the policy's enforcement level for migrations: **Warn**: the statement runs, the finding is recorded, and a `migration_flagged` event fires. Use this once you trust the workflow and want a record. **Block**: a statement with a finding at or above the threshold is refused on the wire, with the rule and suggestion in the error so the agent can fix it. Blocking is the strict end. To let risky DDL through under supervision, hold it for approval. To let an agent iterate on DDL with no risk at all, point it at a branch, where a table rewrite affects only the throwaway copy. ## Related Sandbox writes: run DDL against a throwaway branch. Approvals: hold flagged DDL for human sign-off. Audit export: forward `migration_flagged` events. Policies: set the migration enforcement level. --- # Sandbox Writes URL: https://pgbeam.com/docs/sandbox-writes Description: Let an agent write freely against an instant, isolated branch of your database, or run every write in always-rollback dry-run mode. Production is never touched. Read-only enforcement keeps an agent off your data by refusing every write. That is the right default. It is also too strict when the agent's job is to write: a migration, a backfill, a generated `UPDATE` you want to test before you trust it. Sandbox writes are the safe-write counterpart. The agent writes for real, just not against production. PgBeam offers two modes: an instant branch the agent can write to and you can inspect, and an always-rollback mode where writes execute and then disappear. ## Instant branches A branch is an isolated copy of your database. It starts from production's current state, spins up in seconds, and costs nothing while idle. The agent connects with its scoped credential or the hosted MCP endpoint exactly as before. The only difference is the target: a branch credential routes the session to a fresh branch instead of production. **Isolated**: writes land on the branch, never on production. **Instant**: the branch is ready in seconds, on demand. **Lightweight**: a branch only stores what it changes, so it is cheap to create and cheap to keep. **Scale-to-zero**: an idle branch costs nothing; a discarded branch is gone. On the policy profile, set **Write target** to **Branch**. Live branches show up on the **Branches** tab with the statements that ran against them and a summary of what changed. Discard a branch there when you are done. ## The workflow Attach a sandbox policy to an agent credential, targeting a branch. The agent opens a session. PgBeam provisions a branch from the database's current state and pins the session to it. The agent writes freely: `INSERT`, `UPDATE`, `DELETE`, and DDL, all against the branch. You inspect what changed in the dashboard: which statements ran and the full audit trail for the session. You discard the branch. Nothing merges back to production unless you explicitly promote it. ## Always-rollback dry-run When you want to see whether a write *would* work without keeping anything, always-rollback mode runs each of the agent's transactions and then rolls it back. The statement executes against production, so the agent gets real errors, real row counts, and a real plan, but the transaction never commits. Nothing persists. Use dry-run to validate a generated `UPDATE` against live data and constraints without a branch. Use a branch when the agent needs its writes to stick around for a multi-step task or for you to review. Situation Use Agent should only read Read-only Agent should write, but never persist Always-rollback dry-run (this page) Agent needs a writable copy for a multi-step task Instant branch (this page) A human should sign off before a write lands Approvals ## How it works A branch is a real Postgres endpoint that starts from your database's current state and only stores what the session changes, so it stays cheap to spin up and keep around. The agent's session reaches it through the same wire-protocol proxy that enforces every other policy, so audit capture, budgets, masking, and row filters still apply on the branch. Read-only enforcement is relaxed for the branch and only the branch, because there is nothing on it worth protecting. Always-rollback mode wraps the agent's work in a transaction the proxy refuses to commit. The database does the real work, then the proxy issues the rollback, so the agent observes the true outcome while production stays untouched. Either way the core guarantee holds: an agent with a sandbox credential cannot change production data. The worst case is a discarded branch. ## Related Read-only enforcement: block writes entirely. Approvals: hold a production write for human sign-off. Policies: how the sandbox target binds to a credential. Audit log: every statement, branch or production. --- # Sandbox URL: https://pgbeam.com/docs/sandbox Description: Sandbox writes have shipped. This page has moved to Sandbox Writes. Sandbox writes are available now. This page has moved. See Sandbox writes for instant branches and always-rollback dry-run mode. --- # PII Auto-Detection URL: https://pgbeam.com/docs/scan-pii Description: Scan a database for likely-PII columns and get ranked masking suggestions. Review them in the dashboard and add the ones you want in one click. PII auto-detection scans a database and tells you which columns look like personal data, with a recommended masking rule for each one. It connects read-only, reads the schema, samples column values, and returns ranked suggestions. Nothing is applied automatically: you review the suggestions and add the ones you want to a policy profile. Use it when you are setting up masking on a database you do not know column by column, or to catch new sensitive columns after a schema change. It finds the `email`, `ssn`, and `card_number` columns for you so you do not have to grep the schema by hand. ## Run a scan Open a policy profile, go to the **Masking** section, and click **Scan for PII**. Pick the database to scan and click **Run scan**. PgBeam lists the columns it flagged; review them and add the ones you want (see Review and apply below). A project's **Schema** page runs the same scan from the other direction: click **Scan for PII** there and every flagged column that no masking rule covers is marked as you browse (see While browsing the schema). There is no CLI command for the scan. It runs from the dashboard, the REST API, or the SDKs. ## What the scan returns The scan reports how much it inspected and a list of ranked suggestions, highest confidence first: Field Description `scanned_tables` Number of tables inspected. `scanned_columns` Number of columns inspected. `suggestions` Ranked masking suggestions, highest confidence first. Empty if none found. `truncated` `true` when the scan stopped early at the column limit. `error` Present when the scan could not connect or read the schema. Each suggestion carries the column location, the kind of PII detected, a recommended mask kind, a confidence score, and the reasons behind it: Field Description `schema` Schema the column belongs to (for example `public`). `table` Table the column belongs to. `column` The detected column. `data_type` PostgreSQL data type of the column. `pii_type` The kind of PII detected (see the table below). `mask_kind` The recommended mask kind: `redact`, `null`, or `hash`. `confidence` Score in `[0, 1]`. Combines the column-name signal and the sampled-value signal. `reasons` Human-readable explanations for why the column was flagged. `sample_match_count` Number of sampled values that matched the PII pattern. `sample_size` Number of non-null values sampled from the column. ## How detection works Detection combines two signals per column: **Name signal**: the column and table names are matched against curated keyword and regex patterns for each PII type (for example a column named `email` or `phone_number`). **Value signal**: for columns that show a name signal, the scanner samples up to 20 non-null values and matches them against value-shape patterns (for example an email or SSN shape). A high match ratio strengthens the score. The two signals fuse into a single confidence score in `[0, 1]`, and a column is only suggested when it clears the detection floor. The scan runs read-only and samples a small number of values per column, so it does not read your whole table. A match ratio of zero lowers the score only where the value shape covers essentially every form its type takes, so a column named `ip` holding `intellectual property` tags is dropped. Some shapes recognize only part of their type: `api_secret` is a list of known token prefixes, `bank_account` is IBAN, and `passport` is a short uppercase code. A bcrypt digest, a US routing number and a SWIFT code are all exactly what their column names say and match none of those, so for these types the name signal stands on its own and the column is still suggested. Where the column's own name points at a type, that type wins over one only its values suggest: `routing_number` comes back as `bank_account`, not as a `phone` its nine digits also fit. ## PII types and recommended masks Each PII type maps to a recommended mask kind. Identifiers you may still want to join or group on get `hash`; highly sensitive values get `null`; free-text personal data gets `redact`. `pii_type` Recommended `mask_kind` `email` `hash` `ip_address` `hash` `phone` `redact` `full_name` `redact` `street_address` `redact` `date_of_birth` `redact` `ssn` `null` `credit_card` `null` `bank_account` `null` `national_id` `null` `passport` `null` `api_secret` `null` The recommendation is a starting point, not a rule. You can change the mask kind on any column before or after you add it. ## Review and apply In the dashboard, the scan result lists one row per suggested column with a checkbox. High-confidence suggestions (confidence of `0.65` or higher) are pre-selected, but every suggestion is yours to review. Toggle the rows you want, then click the add button to write them into the policy profile's masking rules. Non-`public` schemas are qualified as `schema.table` so the rule is unambiguous. Suggestions are advisory: nothing changes on the profile until you add them. Once added, the rules behave like any masking rule you wrote by hand. See PII masking for how each mask kind renders on the wire. ## While browsing the schema The project's **Schema** page normally reports a column as PII when a masking rule covers it, because a rule is the only thing that changes what an agent receives. That leaves one gap: a column that looks like personal data and that nobody has written a rule for reads as plain `Visible`. Click **Scan for PII** on that page to close it. The scan runs against the database you are browsing and the page then marks every flagged column no rule covers with a **Likely PII** badge, hover it for the detected type, the confidence, and the suggested mask kind. A **Likely PII** lens appears next to the column filters and narrows the table to those columns, and each table in the list carries its own count. A flagged column that a rule already masks gets no badge, because there is nothing to act on. The scan is opt-in per database and per visit: it connects to your database and samples values, so the page never runs it on load. Nothing on the Schema page writes a masking rule; the link in the scan summary takes you to the policy profile where you add them. ## Related PII masking: how masked columns are rendered for agents. Policies: where masking rules live. Allowlists: allow a column so an agent can join on it, then mask it so the agent never reads the raw value. --- # Schema annotations URL: https://pgbeam.com/docs/schema-annotations Description: Attach human-written descriptions to your tables and columns and surface them to connected agents through the MCP schema catalog, so an agent gets curated context instead of guessing from names alone. An agent reads your schema through the MCP `schema_catalog` and `describe_table` tools. By default the description it sees for a table or column is the DB-native comment (`COMMENT ON`, exposed as `pg_description`). Many databases have none, or have terse ones written for humans who already know the domain. A schema annotation is a description you write for a specific table or column. When one exists, PgBeam surfaces it in the catalog in place of the DB-native comment, so the agent gets your curated wording. When none exists, the catalog falls back to the DB comment exactly as before. Annotations never change what data the agent can read: policy, masking, allowlists, and budgets are unchanged. ## Precedence For each table and column the catalog picks the description in this order: A schema-qualified annotation for that exact relation (for example `public.users`). An unqualified annotation for the same table or column name (schema omitted). The DB-native comment (`obj_description` / `col_description`). The first one present wins. A qualified annotation always beats an unqualified one for the same relation. ## Attach an annotation Annotations are keyed by `(schema_name, table_name, column_name)`. Omit `column_name` to describe the table itself. Omit `schema_name` to match the unqualified form. A `PUT` with an existing key replaces that annotation. From the CLI, against the linked project: Or over HTTP. Describe a table: Describe a column: ## List and delete From the CLI: `annotations list` prints the key and the description; pass `--json` for the full records, including ids and timestamps. `annotations delete` prompts before removing, and `--yes` skips the prompt for scripts and CI. Over HTTP, list every annotation for a project (cursor-paginated): Delete one by its key. Pass the same `table_name`, plus `schema_name` and `column_name` when they were set: ## How it reaches the agent Annotations are project configuration, streamed to the edge proxies on the same channel as your policies and honeytokens. A change propagates within seconds, so the next `schema_catalog` call reflects it. The proxy applies the annotation after policy filtering, so an annotation on a table the credential cannot see is never surfaced. ## Notes Annotation names are matched case-insensitively, using the same normalization as the relation allowlist. Writing an annotation needs the `schema_annotation:write` permission (held by owners, admins, security admins, and policy authors). Reading needs `schema_annotation:read`. The CLI commands act on the linked project. Use `--project` to target another one without switching links. Annotations are editable in the dashboard, on a project's **Schema** page under Policy and Safety. It lists the tables and columns the project can see, shows which columns a masking rule covers and with which mask kind, and lets you write or remove a description inline. The API stays available for scripted use. The same page can run a PII scan to mark the likely-PII columns no rule masks. --- # SCRAM-SHA-256 Auth URL: https://pgbeam.com/docs/scram-auth Description: Authenticate credentials with SCRAM-SHA-256 so the password never crosses the wire. Cleartext-over-TLS stays available as a fallback for clients that need it. PgBeam authenticates agent and human credentials with SCRAM-SHA-256. The password is never sent over the connection: the client and PgBeam each prove knowledge of it through a challenge-response exchange, and PgBeam stores only a verifier, not the password itself. This is the same mechanism modern Postgres uses by default, so every current driver already speaks it. Cleartext-over-TLS remains available as a fallback for older clients that cannot do SCRAM. TLS is mandatory on every credential either way. ## Connect with SCRAM Nothing special is required on the client. Any PostgreSQL client that supports SCRAM-SHA-256 (libpq 10+, and every driver built on it) negotiates it automatically. Connect with the scoped credential as usual: PgBeam advertises SCRAM-SHA-256 in the authentication handshake. The client and PgBeam exchange the SCRAM messages, and the connection is authenticated without the password ever appearing on the wire. You can confirm the negotiated method: ## How it works PgBeam terminates authentication itself. It verifies the credential against a stored SCRAM verifier, then opens the upstream connection with your project's real database credentials. The agent or analyst never sees the upstream credentials, and with SCRAM their own password never travels in cleartext either. The client opens a TLS connection. PgBeam routes it by SNI and offers SCRAM-SHA-256. The client and PgBeam run the SCRAM challenge-response. Each proves it knows the password without sending it. On success, PgBeam acquires an upstream connection using the project's stored credentials and relays the session under the credential's policy. ## Cleartext fallback Some clients and embedded drivers do not implement SCRAM. For those, PgBeam accepts a cleartext password, which is safe only because the connection is already inside mandatory TLS, the same posture connection poolers have shipped for years. SCRAM is the default and the better choice: prefer it whenever your client supports it. SCRAM applies to every PgBeam-issued credential, agent or human. The hosted MCP endpoint uses a bearer token instead of a SQL password, so SCRAM does not apply there. ## Related Agent credentials: how a credential is issued. Connection string: connect a driver or ORM. Policies: what a credential is allowed to do once connected. --- # Self-hosted data plane (BYOC) URL: https://pgbeam.com/docs/self-hosted Description: Run the PgBeam proxy inside your own VPC or cluster so the agent connection and audit stream never leave your network, while the control plane, policy engine, and dashboard stay hosted by PgBeam. The self-hosted (BYOC, "bring your own cloud") data plane runs the same PgBeam proxy image inside your own network. Queries from your agents flow through a proxy you operate; the proxy only dials home to the PgBeam control plane over gRPC to fetch project config and to ship the audit trail back. Your database credentials and query traffic stay in your VPC. This is a Scale and enterprise capability. It sells the compliance story: your data plane, our policy engine. ## What stays where Component Runs where Proxy (PG wire, policy, cache) Your VPC/cluster Query traffic + DB credentials Your VPC/cluster Control plane (config, billing) PgBeam (hosted) Dashboard, policy authoring PgBeam (hosted) Audit trail Shipped to PgBeam over gRPC The proxy enforces every policy (read-only, allowlists, masking, budgets, approvals, kill-switch) locally in the PG wire protocol. It receives that policy from the control plane over the config stream, the same mechanism the hosted data plane uses. ## How enrollment works A self-hosted proxy authenticates to the control plane with a self-host enrollment token. The token: Is issued once per enrollment and shown a single time. Only its SHA-256 hash is stored. Scopes the proxy to your organization. A self-hosted proxy receives config for your projects only, never another tenant's, and never the PgBeam platform TLS key. Is gated on entitlement. If your organization is not on a self-host-capable plan (Scale or enterprise), the connection is rejected. Can expire, be rotated, and be revoked. All three take effect immediately, including for proxies that are already connected. See the token lifecycle below. Because the proxy runs in your network, you provide its TLS certificate for your proxy domain. The platform wildcard certificate is never streamed to a self-hosted proxy. ## Issue an enrollment token Create an enrollment for your organization (owner or admin): `expires_at` is optional; omit it for a token that never expires. Setting it gives the token a hard TTL, which keeps the blast radius of a leak small. The response includes the plaintext token once: Store the `token` securely; it cannot be retrieved again. List enrollments with `GET` on the same path. ## Token lifecycle Treat an enrollment token like any other production secret, and use expiry and rotation to limit how long a leaked token stays useful. **Expiry**: an expired token is rejected fail-closed at the control plane's gRPC auth gate the instant its `expires_at` passes. Expiry is visible in the list endpoint and the dashboard. **Rotation**: `POST /v1/organizations/{org_id}/self-host-enrollments/{enrollment_id}/rotate` mints a new token for the same enrollment (same id, metadata, and expiry) and returns it once. The swap is atomic: the old token stops authenticating new connections the moment the call returns. Update the proxy's secret (`controlPlane.enrollmentToken` in Helm, `PGBEAM_ENROLLMENT_TOKEN` in compose) and restart or roll the proxy to pick up the new token. **Revocation**: `DELETE .../self-host-enrollments/{enrollment_id}` cuts the enrollment off permanently. Revoked enrollments cannot be rotated; issue a new enrollment instead. Expiry, rotation, and revocation stop new gRPC connections and also terminate the streams a connected proxy already holds. On revoke or rotate, the control plane closes the proxy's live streams the moment the change commits; a stream opened before an expiry instant is closed when that instant passes. The proxy sees a `permission_denied` status naming the enrollment and the reason in its logs, then reconnects with backoff and fails auth until it presents a currently valid token. Rotate first, roll the proxy with the new token, and the old token is dead from the moment of rotation; there is no shared-secret overlap window to manage. ## Mark a project self-hosted Set `self_hosted` when creating a project so the control plane treats its data plane as customer-operated and does not provision hosted infrastructure for it: ## Run the proxy Packaging for both Kubernetes and Docker Compose lives in `deploy/byoc/`. ## Helm ## Docker Compose ## Connect your agents Route clients through the proxy using TLS SNI, exactly as with the hosted data plane, but against your proxy domain: The subdomain identifies the project. The proxy resolves it against the config streamed from the control plane. ## Configuration reference The proxy is configured entirely with environment variables. The most relevant for BYOC: Variable Purpose `AGENT_API_URL` Control-plane gRPC URL to dial home to `GRPC_AUTH_TOKEN` Self-host enrollment token (pbh\_...) `AGENT_REGION` Region label reported to the control plane `AGENT_INSTANCE` Unique instance id for this proxy `PROXY_DOMAIN` Base domain for TLS SNI project routing `TLS_CERT_FILE` Path to your proxy TLS certificate `TLS_KEY_FILE` Path to your proxy TLS private key `SERVERLESS_ADDR` Listen address for the Neon-compatible HTTP/WS + MCP endpoint `CACHE_ENABLED` Enable query caching (off by default) ## Limits and follow-ups Config, audit, and hostname self-heal are scoped to the enrolling org. Metrics and insights reporting from a self-hosted proxy are trusted at the org level; fine-grained per-project scoping of those aggregate reports is a planned follow-up. --- # Serverless Driver URL: https://pgbeam.com/docs/serverless Description: Use @neondatabase/serverless to connect from edge runtimes and serverless functions through PgBeam with HTTP or WebSocket transports. Connect from edge runtimes and serverless functions using the `@neondatabase/serverless` driver. PgBeam supports both the HTTP query endpoint and the WebSocket wire protocol. Your `neon()` / `Pool` call sites and every query stay exactly as they are. Changing the connection-string host is **not** enough on its own. By default `@neondatabase/serverless` derives its endpoint by rewriting the host: it replaces the first label with `api.`, so `abc.proxy.pgbeam.app` would resolve to `https://api.proxy.pgbeam.app/sql`, dropping the `abc` subdomain PgBeam needs to route your project. Point the driver at PgBeam once, globally, with `neonConfig` before any query runs: These two lines are the only addition. Your query call sites do not change. (On Neon's own `*.neon.tech` hosts the defaults work; PgBeam needs the override because its hostnames are not `*.neon.tech`.) ## Setup ## Install the package For Node.js environments using WebSocket transport, also install `ws`: ## Point the driver at PgBeam Set `neonConfig` once, before any query runs (see the warning above for why this is required). In Node.js, also set the WebSocket constructor. ## HTTP transport: `neon()` tagged template Best for one-shot queries from edge/serverless functions. Each call is a single HTTP request. No persistent connection required. ## WebSocket transport: `Pool` / `Client` Best for interactive transactions or session-level features. Uses the PostgreSQL wire protocol over WebSocket. With the driver's default configuration, the WebSocket `Pool` / `Client` connection **hangs** against PgBeam. PgBeam authenticates with SCRAM, and the driver's default `pipelineConnect: "password"` optimistically pipelines a cleartext password before it reads the server's auth challenge, so the SCRAM handshake never completes. Set `neonConfig.pipelineConnect = false` (already in the `neon-config.ts` above) so the driver waits for the challenge and completes SCRAM. The HTTP `neon()` path is unaffected; if you only need one-shot queries, it works with just `fetchEndpoint` set. ## Run a test query If this returns results, the serverless driver is connected through PgBeam. ## HTTP vs WebSocket HTTP (`neon()`) WebSocket (`Pool` / `Client`) **Best for** One-shot queries, edge functions Transactions, session features **Connection** Stateless HTTP request Persistent WebSocket **Cold start** None WebSocket handshake + TLS **Transactions** `sql.transaction([...])` `BEGIN` / `COMMIT` via client **Pipelining** Automatic (batched in one request) PostgreSQL wire protocol **Max payload** \~10 MB response Unlimited streaming ## Edge runtime compatibility The serverless driver works in any runtime with `fetch` (for HTTP) or `WebSocket` (for WS): Runtime HTTP WebSocket Notes Vercel Edge Functions Yes Yes Built-in WebSocket support Cloudflare Workers Yes Yes Built-in WebSocket support Deno Deploy Yes Yes Built-in WebSocket support Bun Yes Yes Built-in WebSocket support Node.js Yes Yes Requires `ws` package ## Drizzle ORM integration Use the serverless driver adapters with Drizzle for type-safe queries: The same `neonConfig` setup applies. Drizzle wraps the Neon driver, so once the endpoint is pointed at PgBeam, your Drizzle schema and queries are unchanged. ## Transactions Use `sql.transaction()` to run multiple statements in a single HTTP request: Use standard `BEGIN` / `COMMIT` with a dedicated client: ## Data type notes PgBeam matches the `@neondatabase/serverless` type contract over the HTTP endpoint. In particular, `bigint` (`int8`), `numeric`, and `money` are returned as **strings**, not numbers: a JavaScript `Number` cannot represent integers above 2^53 or arbitrary-precision decimals without silent loss. Wrap them with `BigInt(...)` or a decimal library as needed. `json` / `jsonb` are parsed into objects, and arrays into JS arrays, exactly as the Neon driver does. ## Caching and replicas SQL annotations work the same with the serverless driver: See Caching and Read Replicas for details. ## Common issues Issue Cause Fix Requests hit `api.proxy.pgbeam.app` / 404 / wrong project `neonConfig.fetchEndpoint` not set; driver rewrote the host to `api.` Set `neonConfig.fetchEndpoint` so requests target the `/sql` path (see Setup step 2) `WebSocket is not defined` Node.js missing WS constructor Install `ws` and set `neonConfig.webSocketConstructor = ws` WebSocket `Pool` / `Client` connects then hangs, no error Default `pipelineConnect: "password"` pipelines a cleartext password, but PgBeam uses SCRAM Set `neonConfig.pipelineConnect = false`. If you only need one-shot queries, use the HTTP `neon()` path instead `fetch failed` on HTTP endpoint Network/firewall blocking HTTPS, or `fetchEndpoint` not pointed at `/sql` Verify the proxy hostname resolves, port 443 is open, and `fetchEndpoint` is set Slow cold starts with WebSocket TLS + WS handshake on each invocation Use HTTP transport for stateless queries `connection terminated` Idle timeout exceeded Use connection pooling or reconnect on error ## Further reading Connection Pooling: Pool modes and sizing guidance Caching: TTL, SWR, cache rules, and SQL annotations Read Replicas: Replica setup and routing @neondatabase/serverless on npm: Driver documentation --- # SQL over HTTP URL: https://pgbeam.com/docs/sql-over-http Description: Run single-shot SQL queries over plain HTTPS with POST /v1/sql, with the full policy pipeline and audit trail applied to every statement. The REST SQL endpoint runs one SQL statement per HTTPS request, no driver required. It is built for edge and serverless agents that want a curl-friendly surface: post JSON, get rows back as JSON. Every statement goes through the same enforcement pipeline as a direct wire connection: table and column allowlists, PII masking, row filters, query budgets, the whereless-write safety floor, `max_affected_rows` caps, and the audit trail. If you use the `@neondatabase/serverless` driver, use the Neon-compatible endpoints instead; `/v1/sql` is the plain REST alternative for everything else. ## Authentication The endpoint authenticates exactly like the serverless driver surface: pass a PgBeam connection string in the `Connection-String` header (`Neon-Connection-String` is also accepted). The hostname's subdomain routes the request to your project, and the credentials are verified by the proxy before the statement runs. Agent credentials get their policy profile enforced; regular database credentials pass through. Project IP filtering applies to this endpoint the same way it does to `/sql`: when a project has an allowlist configured, requests from addresses outside it are rejected with `403` before any SQL runs. ## Request `POST /v1/sql` with a JSON body: Field Type Required Description `query` string Yes A single SQL statement. `params` array No Positional parameters bound to `$1`..`$N` in order. Parameters are bound over the PostgreSQL extended query protocol. Values are never interpolated into the SQL text, so there is no injection surface in the binding step. A parameter that is itself a JSON array binds as a PostgreSQL array, so `"params": [[1, 2, 3]]` works against `WHERE id = ANY($1)`. A JSON object binds as JSON. Both keep their exact values: a whole number never picks up exponent notation, and a string is never read back as SQL `NULL` or trimmed of surrounding whitespace. One statement per request. Batch bodies (a `queries` array) are rejected with a clear error; if you need multi-statement transactions in one request, use the Neon-compatible `/sql` endpoint and `sql.transaction([...])`. ## Response Field Description `columns` Result columns with the PostgreSQL type name and OID. Empty for statements without a result set. `rows` One JSON object per row, keyed by column name. Always present, `[]` when empty. `command` The completed command tag (`SELECT`, `INSERT`, `UPDATE`, ...). `rowCount` Rows returned (reads) or affected (writes). `null` when the command reports no count. Values are typed JSON: numbers for `int2`/`int4`/floats, booleans for `bool`, parsed objects for `json`/`jsonb`, arrays for array columns. `bigint` (`int8`), `numeric`, and `money` are returned as strings, matching the serverless driver contract: a JavaScript `Number` silently corrupts integers above 2^53 and arbitrary-precision decimals. The same holds element-wise for `int8[]`, `numeric[]` and `money[]`. `uuid` is returned as its canonical dashed text (`"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"`), and `uuid[]` as an array of those strings. ## Errors Errors are JSON with the PostgreSQL SQLSTATE preserved, in the same shape as the serverless surface: HTTP status maps from the SQLSTATE class: authentication failures are `401`, syntax/access/policy errors (including policy blocks, `42501`) and constraint violations are `400`, resource exhaustion is `503`, upstream connection problems are `504`. See error codes for the SQLSTATEs the policy engine emits. ## Policy enforcement and audit The handler does not evaluate policy itself. It opens a loopback session to the local PG wire proxy, presenting your project's hostname as TLS SNI, so the statement takes the identical enforcement path as a `psql` connection: one pipeline, no REST-specific variant. Query caching, pooling, and read-replica routing also apply, and cache annotations like `/* @pgbeam:cache maxAge=300 */` work unchanged. Statements run through `/v1/sql` are recorded in the audit log with `source=rest`, so you can distinguish REST traffic from direct wire connections (`wire`) and MCP sessions (`mcp`) in the dashboard filter, the API, and CSV exports. ## Limits One statement per request; no batches and no cross-request transactions. Each request runs in its own short-lived session, so session state (`SET`, prepared statements, advisory locks) does not carry over. Request bodies are capped at 10 MB, and a statement times out after 30 seconds. Parameterized writes under a `max_affected_rows` cap are rejected fail-closed with SQLSTATE `0A000` (the cap cannot count rows on the extended protocol). Statements without `params` run over the simple query protocol, where the cap is enforced normally, so either inline the values or lift them into the statement. Reads are unaffected. `LISTEN`/`NOTIFY` and `COPY` are not supported on this surface. ## Further reading Serverless Driver: the Neon-compatible `/sql` and `/v2` endpoints for `@neondatabase/serverless` Agent Credentials: scoped credentials with policy profiles Audit Log: what is recorded for every statement Error Codes: SQLSTATEs emitted by the policy engine --- # SSO (SAML / OIDC) URL: https://pgbeam.com/docs/sso Description: Configure Single Sign-On for your organization using SAML 2.0 or OpenID Connect. Scale plan only. Single Sign-On (SSO) lets your team authenticate to PgBeam using your existing identity provider: Okta, Azure AD, Google Workspace, or any SAML 2.0 / OIDC provider. Team members sign in with their corporate credentials instead of managing separate PgBeam passwords. SSO requires the **Scale plan**. See Plans & Pricing for details. ## Supported protocols Protocol Use case **SAML 2.0** Enterprise IdPs (Okta, Azure AD, OneLogin) **OpenID Connect** Modern IdPs and custom OAuth2 providers Choose whichever protocol your identity provider supports. If your IdP supports both, OIDC is generally simpler to configure. ## SAML 2.0 setup ## Create a SAML application in your IdP In your identity provider (Okta, Azure AD, Google Workspace, OneLogin, etc.), create a new SAML 2.0 application. Most providers have a "custom SAML app" option. ## Get PgBeam's SAML configuration Go to **Settings > Security > Configure SSO** in the PgBeam dashboard. You will see two values to copy into your IdP: Field Description **ACS URL** (Assertion Consumer Service) Where your IdP sends SAML responses **Entity ID** (SP Entity ID) PgBeam's SAML identifier ## Configure attribute mapping Map the following SAML attributes in your IdP. PgBeam uses these to identify users: SAML attribute Required Maps to `email` or `NameID` Yes User email `firstName` No Display name `lastName` No Display name ## Add IdP metadata to PgBeam Copy your IdP's **metadata URL** into PgBeam's SSO configuration page and save. PgBeam fetches the IdP certificate, SSO URL, and entity ID from this URL automatically. If your IdP does not provide a metadata URL, you can paste the metadata XML directly. ## Test the connection Click **Test** in the PgBeam dashboard to verify the SAML flow. This opens a new window that walks through the full sign-in process. If the test succeeds, you will see a confirmation with the authenticated user's details. ## OIDC setup ## Create an OIDC application in your IdP In your identity provider, create a new OpenID Connect (OIDC) application. Choose "Web Application" as the application type. ## Configure the redirect URI Set the **redirect URI** to the value shown in PgBeam's SSO configuration page (under **Settings > Security > Configure SSO**). ## Add credentials to PgBeam Copy the following from your IdP into PgBeam: Field Where to find it **Client ID** Application settings in your IdP **Client secret** Application settings in your IdP **Discovery URL** Usually `https://your-idp.com/.well-known/openid-configuration` PgBeam uses the discovery URL to automatically fetch authorization endpoints, token endpoints, and signing keys. ## Test the connection Click **Test** in the PgBeam dashboard to verify the OIDC flow. This redirects to your IdP for authentication and confirms the user details returned. ## Supported identity providers SSO works with any SAML 2.0 or OIDC-compliant identity provider. Commonly used providers include: Provider SAML OIDC Notes Okta Yes Yes Both protocols fully supported Azure AD / Entra ID Yes Yes Use "Enterprise Application" for SAML Google Workspace Yes Yes SAML via Admin Console OneLogin Yes Yes Both protocols fully supported Auth0 Yes Yes Use "Regular Web Application" JumpCloud Yes Yes Both protocols fully supported ## Just-in-time provisioning When a user authenticates via SSO for the first time, PgBeam automatically creates an account for them in your organization with the **Member** role. This means you do not need to invite users individually. Anyone who can authenticate through your IdP is automatically provisioned. Admins and Owners can change a user's role after they have been provisioned. ## SSO enforcement Once SSO is configured and tested, you can **enforce** it for your organization. Enforcement means: All organization members **must** authenticate via SSO Password-based login is **disabled** for the organization Existing sessions are **invalidated** when enforcement is enabled New invitations require the recipient to sign in via SSO Organization owners retain the ability to log in with email/password even when SSO enforcement is enabled. This serves as a recovery mechanism in case the IdP is unavailable or misconfigured. ## Enable enforcement Go to **Settings > Security** in the dashboard. After configuring SSO, toggle **Require SSO for all members**. Confirm the action. All non-owner members will be signed out immediately. ## Troubleshooting ## SAML issues Problem Likely cause Fix "Invalid ACS URL" error ACS URL mismatch between IdP and PgBeam Copy the exact ACS URL from PgBeam "Audience mismatch" error Entity ID mismatch Verify SP Entity ID matches in both systems User lands on error page Attribute mapping missing `email` Ensure `email` or `NameID` is mapped Certificate validation failed IdP certificate rotated Re-import the metadata URL in PgBeam ## OIDC issues Problem Likely cause Fix "Invalid redirect URI" Redirect URI mismatch Copy the exact redirect URI from PgBeam "Invalid client" error Wrong client ID or secret Re-copy credentials from your IdP Discovery URL fails URL is incorrect or not publicly reachable Verify the URL returns JSON in a browser ## General issues Problem Likely cause Fix Users can still use passwords SSO enforcement not enabled Toggle "Require SSO" in Security settings New user gets wrong role Default JIT role is Member Change role after provisioning IdP is down and nobody can log in SSO enforcement is enabled Owner can log in with email/password and disable enforcement ## Further reading Organizations: Roles, team seats, and member management Plans & Limits: SSO is available on the Scale plan API Keys: Programmatic access that does not require SSO --- # Terraform URL: https://pgbeam.com/docs/terraform Description: Manage PgBeam projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, self host enrollments, and honeytokens as infrastructure using Terraform and the pgbeam provider. Manage your PgBeam infrastructure as code with Terraform. The `pgbeam` provider offers native resources for projects, databases, replicas, custom domains, cache rules, spend limits, agent credentials, policy profiles, webhook endpoints, self host enrollments, and honeytokens. ## Setup ## Configure the provider The Terraform provider is coming soon. Registry publishing is on the roadmap. ## Configure credentials Set your PgBeam API key via provider config or environment variable: ## Create a project ## Deploy Terraform creates the PgBeam project and its primary database atomically. The `proxy_host` output gives you the PgBeam proxy endpoint to use in your application connection string. ## Resources **Approval and anomaly rules are not yet managed as code.** Policy profiles and honeytokens are managed resources, so the enforcement rules and the decoys live in your reviewed IaC flow and are covered by drift detection. Approval rules and anomaly rules are not: the API exposes them only as events to review after the fact (approve/reject, ack/resolve), so there is nothing to declare yet. Those two still live outside IaC. ## pgbeam_project Manages a PgBeam project with a primary database. **Computed:** `proxy_host`, `queries_per_second`, `burst_size`, `max_connections`, `database_count`, `active_connections`, `created_at`, `updated_at`, `primary_database_id` **Import:** `terraform import pgbeam_project.example ` ## pgbeam_database Manages an upstream database connection within a PgBeam project. **Computed:** `connection_string`, `created_at`, `updated_at` **Import:** `terraform import pgbeam_database.example /` ## pgbeam_replica Manages a read replica for a PgBeam database. Replicas are immutable; any property change triggers replacement. **Computed:** `created_at`, `updated_at` **Import:** `terraform import pgbeam_replica.example /` ## pgbeam_custom_domain Manages a custom domain for a PgBeam project. CustomDomains are immutable; any property change triggers replacement. **Computed:** `verified`, `verified_at`, `tls_cert_expiry`, `dns_verification_token`, `dns_instructions`, `created_at`, `updated_at` **Import:** `terraform import pgbeam_custom_domain.example /` ## pgbeam_cache_rule Manages a per-query cache rule. Deletion disables caching (soft-delete). **Computed:** `query_hash`, `normalized_sql`, `query_type`, `call_count`, `avg_latency_ms`, `p95_latency_ms`, `avg_response_bytes`, `stability_rate`, `recommendation`, `first_seen_at`, `last_seen_at` **Import:** `terraform import pgbeam_cache_rule.example //` ## pgbeam_spend_limit Manages the monthly spend limit for an organization. **Computed:** `org_id`, `plan`, `billing_provider`, `subscription_status`, `current_period_end`, `enabled`, `custom_pricing`, `spend_capped`, `spend_capped_at`, `limits`, `created_at`, `updated_at` **Import:** `terraform import pgbeam_spend_limit.example ` ## pgbeam_agent_credential Manages a scoped agent credential (a PgBeam-issued Postgres login plus a hosted MCP token) for an AI agent. The connection string and MCP token are one-time secrets returned only at creation and exposed as sensitive computed outputs; they cannot be retrieved again. To rotate the secrets, taint/replace the resource (or use the rotate endpoint out of band). **Computed:** `pg_username`, `auth_method`, `last_used_at`, `created_at`, `updated_at`, `connection_string`, `mcp_url`, `mcp_token` **Import:** `terraform import pgbeam_agent_credential.example /` ## pgbeam_policy_profile Manages a policy profile: a named bundle of agent-gateway enforcement rules (access mode, table allow/deny lists, statement-kind rules, PII masking rules, per-relation row filters, query/egress budgets, write mode, approvals, and migration safety) attached to agent credentials and enforced in the PG wire protocol. Nested-list fields (masking\_rules, row\_filters) and the nested statement\_rules object are expressed as structured config. **Computed:** `created_at`, `updated_at` **Import:** `terraform import pgbeam_policy_profile.example /` ## pgbeam_webhook_endpoint Manages a webhook endpoint that receives project audit and anomaly event deliveries. The signing secret is write-only and never returned by the API. **Computed:** `created_at`, `updated_at` **Import:** `terraform import pgbeam_webhook_endpoint.example /` ## pgbeam_self_host_enrollment Manages a self-host (BYOC) enrollment: a token a self-hosted proxy uses to authenticate to the control plane's config/audit stream. The token is a one-time secret returned only at creation and exposed as a sensitive computed output; it cannot be retrieved again. To rotate the token, replace the resource. Deletion revokes the enrollment. SelfHostEnrollments are immutable; any property change triggers replacement. **Computed:** `created_by`, `created_at`, `last_seen_at`, `revoked_at`, `token` **Import:** `terraform import pgbeam_self_host_enrollment.example /` ## pgbeam_honeytoken Manages a honeytoken: a decoy (canary) relation that no legitimate query should ever touch. Any agent statement referencing it is blocked and recorded as a canary\_tripped audit event; the kill action additionally disables the tripping credential via the kill-switch. The relation does not have to exist in the upstream database: enforcement is by name, in the wire protocol, before the statement reaches Postgres. **Computed:** `created_at`, `updated_at` **Import:** `terraform import pgbeam_honeytoken.example /` ## Configuration Setting Source Description `api_key` Provider block API key (sensitive, recommended: use a variable) `base_url` Provider block API base URL (default: `https://api.pgbeam.com`) `PGBEAM_API_KEY` Environment Fallback API key `PGBEAM_API_URL` Environment Fallback base URL Config resolution order: provider block > environment variables. ## Replacement vs update Some property changes trigger resource replacement (destroy + create) rather than in-place updates: Resource Replacement triggers Project `org_id`, `cloud`, `self_hosted` Database `project_id` Replica Any property change (immutable) CustomDomain Any property change (immutable) CacheRule `project_id`, `database_id`, `query_hash` SpendLimit `org_id` AgentCredential `project_id`, `policy_profile_id`, `name`, `principal_type`, `expires_at` PolicyProfile `project_id` WebhookEndpoint `project_id` SelfHostEnrollment Any property change (immutable) Honeytoken `project_id` ## Further reading Connection Pooling: pool modes and sizing Caching: query caching and SWR Read Replicas: replica routing Custom Domains: DNS setup and verification API Keys: managing API credentials Plans: plan limits and pricing --- # Troubleshooting URL: https://pgbeam.com/docs/troubleshooting Description: Common PgBeam failures, what they usually mean, and step-by-step instructions to diagnose and fix them. Something is broken, traffic is failing, and you need to figure out whether the problem is in PgBeam, your origin database, or your application configuration. This guide walks through the most common issues. ## Start with debug mode Before tackling specific problems, enable PgBeam's debug output. This adds a `NOTICE` to every query response with cache, routing, and timing information: Debug notices tell you: Whether the query was a cache **hit**, **miss**, **stale hit**, or **bypass** Cache timing: how old the cached entry is, TTL, and SWR values Whether **replica routing** was used and which upstream handled the query Disable it again with `SET pgbeam.debug = off`. ## Connection problems ## Cannot connect at all **Symptoms:** Connection timeout, connection refused, or DNS resolution failure. **Checklist:** **Verify the hostname.** It should be `.proxy.pgbeam.app` on port `5432`. Check for typos. **Verify TLS is enabled.** PgBeam requires TLS. Most PostgreSQL drivers enable it by default, but check your connection string for `sslmode=disable`. That will not work. **Check your firewall.** Confirm outbound TCP traffic on port 5432 is allowed from your environment. Corporate networks, VPNs, and cloud security groups sometimes block non-HTTP ports. **Confirm the project exists.** Log in to dash.pgbeam.com and verify the project is there and the organization is active. **Check PgBeam status.** Visit the PgBeam status page or run `pgbeam platform health` in the CLI. ## `08004`: Project not found The hostname does not match any project. Common causes: Typo in the connection string The project was deleted Using a custom domain that hasn't been verified yet **Fix:** Check the hostname in your `DATABASE_URL` against the project hostname in the dashboard. ## `08004`: IP not allowed The project has an IP allowlist configured and your client's IP is not in it. **Checklist:** **Check the allowlist.** Go to your project's **Settings > Security** to see which CIDR ranges are allowed. **Find your egress IP.** Your client's outbound IP may differ from what you expect: cloud platforms, VPNs, and NAT gateways change the source IP. Run `curl ifconfig.me` from the environment that connects to PgBeam. **Add the IP.** Add your IP (as `/32` for a single address) or CIDR range to the allowlist. **Check all environments.** Make sure CI/CD, staging, monitoring tools, and developer machines are all included. See IP Allowlisting for configuration details. ## `08004`: Organization suspended The organization's billing is inactive. This happens when: A payment method fails The trial expired without a payment method An owner cancelled the subscription **Fix:** Go to **Settings > Billing** in the dashboard and update the payment method or reactivate. ## Authentication problems ## `08006`: Authentication failed PgBeam forwarded your credentials to the origin database and it rejected them. This is an upstream issue, not a PgBeam issue. **Checklist:** **Test direct connection.** Connect directly to the origin database with the same credentials. If it fails there too, the problem is not PgBeam. **Check the database name.** Verify that the database name configured in PgBeam matches the actual database you want to connect to. **Check user permissions.** Confirm the database user has `CONNECT` permission: `SELECT usename, usesuper FROM pg_user WHERE usename = 'myuser';` **Check pg\_hba.conf.** If the origin uses host-based authentication rules, ensure the PgBeam IP range is allowed. ## `08004`: Auth rate limited Too many failed authentication attempts from the same IP address in a short period. **Fix:** Stop the source of failed authentications (misconfigured client, wrong password in environment) Wait a few minutes for the rate limit to expire Verify credentials are correct before retrying ## Upstream problems ## `08006`: Circuit breaker open The origin database failed 3 consecutive connection attempts. PgBeam opened the circuit breaker to stop hammering it. **Checklist:** **Check origin health.** Can you connect directly to the origin database from another client? **Check connection limits.** Has the origin database hit its own `max_connections` limit? **Check network path.** Are there firewall rules, security groups, or IP allowlists blocking PgBeam? **Wait for recovery.** The circuit breaker probes automatically every 5-60 seconds (exponential backoff). Successful probes restore traffic. See Resilience for details on circuit breaker states and recovery. ## Origin database is slow If queries are slow but connections work, PgBeam is passing traffic through correctly. The issue is upstream. **Checklist:** Enable `pgbeam.debug` to confirm queries are reaching the upstream (you'll see `cache=miss`) Run the same query directly against the origin to compare latency Check the origin database for slow query logs, lock contention, or resource exhaustion ## Connection limit problems ## `53300`: Too many connections The project hit its concurrent connection limit (20 / 100 / 500 depending on plan). **Fixes, in order of preference:** **Reduce client pool size.** If you have 4 app servers each with a pool of 20, that's 80 connections. With PgBeam, use 3-5 per instance instead. See Connection Pooling. **Switch to transaction pool mode.** Session mode (the default) holds an upstream connection for the entire client session. Transaction mode releases it after each transaction, dramatically improving reuse. **Close idle connections.** Check for dev tools, monitoring scripts, or migration runners holding connections open. **Upgrade your plan.** If the workload has genuinely outgrown the current tier. ## Connections spike after deploy After a rolling deploy, old and new instances briefly overlap, doubling the connection count. This is normal and resolves as old instances shut down. **Mitigation:** Set short connection pool idle timeouts in your application Use transaction pool mode to reduce the per-instance connection footprint If the spike exceeds your limit, consider upgrading temporarily or staggering deploys ## Rate limit problems ## `53400`: Query rate limit exceeded The project exceeded its QPS limit (10 / 50 / 250 depending on plan). **Fixes:** **Enable caching** for high-frequency repeated reads. Cached queries reduce upstream load and the effective QPS. See Caching. **Batch queries** where possible. Multiple small queries can sometimes be combined. **Check for runaway clients.** A misconfigured cron job or retry loop can exhaust the QPS budget. **Upgrade your plan** for a higher QPS allowance. ## Cache problems ## Cache is not caching anything **Checklist:** **Is caching enabled?** Caching is off by default. Check that it is enabled via cache rules, session override, or database default. **Is the query a read?** Only `SELECT` statements are cacheable. **Is the query inside a transaction?** Queries in `BEGIN`/`COMMIT` blocks are never cached. **Does the query use volatile functions?** `NOW()`, `RANDOM()`, `pg_advisory_lock()`, and similar functions cause bypass. **Does the SQL explicitly disable cache?** Check for `/* @pgbeam:cache noCache */`. **Enable debug mode** and check the NOTICE output to see why the query is not being cached. ## Getting stale data after writes If you write data and immediately read it back, you may get a cached (stale) version of the old data. **Fixes:** **Use `noCache` for read-after-write queries:** **Reduce TTL** for query shapes where freshness is important. **Disable caching** for queries that must always return the latest data. ## Cache hit rate is low A low cache hit rate means the cache is not saving much upstream load. **Common causes:** Queries have highly variable parameters (each unique set of params creates a new cache entry) TTL is too short for the query frequency The workload is write-heavy and data changes between reads ## TLS problems ## Client rejects the certificate **Checklist:** **Update your CA bundle.** PgBeam uses publicly trusted certificates that work with all modern systems. If your client is running on an old OS or container image, the CA bundle may be outdated. **Check the hostname.** The certificate matches `*.proxy.pgbeam.app`. If you are using an IP address or a hostname that does not match, TLS validation will fail. **Custom domains:** If using a custom domain, verify the ACME challenge CNAME is in place so PgBeam can provision the certificate. See Custom Domains. ## TLS required but client is not using it PgBeam requires TLS for all connections. If your client has TLS disabled (`sslmode=disable`), the connection will fail. **Fix:** Remove `sslmode=disable` from your connection string or set `sslmode=require`. ## Performance problems ## First connection after inactivity is slow Projects with no activity for 5 minutes enter a **parked** state. The first connection triggers a cold start that adds some latency. Subsequent connections are fast. This is expected behavior. See Resilience for details on scale-to-zero. ## Cross-region latency If your database is in one region but your application is in another, cache misses incur cross-region latency (30-150ms). Cache hits are served locally with sub-millisecond latency. **Mitigations:** Enable caching for repeated reads to serve them from the nearest region Add read replicas in regions closer to your application If latency is critical, consider deploying your database closer to your users ## SQLSTATE quick reference SQLSTATE Message Section `08004` Project not found Connection problems `08004` IP not allowed Connection problems `08004` Organization suspended Connection problems `08004` Auth rate limited Authentication problems `08006` Upstream auth failure Authentication problems `08006` Circuit breaker open Upstream problems `53300` Too many connections Connection limit problems `53400` Query rate limit exceeded Rate limit problems See Error Codes for the full reference with code examples. ## Still stuck? If you have worked through the relevant section and the problem persists: Enable `pgbeam.debug` and capture the NOTICE output Check Error Codes for the specific SQLSTATE Test a direct connection to the origin database to isolate PgBeam vs upstream Contact support at support\@pgbeam.com with the debug output, SQLSTATE, and steps to reproduce --- # Vercel Marketplace URL: https://pgbeam.com/docs/vercel-marketplace Description: Deploy PgBeam as a Vercel Marketplace integration. Provision a policy-enforced Postgres gateway with pooling and caching directly from your Vercel dashboard. Deploy PgBeam directly from the Vercel Marketplace. The integration provisions a PgBeam project, connects it to your database, and injects connection secrets into your Vercel project. Zero configuration required. The integration is built and ready. The public Vercel Marketplace listing goes live at launch. Until then, provision PgBeam from the dashboard. ## How it works ## Install from Vercel Marketplace Find PgBeam in the Vercel Marketplace and click **Add Integration**. This creates a PgBeam organization linked to your Vercel team. ## Provision a resource From the integration page, create a new PgBeam resource. Provide your upstream database connection details and PgBeam provisions a project with connection pooling and optional query caching. ## Connect your app PgBeam automatically sets `DATABASE_URL` and `PGBEAM_PROJECT_ID` as environment variables in your Vercel project. Update your application to use the PgBeam connection string. No code changes beyond swapping the DSN. ## Features **One-click provisioning**: create PgBeam projects without leaving Vercel **Automatic secrets**: connection strings injected as environment variables **Unified billing**: PgBeam usage appears on your Vercel invoice **Per-project resources**: each Vercel project gets its own PgBeam project **Team sync**: Vercel team members get access to the PgBeam dashboard ## Billing PgBeam usage provisioned through the Vercel Marketplace is billed through Vercel. The same plan tiers (Starter, Pro, Scale) and overage rates apply. See Plans and Limits for details. ## Further reading Serverless Connections: optimizing for serverless Connection Pooling: pool modes and sizing Caching: query caching and SWR Plans: plan limits and pricing --- # Webhook Events URL: https://pgbeam.com/docs/webhook-events Description: The full set of webhook event types PgBeam delivers, when each one fires, and the payload shape you receive. Audit export delivers events to a webhook endpoint as they happen. This page enumerates every event type you can subscribe to, when each one fires, and the fields in its payload. Subscribe to a subset with `event_types` (the CLI `--event` flag), or omit it to receive all of them. ## Event types `event_type` Fires when `query_blocked` A statement is rejected by policy (allowlist, read-only, and so on). `budget_exhausted` A credential hits its query or row budget. `kill_switch` A credential or project kill-switch is tripped. `masked` A result is returned with one or more masked columns. `migration_flagged` A DDL statement is flagged by the safe-migration linter. `approval_requested` A write or DDL is held for approval. `anomaly_alert` Anomaly detection raises an alert. `audit_checkpoint` A signed checkpoint is issued over the project's audit chain. A separate `webhook.test` event is sent only when you use **Send test event** on an endpoint. You do not subscribe to it, and it never fires from live traffic. ## Envelope Every delivery in the native `json` format shares the same envelope. The event-specific fields live under `data`. Field Description `id` Stable event id. Use it to de-duplicate retried deliveries. `type` The event type, one of the values above. `project_id` The project the event belongs to. `occurred_at` When the underlying event happened (RFC 3339). `data` Event-specific fields, documented per event type below. The SIEM formats (`splunk_hec`, `datadog`, `elastic`) wrap these same fields in the shape that product expects. ## Audit-derived events `query_blocked`, `budget_exhausted`, `masked`, `migration_flagged`, and `approval_requested` all come from the audit log. They share the same `data` shape; the `event` field inside `data` tells you which underlying audit event it was. Field Description `audit_id` Id of the audit-log entry this event came from. `credential_id` The credential that ran the statement. `region` Region that served the statement. `event` The underlying audit event (for example `blocked`, `masked`). `sql` The statement, as parsed. `normalized_sql` The statement with literals stripped. `query_hash` Hash of the normalized statement. `statement_kind` The statement kind (for example `select`, `delete`). `decision_rule` The rule that produced the decision. `reason` Why it was blocked, masked, or held. `rows_returned` Rows returned to the agent, after masking and row caps. `bytes_out` Bytes returned. `latency_ms` Time to serve the statement. `client_ip` The agent's source IP. `session_id` The wire session the statement ran in. `source` Where the statement came from: a connection string or MCP. The `kill_switch` type also fires from the audit stream when a statement is killed mid-flight, with the same `data` shape as above. ## `kill_switch` (project) When a project kill-switch is engaged from the control plane, the event carries a compact payload rather than a per-statement one: Field Description `project_id` The project whose kill-switch was engaged. `agents_disabled` `true` while agent connections are blocked. `reason` Why the kill-switch fired. ## `anomaly_alert` Raised by anomaly detection when a credential drifts from its baseline. Field Description `id` The anomaly alert id. `project_id` The project the alert belongs to. `credential_id` The credential the alert is about. `kind` The signal that tripped: `volume_spike`, `egress_spike`, `new_query_shape`, `off_hours`, or `error_spike`. `severity` The alert severity. `title` A short human-readable summary. `details` Signal-specific detail (varies by `kind`). `window_start` Start of the window the alert was computed over (RFC 3339). `window_end` End of that window (RFC 3339). ## `audit_checkpoint` A periodic signed statement of how long the project's audit chain is and what it contains. Unlike every other event here, it is not about one query: it is about the whole chain. Keep these. A hash chain cannot detect deletion at its own tip, because nothing inside it records how long it was supposed to be. A checkpoint you have retained is an outside record, so it lets you detect a truncation from a copy PgBeam no longer holds, and lets you verify the claim without trusting us to verify it for you. Field Description `checkpoint_id` Id of the checkpoint. `origin` Log identity, `pgbeam/audit/`. Bound into the signature. `size` Number of audit entries the checkpoint commits to. `root` Merkle root over those entries, hex. `key_name` Name of the Ed25519 key that signed the note. `note` The signed artifact, in the transparency-log note format. This is what to retain. The `size` and `root` fields are there so you can read the event without parsing anything. `note` is the one that carries the claim: it is signed, so `size` and `root` cannot be altered inside it, and it is what a verifier checks. If you keep only one field, keep that one. The tree is an RFC 6962 Merkle tree, so any library implementing that specification can verify a note against a set of entries. ## `webhook.test` Sent by **Send test event** so you can verify a receiver before relying on it. ## Related Audit export: configure endpoints, signing, and SIEM formats. Audit log: the queryable history audit-derived events come from. Anomaly detection: source of `anomaly_alert` events. Kill-switch: source of `kill_switch` events. Audit log: the chain `audit_checkpoint` commits to, and the verification endpoint that compares the two. --- # REST API URL: https://pgbeam.com/docs/api Description: The PgBeam REST API. Control-plane endpoints for projects, databases, policies, agents, analytics, and platform state, described by an OpenAPI 3.1 spec at https://pgbeam.com/openapi.json. The PgBeam API is the control plane behind the dashboard and CLI. Use it when you want to automate project creation, database setup, usage reporting, cache configuration, or onboarding from your own tooling. **Base URL:** `https://api.pgbeam.com` The PgBeam CLI wraps the same API and is usually the fastest way to explore the platform from a terminal. Reach for the raw API when you need custom automation, CI integration, or your own internal tooling. ## What this API is good at Area Use it for Projects Create, inspect, update, and delete PgBeam projects Databases Register origin databases, test connectivity, and adjust pool or cache settings Agents Issue, inspect, and revoke scoped agent and human credentials Policies Manage policy profiles: access mode, allowlists, row filters, masking, budgets Approvals List, approve, and reject held writes and DDL Webhooks Configure HMAC-signed webhook and SIEM audit export endpoints Anomalies List and triage anomaly alerts Branches List and discard sandbox branches Migrations Lint DDL for locks, rewrites, and unsafe changes Analytics Read usage, activity, metrics, and query insights Platform Discover regions, plans, and health Account Export account data and track onboarding progress ## Authentication Most endpoints require `Authorization: Bearer ...`. The credential can be either: Credential How to get it Header Dashboard token Sign in to the dashboard and reuse the session token in trusted tooling `Authorization: Bearer ` API key Create one from the dashboard for scripts, CI, and long-lived automation `Authorization: Bearer ` `/v1/health` is public. Everything else in the public API expects auth. See API Keys for key creation and rotation. ## OpenAPI & Codegen The public spec is available at api.pgbeam.com/openapi.json. It is the source for our SDK and the generated endpoint pages in this section. ## Download the spec ## Generate a client Feed the spec to your OpenAPI tooling of choice. For example, with openapi-generator: If you are working in TypeScript, use the official PgBeam SDK instead of generating a client. It is maintained alongside the API and provides tag-based access, error handling, and full type safety out of the box. ## Next steps Response Conventions — status codes, pagination, and error envelopes --- # MCP Server URL: https://pgbeam.com/docs/api/mcp Description: Remote MCP endpoint for AI agent integration. `POST /v1/mcp` is a remote Model Context Protocol server using the Streamable HTTP transport. It lets AI assistants manage PgBeam resources (projects, databases, policies, agent credentials) through three meta-tools rather than one tool per endpoint. See the MCP command docs for full setup instructions covering both the CLI (stdio) and remote (HTTP) transports. This is the **management** MCP — it administers your account. To give an agent **query access to a database**, use the hosted agent-database MCP, a separate endpoint with `briefing`, `query`, `validate_sql`, `list_tables`, `describe_table`, `explain`, `schema_catalog`, and `my_permissions` tools enforced by your policies, plus `search_docs` and `read_doc`. ## Quick start ## Protocol Property Value Transport Streamable HTTP (MCP spec 2025-03-26) Wire format JSON-RPC 2.0 Auth `Authorization: Bearer ` Methods `initialize`, `notifications/initialized`, `tools/list`, `tools/call`, `ping` ## Authentication The MCP endpoint uses the same authentication as the REST API. Pass a bearer token or API key in the `Authorization` header. See Authentication. ## Tools `tools/list` returns three meta-tools that wrap the whole API. This keeps the agent's context small — it discovers operations on demand instead of loading a schema for every endpoint up front. Tool Purpose `search_endpoints` Find operations by intent (`query`, `limit`). Returns `operation_id`, `method`, `path`, `tag`. `describe_endpoint` Full schema for one operation (`operation_id`): parameters and request body. `call_endpoint` Invoke an operation: `operation_id`, plus `path_params`, `query_params`, and `body` as needed. The operation ids and shapes mirror the OpenAPI spec. A typical flow is `search_endpoints` → `describe_endpoint` → `call_endpoint`. --- # Response Conventions URL: https://pgbeam.com/docs/api/response-conventions Description: Status codes, error envelope, retries, and idempotency across the PgBeam API. Every endpoint follows the same conventions for status codes, error responses, retries, and idempotency. ## Status codes Code Meaning Description `200` OK Success with a response body `201` Created A resource was created `204` No Content Success, no response body `4xx` Client error Bad request, unauthorized, not found, etc. `5xx` Server error Something went wrong on our end ## Pagination List endpoints return an array plus pagination metadata. ## Error envelope All errors use the same JSON envelope: Field Type Description `error.code` `string` Machine-readable error code `error.message` `string` Human-readable description ## Error codes HTTP Status `error.code` Description 400 `INVALID_INPUT` Bad request — fix the input 401 `UNAUTHORIZED` Missing or invalid authentication 403 `FORBIDDEN` Insufficient permissions or plan limits 404 `NOT_FOUND` Resource not found 409 `CONFLICT` Resource already exists or state conflict 422 `INVALID_INPUT` Validation error 429 `RATE_LIMITED` Too many requests (includes `Retry-After` header) 500 `INTERNAL_ERROR` Internal server error 502 — Bad gateway 503 — Service unavailable 504 — Gateway timeout ## Retries ## Retryable status codes The SDKs automatically retry requests that fail with these status codes: Status Retryable Notes 408 **Yes** Request timeout 429 **Yes** Rate limited — respects `Retry-After` 502 **Yes** Bad gateway 503 **Yes** Service unavailable — respects `Retry-After` 504 **Yes** Gateway timeout Network error **Yes** Connection refused, DNS failure, timeout All other codes No Returned immediately ## Exponential backoff with jitter The wait between retries follows this formula: Setting Default Description Max retries 5 Total retry attempts (`0` to disable) Initial delay 500ms First backoff interval Max delay 30s Backoff ceiling ## Retry-After header When the server returns a `Retry-After` header (on 429 or 503), the SDKs use that value instead of their own computed backoff. Both formats are supported: **Integer seconds:** `Retry-After: 60` **HTTP-date:** `Retry-After: Thu, 01 Jan 2026 00:00:00 GMT` ## Idempotency POST and PATCH requests include an `Idempotency-Key` header so retries never double-create resources. Keys are UUID v4, generated once per SDK call and reused across all attempts Sent on every attempt (including the first) so the server can deduplicate even if the initial request succeeds but the client loses the response GET and DELETE are naturally idempotent — no key needed The server caches idempotent responses for **24 hours** Success responses and 4xx responses are cached. A 4xx is the server's settled answer about that exact request, so a retry carrying the same key is answered from the cache rather than running the handler again Every 5xx, plus 408 and 429, is **not** cached. A server error means the request produced no settled answer, so the next retry with the same key executes the handler again See the TypeScript SDK and Go SDK docs for language-specific configuration. --- # doctor URL: https://pgbeam.com/docs/cli/doctor Description: Diagnose your PgBeam setup end to end Run an end-to-end diagnostic of your PgBeam setup and print actionable pass, warning, and fail results. Doctor checks that credentials are present and valid, the control-plane API is reachable, the selected organization, project, and databases resolve, the proxy Postgres port is reachable (best-effort TCP), the hosted MCP endpoint answers (and, with `--mcp-token`, exposes the expected agent-database tools), and summarizes the project's default policy. It degrades gracefully offline: network problems are warnings with guidance, not crashes, and it never prints secrets. It exits non-zero only when a check fails. ## Usage ## Options Option Description Required Default `--mcp-url ` MCP endpoint URL to check directly (defaults to the project's proxy host). No - `--mcp-token ` Agent MCP bearer token (`pba_...`) used to verify the endpoint's tool set. Also read from `PGBEAM_MCP_TOKEN`. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints one line per check with a `PASS`, `WARN`, `FAIL`, or `SKIP` tag, a one-line finding, and a remedy for anything that is not passing, followed by a summary. With `--json`, returns `{ ok, summary, checks }`. Exits non-zero when any check fails. --- # Global Options URL: https://pgbeam.com/docs/cli/global-options Description: Flags and environment variables available on every PgBeam CLI command. ## Global flags Flag Description `--token` API token (overrides profile) `--profile` Auth profile to use `--project` Project ID (overrides linked project) `--org` Organization ID (overrides profile) `--json` Output as JSON `--no-color` Disable color output `--no-trunc` Show full table cell values `--debug` Enable debug output Use `--json` on any command to get machine-readable JSON output. This is useful for scripting and CI/CD pipelines. With `--json`, errors are machine-readable too: instead of human-formatted console output, a failed command prints a JSON error object to stdout and exits non-zero. The `status` field is present for API errors, and `hint` carries the same remediation hint the human output shows: ## Environment variables Variable Description `PGBEAM_TOKEN` Use a token directly (skips profile lookup) `PGBEAM_PROFILE` Select a named profile without `--profile` `PGBEAM_NO_UPDATE_CHECK` Disable automatic update checks ## Raw API access The CLI includes a built-in HTTP client for making raw API requests: See api ls for full details. --- # CLI installation URL: https://pgbeam.com/docs/cli Description: Install the PgBeam CLI on macOS or Linux. The installer downloads a precompiled binary and adds it to your PATH. Supports x86\_64 and ARM64 architectures. Verify the installation: After installing, authenticate with your PgBeam account: See auth login for details. --- # mcp URL: https://pgbeam.com/docs/cli/mcp Description: Start MCP server (stdio transport) Start a Model Context Protocol (MCP) server using stdio transport. This allows AI coding assistants like Claude Code, Cursor, and other MCP-compatible clients to manage PgBeam projects, databases, and cache rules directly. Rather than one tool per endpoint, the server exposes three meta-tools — search\_endpoints, describe\_endpoint, and call\_endpoint — so the agent discovers and invokes the API it needs without loading dozens of tool schemas up front. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Starts the MCP server and listens for JSON-RPC messages on stdin/stdout. The server runs until the process is terminated. No human-readable output is produced — all communication is via the MCP protocol. ## Configuration Two transports are available: Transport When to use **CLI (stdio)** Local dev — the AI tool spawns `pgbeam mcp` as a subprocess **Remote (Streamable HTTP)** Server-to-server, hosted agents, or when the CLI isn't installed ## CLI transport (stdio) Add the MCP server to your AI tool's configuration: ## Remote transport (Streamable HTTP) The remote endpoint follows the MCP Streamable HTTP transport (spec version 2025-03-26). Use it when the CLI isn't available or you need server-to-server integration. Any MCP client that supports Streamable HTTP can connect directly: ## Example: raw JSON-RPC ## Available tools The management API has dozens of endpoints. Exposing each as its own MCP tool floods the agent's context with schemas it will never use, so the server instead exposes three meta-tools and lets the agent discover what it needs: Tool Purpose `search_endpoints` Find operations by intent. Returns a compact list (`operation_id`, `method`, `path`, `tag`). Optional `query` and `limit`. `describe_endpoint` Return one operation's full schema: parameters and request body. Takes `operation_id`. `call_endpoint` Invoke an operation. Takes `operation_id`, plus `path_params`, `query_params`, and `body` as needed. The operation ids and shapes come from the OpenAPI spec. The typical flow is `search_endpoints` → `describe_endpoint` → `call_endpoint`. Both transports expose the same three meta-tools. This server manages your PgBeam account (projects, databases, policies, credentials). To give an agent **query access to a database**, use the hosted agent-database MCP instead, a separate endpoint with `briefing`, `query`, `validate_sql`, `list_tables`, `describe_table`, `explain`, `schema_catalog`, and `my_permissions` tools held to your policies, plus `search_docs` and `read_doc`. --- # update URL: https://pgbeam.com/docs/cli/update Description: Update the PgBeam CLI to the latest version Check for and install CLI updates. By default, checks the latest stable release and prompts before updating. Use `--channel dev` with `--version` to install development builds (e.g. PR preview builds). The binary is downloaded from S3 and replaces the current installation in-place. ## Usage ## Options Option Description Required Default `--yes`, `-y` Skip the confirmation prompt before updating No `false` `--channel ` Update channel to use: latest (stable releases) or dev (PR preview builds) No `latest` `--version ` Specific version to install. Required for the dev channel (e.g. pr-434). Optional for latest channel (e.g. 1.2.3). No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Shows the current and target version. If already on the latest version, prints a success message. Otherwise, prompts for confirmation (unless `--yes`), downloads the new binary, and confirms the installation. --- # Error Handling URL: https://pgbeam.com/docs/go-sdk/error-handling Description: Catch and inspect API errors, configure retries, and use idempotency keys in the PgBeam Go SDK. All methods return an `error` on failure. Use `pgbeam.IsNotFound()` to check for 404 responses, and `errors.As` to extract detailed status information from `*pgbeam.APIError`. ## APIError properties Property Type Description `StatusCode` `int` HTTP status code `Status` `string` HTTP status text `Body` `string` Raw response body ## IsNotFound helper `pgbeam.IsNotFound(err)` returns `true` if the underlying error is a 404 response. It uses `errors.As` internally, so it works even when the error is wrapped with `fmt.Errorf("...: %w", err)`. See Response Conventions for the full list of error codes and the error envelope format. ## Retries The SDK automatically retries transient errors with exponential backoff. Non-retryable errors are returned immediately. **Retried:** 408, 429, 502, 503, 504, and network errors (connection refused, DNS failure, timeout). All other status codes are **not** retried. When the server returns a `Retry-After` header (on 429 or 503), the SDK uses that value instead of its own computed backoff. See Response Conventions for the backoff formula and retry behavior details. ## Retry configuration Field Type Default Description `MaxRetries` `int` `5` Max retry attempts after the initial request. `0` disables retries. `InitialDelay` `time.Duration` `500ms` Initial backoff delay. `MaxDelay` `time.Duration` `30s` Maximum backoff delay. ## Disabling retries ## Context cancellation Retry loops respect `context.Context`. If the context is cancelled or its deadline expires, the SDK stops retrying and returns the context error. ## Idempotency POST and PATCH requests automatically include an `Idempotency-Key` header when retries are enabled, so retries never double-create resources. The server caches responses for 24 hours. See Response Conventions for how idempotency keys work. --- # Go SDK installation URL: https://pgbeam.com/docs/go-sdk Description: Install the pgbeam-go SDK, configure the client, authenticate, and learn the service-based access pattern with a full agent-gateway quickstart. The PgBeam Go SDK is the official client for the PgBeam control-plane API. It covers every API resource — projects and databases, plus the agent gateway: agent credentials, policy profiles, approvals, webhooks, anomalies, and audit logs — so you can provision safe, scoped Postgres access for AI agents from Go. The module path is `go.pgbeam.com/sdk` (a vanity import that resolves to the public mirror). The package name is `pgbeam`. ## Installation Requires Go 1.24 or newer. Import it as: ## Client setup ## Constructor options Option Type Description `APIKey` `string` PgBeam API key (required, prefix `pgb_`) `BaseURL` `string` API base URL (default: `https://api.pgbeam.com`) `HTTPClient` `*http.Client` Custom HTTP client for proxies, timeouts, etc. ## Authentication See API Keys for key creation and rotation. ## Usage pattern The Go SDK uses service-based access, matching the TypeScript SDK's tag-based `api.projects.*`, `api.databases.*` pattern: Each service field on the client maps to an API tag: Service Go Covers `Projects` `client.Projects` Projects, replicas, custom domains, cache rules `Databases` `client.Databases` Upstream database connections `Policies` `client.Policies` Policy profiles (read-only, allowlists, masking) `Agents` `client.Agents` Agent credentials, rotation, audit logs `Approvals` `client.Approvals` Held-statement approval requests `Webhooks` `client.Webhooks` Webhook endpoints for gateway events `Anomalies` `client.Anomalies` Anomaly alerts `Branches` `client.Branches` Database branches `Migrations` `client.Migrations` Migration safety linting `Analytics` `client.Analytics` Plans, usage, spend limits, insights `Platform` `client.Platform` Health, regions `Account` `client.Account` Account export, onboarding ## Quickstart: provision an agent credential This end-to-end example creates a read-only policy profile and issues a scoped agent credential against it. The connection string and MCP token are returned **once** — capture them immediately. ## Examples across the surface ## List and inspect policy profiles ## Rotate or revoke an agent credential ## Approve a held statement When a policy holds a write for approval, decide on it from the approvals service: ## Register a webhook endpoint ## Page through the audit log For per-method reference — every parameter, response type, and error code — see the service pages in the sidebar. For error handling, retries, and idempotency, see Error Handling. --- # Error Handling URL: https://pgbeam.com/docs/ts-sdk/error-handling Description: Catch and inspect API errors, configure retries, and use idempotency keys in the PgBeam TypeScript SDK. All non-2xx responses throw an `ApiError`: ## ApiError properties Property Type Description `status` `number` HTTP status code `statusText` `string` HTTP status text `body` `unknown` Parsed response body ## extractMessage helper Pulls the human-readable message from the standard `{ error: { code, message } }` envelope: See Response Conventions for the full list of error codes and the error envelope format. ## Retries The SDK automatically retries transient errors with exponential backoff. Non-retryable errors are thrown immediately. **Retried:** 408, 429, 502, 503, 504, and network errors (connection refused, DNS failure, fetch error). All other status codes are **not** retried. When the server returns a `Retry-After` header (on 429 or 503), the SDK uses that value instead of its own computed backoff. See Response Conventions for the backoff formula and retry behavior details. ## Retry configuration Option Type Default Description `maxRetries` `number` `5` Max retry attempts after the initial request. `0` disables retries. `initialDelayMs` `number` `500` Initial backoff delay in milliseconds. `maxDelayMs` `number` `30000` Maximum backoff delay in milliseconds. `idempotencyKeys` `boolean` `true` Auto-send `Idempotency-Key` header on POST/PATCH. ## Disabling retries ## Idempotency When `idempotencyKeys` is enabled (the default), POST and PATCH requests include an `Idempotency-Key` header so retries never double-create resources. The server caches responses for 24 hours. See Response Conventions for how idempotency keys work. --- # TypeScript SDK installation URL: https://pgbeam.com/docs/ts-sdk Description: Install the PgBeam SDK, configure the client, authenticate, and learn the two access patterns. ## Installation ## Client setup ## Constructor options Option Type Description `token` `string \| null \| () => Promise` JWT token, API key, or async function that resolves one `baseUrl` `string` Base URL of the PgBeam API `fetch` `typeof globalThis.fetch` Optional custom fetch implementation `onResponse` `OnResponseHook` Optional hook called after every response ## Authentication The `token` constructor option accepts a static string, an async function, or an API key. Choose the approach that fits your environment. See API Keys for key creation and rotation. ## Usage patterns The SDK supports two styles for making requests: tag-based access and route-based access. Both are fully type-safe. ## Tag-based access Methods are grouped by tag: `projects`, `databases`, `analytics`, `platform`, and `account`. ## Route-based access Use `api.request()` with a route string for a more REST-like style: Tag-based access is recommended for most use cases. It provides better discoverability through IDE autocomplete. Route-based access is useful when you want your code to mirror the REST endpoints directly. --- # Export account data URL: https://pgbeam.com/docs/api/account/exportAccountData Description: Returns all personal data associated with the authenticated user in a structured JSON format. Supports GDPR data portability and CCPA right to know. Audit logs are limited to the most recent 1000 entries. --- # Get onboarding progress URL: https://pgbeam.com/docs/api/account/getOnboardingProgress Description: Returns the onboarding checklist progress for an organization. --- # List organizations URL: https://pgbeam.com/docs/api/account/listOrganizations Description: Lists the organizations visible to the caller's credential. An organization-scoped API key (pbo_) returns exactly the organization it belongs to. A user credential (account-scoped API key or dashboard session token) returns the organizations the user is a member of, including the caller's role in each. --- # Update onboarding progress URL: https://pgbeam.com/docs/api/account/updateOnboardingProgress Description: Mark an onboarding step as complete or dismiss the checklist. --- # Create an agent credential URL: https://pgbeam.com/docs/api/agents/createAgentCredential Description: Issues a scoped Postgres login and hosted MCP token for an AI agent. The connection string and MCP token are returned once and cannot be retrieved again. --- # Export agent audit logs as CSV URL: https://pgbeam.com/docs/api/agents/exportAuditLogs Description: Streams the project's agent audit entries as a CSV file, newest first, honoring the same credential, event, decision, source and date-range filters as the list endpoint. The full filtered set is streamed (no pagination); the result is suitable for spreadsheets, SIEM ingestion, and compliance archives. --- # Get an agent credential URL: https://pgbeam.com/docs/api/agents/getAgentCredential Description: Returns a single agent credential. Secrets are never included. --- # Break down project usage by agent credential URL: https://pgbeam.com/docs/api/agents/getAgentUsageBreakdown Description: Aggregates the audit trail into per-agent usage for a window: statements by decision, rows and bytes returned, the cache outcome breakdown, and latency percentiles. Read-only, derived entirely from entries the gateway already records. Grouped by credential, not by session. `session_id` is 32 bits of randomness minted per connection, so it identifies a connection rather than an agent or a run, and at scale it collides; the credential is the only stable identity in the trail. This endpoint reports usage and deliberately attributes no dollar figure to an agent. Overage is computed on the organization's total against a plan limit, so no single agent causes it independently of the others, and any per-agent split of that bill is a policy choice rather than a measurement. The organization's limits and marginal rates are returned alongside the usage so a caller can apply its own policy, with both meanings of a zero limit already resolved. Three things are reported rather than assumed. Usage recorded against no credential is its own line, so agents plus unattributed equals totals exactly. Latency covers only entries that ran and carried a finite value: every refusal writes a literal zero because there was nothing to time, and counting those would drag an agent's percentiles toward zero in proportion to how often it was refused, so the heavily blocked agent would report the fastest queries. And gap markers left by undelivered entries set `complete` to false, since a total over a trail with holes in it is a floor, not a measurement. Both `start` and `end` are optional. Omitting `end` means now; omitting `start` means 30 days before the end. The window is half-open and is capped at 92 days, because this aggregate reads every row in the window on the request path and an unbounded one would sort a year of latencies per group. `requested_start` and `requested_end` echo the window that was actually used, so a caller that pinned neither still knows what the totals cover. --- # Summarize one agent session URL: https://pgbeam.com/docs/api/agents/getAuditSessionSummary Description: Groups a session's audit entries into one deterministic summary: the credentials and origins involved, the window it spans, how many statements were allowed, blocked, masked and truncated, the rows and bytes it moved, and the tables it read, wrote and was refused. No model is involved, so the same entries always summarize the same way. Returns metadata only (table names and counts), never row values, and requires the same audit:read permission the list and export endpoints do. --- # List agent credentials URL: https://pgbeam.com/docs/api/agents/listAgentCredentials Description: Lists agent credentials for the project. Secrets are never returned. --- # List agent audit logs URL: https://pgbeam.com/docs/api/agents/listAuditLogs Description: Returns agent statement audit entries for the project, newest first, with optional credential, event, decision, source and date-range filters. --- # Revoke an agent credential URL: https://pgbeam.com/docs/api/agents/revokeAgentCredential Description: Permanently revokes the credential and drops any live connections. --- # Rotate an agent credential's secrets URL: https://pgbeam.com/docs/api/agents/rotateAgentCredential Description: Generates a new Postgres password and MCP token for the credential in place, keeping the same id, username, name, and policy. Live connections using the old password are dropped within seconds. The new secrets are returned once and cannot be retrieved again. --- # Enable or disable an agent credential URL: https://pgbeam.com/docs/api/agents/updateAgentCredentialStatus Description: Toggles the kill-switch. Disabling drops live connections within seconds. --- # Verify the tamper-evident audit chain URL: https://pgbeam.com/docs/api/agents/verifyAuditChain Description: Recomputes the project's audit hash chain over an optional time range and reports whether it is intact. Each audit entry is linked to its predecessor with a SHA-256 hash, so editing or deleting any row breaks the chain. On a break, the response reports the first sequence number where a tampered or deleted entry was detected. Requires the same audit:read permission as the list and export endpoints. --- # Get organization plan URL: https://pgbeam.com/docs/api/analytics/getOrganizationPlan Description: Returns the current plan and limits for the organization. --- # Get organization usage URL: https://pgbeam.com/docs/api/analytics/getOrganizationUsage Description: Returns daily usage data aggregated across all projects in the organization. --- # Get query insights for a project URL: https://pgbeam.com/docs/api/analytics/getProjectInsights Description: Returns aggregated query-level analytics for a project including top queries by count, cache hit/miss summary, and latency statistics. --- # Get project usage URL: https://pgbeam.com/docs/api/analytics/getProjectUsage Description: Returns daily usage data for a specific project, broken down by region. --- # Get Vercel Marketplace installation status URL: https://pgbeam.com/docs/api/analytics/getVercelInstallation Description: Returns the Vercel Marketplace installation for the organization, including its provisioned resources and their current-period usage. Returns 404 when the organization was not provisioned through the Vercel Marketplace. Powers the dashboard's Vercel integration page. --- # List available plans URL: https://pgbeam.com/docs/api/analytics/listPlans Description: Returns all available plan tiers with their limits and pricing. --- # Submit cancellation feedback URL: https://pgbeam.com/docs/api/analytics/submitCancellationFeedback Description: Records optional feedback when a user cancels their subscription. --- # Update spend limit URL: https://pgbeam.com/docs/api/analytics/updateSpendLimit Description: Sets the monthly spend limit for an organization. Null removes the limit. --- # List anomaly alerts URL: https://pgbeam.com/docs/api/anomalies/listAnomalyAlerts Description: Lists anomaly alerts for the project, newest first, optionally filtered by status. --- # Triage an anomaly alert URL: https://pgbeam.com/docs/api/anomalies/updateAnomalyAlert Description: Updates the triage status of an anomaly alert (acknowledge or resolve). --- # Approve a held statement URL: https://pgbeam.com/docs/api/approvals/approveApprovalRequest Description: Approves a pending approval request, releasing the held statement. --- # List approval requests URL: https://pgbeam.com/docs/api/approvals/listApprovalRequests Description: Lists approval requests for the project, newest first, optionally filtered by status. --- # Reject a held statement URL: https://pgbeam.com/docs/api/approvals/rejectApprovalRequest Description: Rejects a pending approval request, denying the held statement. --- # Discard a sandbox branch URL: https://pgbeam.com/docs/api/branches/discardDatabaseBranch Description: Marks an ephemeral sandbox branch as discarded for teardown. --- # List sandbox branches URL: https://pgbeam.com/docs/api/branches/listDatabaseBranches Description: Lists ephemeral sandbox branches for the project's databases. --- # Add a database URL: https://pgbeam.com/docs/api/databases/createDatabase Description: Registers a new upstream PostgreSQL database for the project. --- # Delete a database URL: https://pgbeam.com/docs/api/databases/deleteDatabase Description: Removes a database registration from the project. --- # Get a database URL: https://pgbeam.com/docs/api/databases/getDatabase Description: Returns a single database by ID. --- # Read a database's schema catalog URL: https://pgbeam.com/docs/api/databases/getSchemaCatalog Description: Connects to the upstream database read-only and returns its user relations (tables and views) and columns. Powers table/column autocomplete and view-aware warnings in the policy editor — relation kind distinguishes a view (whose masking/row-filters apply to the view itself, not its base tables) from a base table, and a per-column is_binary flag flags columns that mask to NULL. System schemas are excluded; nothing is persisted. --- # List databases URL: https://pgbeam.com/docs/api/databases/listDatabases Description: Lists all databases registered for the project. --- # Scan a database for likely-PII columns URL: https://pgbeam.com/docs/api/databases/scanDatabaseForPii Description: Connects to the upstream database read-only, inspects information_schema and samples column values against PII heuristics, and returns ranked masking suggestions. Suggestions are advisory — the operator reviews them and applies the ones they want into a policy profile's masking rules. Nothing is auto-applied. --- # Test database connection URL: https://pgbeam.com/docs/api/databases/testDatabaseConnection Description: Attempts to connect to the upstream database using the stored credentials and returns the result. --- # Update a database URL: https://pgbeam.com/docs/api/databases/updateDatabase Description: Partially updates a database connection. Only provided fields are modified. --- # Register a honeytoken URL: https://pgbeam.com/docs/api/honeytokens/createHoneytoken Description: Registers a decoy (canary) relation for the project. Any agent statement that references it is blocked and recorded as a canary_tripped audit event. --- # Delete a honeytoken URL: https://pgbeam.com/docs/api/honeytokens/deleteHoneytoken Description: Removes a honeytoken from the project. --- # Get a honeytoken URL: https://pgbeam.com/docs/api/honeytokens/getHoneytoken Description: Returns a single honeytoken by ID. --- # List honeytokens URL: https://pgbeam.com/docs/api/honeytokens/listHoneytokens Description: Lists the project's honeytokens. --- # Update a honeytoken URL: https://pgbeam.com/docs/api/honeytokens/updateHoneytoken Description: Updates a honeytoken's relation or action. --- # Handle a Slack support event URL: https://pgbeam.com/docs/api/internal/handleSlackSupportEvent Description: Receives a forwarded Slack event from the dashboard webhook handler and creates a support message. --- # MCP server (Streamable HTTP) URL: https://pgbeam.com/docs/api/mcp/mcpTransport Description: Model Context Protocol endpoint using the Streamable HTTP transport. Accepts JSON-RPC 2.0 requests and exposes every public API operation as an MCP tool. Use this with any MCP-compatible client (Claude Code, Cursor, Windsurf, custom agents) to let AI assistants manage PgBeam resources. **Transport:** Streamable HTTP (MCP spec 2025-03-26) **Protocol:** JSON-RPC 2.0 **Methods:** `initialize`, `tools/list`, `tools/call`, `ping` Prefer the CLI (`pgbeam mcp`) for local stdio transport. Use this endpoint for remote or server-to-server MCP integration. --- # Lint a migration URL: https://pgbeam.com/docs/api/migrations/lintMigration Description: Analyzes a migration script for unsafe schema changes and returns findings. --- # Issue a self-host enrollment token URL: https://pgbeam.com/docs/api/platform/createSelfHostEnrollment Description: Issues an enrollment token a self-hosted (BYOC) proxy uses to authenticate to the control plane's config/audit gRPC stream. The token is returned once and cannot be retrieved again. Requires the Scale or enterprise plan. --- # Health check URL: https://pgbeam.com/docs/api/platform/getHealth Description: Returns the health status of the API server. --- # List available regions URL: https://pgbeam.com/docs/api/platform/listRegions Description: Returns all active data plane regions. --- # List self-host enrollments URL: https://pgbeam.com/docs/api/platform/listSelfHostEnrollments Description: Lists an organization's self-host enrollments. Tokens are never returned. --- # Revoke a self-host enrollment URL: https://pgbeam.com/docs/api/platform/revokeSelfHostEnrollment Description: Revokes an enrollment so its token can no longer authenticate a proxy. Connected proxies keep their last-known config until they reconnect. --- # Rotate a self-host enrollment token URL: https://pgbeam.com/docs/api/platform/rotateSelfHostEnrollment Description: Mints a new enrollment token in place, keeping the same enrollment id, metadata, and expiry. The swap is atomic: the old token stops authenticating new proxy connections the moment this call returns. An already-connected proxy keeps its existing gRPC streams until it disconnects, then must present the new token to reconnect. The new token is returned once and cannot be retrieved again. --- # Create a policy profile URL: https://pgbeam.com/docs/api/policies/createPolicyProfile Description: Creates a policy profile that can be attached to agent credentials. --- # Delete a policy profile URL: https://pgbeam.com/docs/api/policies/deletePolicyProfile Description: Deletes a policy profile. Fails if agent credentials still reference it. --- # Dry-eval a policy against a SQL statement URL: https://pgbeam.com/docs/api/policies/dryEvalPolicy Description: Evaluates a single SQL statement against a policy (either a draft policy supplied inline or an existing policy referenced by id) and returns the decision the proxy would make: allow, block, mask, or row-filter. The evaluation reuses the data plane's own policy engine (the same parser, allow/block rules, row-filter rewriter, and masking analysis enforced on live agent sessions), so a what-if verdict matches real enforcement. Stateful checks a single-statement preview cannot model (per-region query and egress budgets, human approvals, and rollback/sandbox write routing) are reported as informational notes, not verdicts. This is a pure compute endpoint; it does not connect to the upstream database and persists nothing. --- # Get a policy profile URL: https://pgbeam.com/docs/api/policies/getPolicyProfile Description: Returns a single policy profile by ID. --- # List policy profiles URL: https://pgbeam.com/docs/api/policies/listPolicyProfiles Description: Lists all policy profiles for the project. --- # Recommend a least-privilege policy from recorded traffic URL: https://pgbeam.com/docs/api/policies/recommendAgentPolicy Description: Derives the tightest policy that would still pass every statement this agent credential has legitimately run, using its recorded audit history over a lookback window (default 30 days). The candidate's table allowlist is the union of relations actually referenced, its statement-kind allow set is the observed set, it downgrades to read-only when no writes were seen, and its max_rows ceiling comes from an observed high-percentile row count. The candidate is proven safe by replaying it through the data plane's own policy engine against the same history: a good recommendation has replay.summary.newly_blocked == 0. This endpoint is advisory only. It reads the audit log, never connects to the upstream database, and never creates, updates, or mutates any policy or credential; the operator loads the candidate into the editor and saves it themselves. --- # Replay recorded agent traffic against a policy URL: https://pgbeam.com/docs/api/policies/replayPolicy Description: Replays the project's recorded agent audit traffic against a candidate policy (either a draft supplied inline or an existing policy referenced by id) and reports what would change: which queries that ran would now be blocked, which blocked queries would now be permitted, and which results would be masked or row-filtered. Traffic is deduplicated by normalized query shape, newest first, and every statement is evaluated through the data plane's own policy engine, so the verdicts match real enforcement. Stateful checks (budgets, approvals, write-mode routing) are reported as informational notes on each result, not verdicts. This endpoint reads only the audit log; it never connects to the upstream database and persists nothing. --- # Update a policy profile URL: https://pgbeam.com/docs/api/policies/updatePolicyProfile Description: Updates a policy profile. Changes hot-reload to active agent sessions. --- # Add a custom domain URL: https://pgbeam.com/docs/api/projects/createCustomDomain Description: Registers a new custom domain for the project. Returns DNS verification instructions. Requires a Scale or Enterprise plan. --- # Create a project URL: https://pgbeam.com/docs/api/projects/createProject Description: Creates a new project within the specified organization. --- # Add a replica URL: https://pgbeam.com/docs/api/projects/createReplica Description: Adds a read replica to a database. --- # Delete a custom domain URL: https://pgbeam.com/docs/api/projects/deleteCustomDomain Description: Removes a custom domain from the project and revokes its TLS certificate. --- # Delete a project URL: https://pgbeam.com/docs/api/projects/deleteProject Description: Soft-deletes a project and all associated databases. --- # Delete a replica URL: https://pgbeam.com/docs/api/projects/deleteReplica Description: Removes a read replica from a database. --- # Get a project URL: https://pgbeam.com/docs/api/projects/getProject Description: Returns a single project by ID. --- # Get project metrics URL: https://pgbeam.com/docs/api/projects/getProjectMetrics Description: Returns recent project metrics snapshots, optionally filtered by region. --- # List cache rules URL: https://pgbeam.com/docs/api/projects/listCacheRules Description: Returns the cache rules for a database, showing all observed query shapes with their stats and cache recommendations. --- # List custom domains URL: https://pgbeam.com/docs/api/projects/listCustomDomains Description: Lists all custom domains registered for the project. --- # List projects URL: https://pgbeam.com/docs/api/projects/listProjects Description: Lists projects filtered by organization. Requires org_id query parameter. --- # List replicas URL: https://pgbeam.com/docs/api/projects/listReplicas Description: Lists all read replicas for a database. --- # Update cache rule URL: https://pgbeam.com/docs/api/projects/updateCacheRule Description: Enable or disable caching for a specific query shape, with optional TTL and SWR overrides. Requires the query to exist in the cache rules. --- # Update a project URL: https://pgbeam.com/docs/api/projects/updateProject Description: Partially updates a project. Only provided fields are modified. --- # Verify custom domain DNS URL: https://pgbeam.com/docs/api/projects/verifyCustomDomain Description: Checks DNS TXT record to verify domain ownership. Updates domain status on success. Requires a Scale or Enterprise plan. --- # Delete a schema annotation URL: https://pgbeam.com/docs/api/schemaannotations/deleteSchemaAnnotation Description: Removes a single annotation identified by its natural key. Omit column_name to delete a table-level annotation, and omit schema_name to match the unqualified form. --- # List schema annotations URL: https://pgbeam.com/docs/api/schemaannotations/listSchemaAnnotations Description: Lists the project's human-written table and column descriptions. These are surfaced to connected agents through the MCP schema catalog. --- # Create or replace a schema annotation URL: https://pgbeam.com/docs/api/schemaannotations/putSchemaAnnotation Description: Attaches an operator-written description to a table (omit column_name) or a column. Keyed by (schema_name, table_name, column_name); an existing annotation with the same key is replaced. --- # Create a support case URL: https://pgbeam.com/docs/api/support/createSupportCase Description: Creates a new support case with an initial message. --- # Add a message to a support case URL: https://pgbeam.com/docs/api/support/createSupportMessage Description: Adds a new message to an existing support case thread. --- # Get a support case URL: https://pgbeam.com/docs/api/support/getSupportCase Description: Returns a support case with all its messages. --- # List support cases URL: https://pgbeam.com/docs/api/support/listSupportCases Description: Lists support cases for the organization with optional status and search filters. --- # Update a support case URL: https://pgbeam.com/docs/api/support/updateSupportCase Description: Updates the status of a support case (close or reopen). --- # Create a webhook endpoint URL: https://pgbeam.com/docs/api/webhooks/createWebhookEndpoint Description: Creates a webhook endpoint that receives project event deliveries. --- # Delete a webhook endpoint URL: https://pgbeam.com/docs/api/webhooks/deleteWebhookEndpoint Description: Deletes a webhook endpoint and its pending deliveries. --- # Get a webhook endpoint URL: https://pgbeam.com/docs/api/webhooks/getWebhookEndpoint Description: Returns a single webhook endpoint by ID. --- # List webhook endpoints URL: https://pgbeam.com/docs/api/webhooks/listWebhookEndpoints Description: Lists webhook endpoints for the project. --- # Send a test event URL: https://pgbeam.com/docs/api/webhooks/testWebhookEndpoint Description: Enqueues a test event delivery to the webhook endpoint. --- # Update a webhook endpoint URL: https://pgbeam.com/docs/api/webhooks/updateWebhookEndpoint Description: Updates a webhook endpoint. --- # account export URL: https://pgbeam.com/docs/cli/account/export Description: Export account data (GDPR/CCPA) Export all account data as required by GDPR and CCPA regulations. Includes your user profile, organizations, projects, databases, active sessions, and audit logs. Use `--file` to write the full export to a JSON file, or `--json` to print the full export to stdout. ## Usage ## Options Option Description Required Default `--file ` Write the full export to a JSON file at this path instead of printing to stdout No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Without `--file` or `--json`, displays a summary showing counts of organizations, projects, databases, sessions, and audit logs. With `--file`, writes the full JSON export to the specified path. With `--json`, outputs the complete export object. --- # agents create URL: https://pgbeam.com/docs/cli/agents/create Description: Issue a new agent credential Issue a scoped Postgres login and hosted MCP token for an AI agent. The connection string and MCP token are shown once and cannot be retrieved again. Store them securely. A ready-to-paste MCP client config (Claude Code, Claude Desktop, Cursor, VS Code, Cline, or Windsurf) is printed alongside the secrets. ## Usage ## Options Option Description Required Default `--name ` Human-readable label for the credential Yes - `--policy ` Policy profile ID to enforce Yes - `--client ` MCP client to emit config for: claude (default), claude-desktop, cursor, vscode, cline, windsurf, or all No `claude` `--expires ` Credential lifetime: a duration like 30d/12h/90m, or an absolute ISO 8601 timestamp. Omit for no expiry. No - `--principal-type ` Whether the credential represents an autonomous agent (default) or a human operator: agent or human No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the connection string, MCP URL, MCP token, and a ready-to-paste MCP client config once. With --json, returns the full secrets object. --- # agents disable URL: https://pgbeam.com/docs/cli/agents/disable Description: Kill-switch an agent credential (reversible) Disable an agent credential as a reversible kill-switch. Live connections using it are dropped within seconds and new connections are rejected until the credential is re-enabled with `pgbeam agents enable`. Unlike `revoke`, this does not permanently destroy the credential. A confirmation prompt is shown unless `--yes` is passed. ## Usage ## Options Option Description Required Default `` Agent credential ID Yes - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Confirms the credential was disabled. --- # agents enable URL: https://pgbeam.com/docs/cli/agents/enable Description: Re-enable a disabled agent credential Re-enable an agent credential that was previously disabled with `pgbeam agents disable`. New connections using it are accepted again, subject to its policy profile. ## Usage ## Options Option Description Required Default `` Agent credential ID Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Confirms the credential was enabled. --- # agents inspect URL: https://pgbeam.com/docs/cli/agents/inspect Description: Show what an agent credential can actually do Fetch an agent credential together with the policy profile attached to it and print one capability card: whether the credential can connect at all, which statement kinds it can run, which relations it can reach, which columns come back masked, its budgets and caps, and how its writes are handled. The card resolves the two records against each other the way the proxy does, so it reports the effective answer rather than the raw fields: a read-only credential that lists `update` in its statement allowlist is still shown as blocked, because access\_mode is a ceiling the allowlist cannot lift. The same static checks `pgbeam policies lint` runs are appended, so a credential attached to a risky policy says so here. Read-only: it fetches two records and computes the rest offline. Use `pgbeam agents show` for the raw credential record. ## Usage ## Options Option Description Required Default `` Agent credential ID Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the capability card: credential state, effective statement kinds, reachable relations, masked columns, row filters, budgets, write handling, the non-configurable safety floor, and any policy lint findings. With --json, returns the full card object including a per-kind statement verdict list and the lint findings with their summary. --- # agents list URL: https://pgbeam.com/docs/cli/agents/list Description: List agent credentials Lists agent credentials for the project. Secrets are never returned. ## Usage ## Options Option Description Required Default `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # agents mcp-config URL: https://pgbeam.com/docs/cli/agents/mcp-config Description: Emit ready-to-paste MCP client config from a credential's secrets Render the per-client MCP configuration (Claude Code, Claude Desktop, Cursor, VS Code, Cline, Windsurf) for the hosted agent-database MCP endpoint, given a credential's MCP URL and token. Because secrets are shown only once at creation, pass the URL + token directly (--url/--mcp-token), pipe the JSON output of `agents create --json` / `agents rotate --json` with --from-json, or read it from a saved file with --from-file. Claude Desktop, Cline and Windsurf each keep one config file per machine rather than one per project, so --write prints those with their per-OS path instead of overwriting them: merge the entry in by hand. Claude Desktop also cannot address a remote URL directly, so its config is an `mcp-remote` bridge. ## Usage ## Options Option Description Required Default `--url ` Hosted MCP URL (the mcp\_url from create/rotate) No - `--mcp-token ` Bearer token for the MCP endpoint (the mcp\_token from create/rotate) No - `--from-json` Read mcp\_url + mcp\_token from an `agents create --json` blob piped on stdin. No `false` `--from-file ` Read mcp\_url + mcp\_token from an `agents create --json` blob saved to this file. No - `--client ` MCP client: claude (default), claude-desktop, cursor, vscode, cline, windsurf, or all No `claude` `--write` Write each client's config to its conventional file path instead of stdout No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the MCP config block(s). With --json, returns a structured array of \{ client, file, config }. With --write, writes each project-scoped client's config to its conventional file path; machine-wide files (Claude Desktop, Cline, Windsurf) are printed with their per-OS location instead of being overwritten. --- # agents recommend-policy URL: https://pgbeam.com/docs/cli/agents/recommend-policy Description: Recommend a least-privilege policy from recorded traffic Derives the tightest policy that would still pass every statement this agent credential has legitimately run, using its recorded audit history over a lookback window (default 30 days). The candidate's table allowlist is the union of relations actually referenced, its statement-kind allow set is the observed set, it downgrades to read-only when no writes were seen, and its max\_rows ceiling comes from an observed high-percentile row count. The candidate is proven safe by replaying it through the data plane's own policy engine against the same history: a good recommendation has replay.summary.newly\_blocked == 0. This endpoint is advisory only. It reads the audit log, never connects to the upstream database, and never creates, updates, or mutates any policy or credential; the operator loads the candidate into the editor and saves it themselves. ## Usage ## Options Option Description Required Default `` Yes - `--lookback-days ` How many days of recorded audit history to analyze. No - `--limit ` Maximum number of distinct query shapes to analyze and replay, newest first. Traffic is deduplicated by normalized query hash. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # agents revoke URL: https://pgbeam.com/docs/cli/agents/revoke Description: Revoke an agent credential Permanently revokes the credential and drops any live connections. ## Usage ## Options Option Description Required Default `` Yes - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # agents rotate URL: https://pgbeam.com/docs/cli/agents/rotate Description: Rotate an agent credential's secrets Generate a new Postgres password and MCP token for an existing credential, keeping its id, username, name, and policy. Connections using the old password are dropped within seconds. The new secrets are shown once and cannot be retrieved again — update your agent before its next call. A ready-to-paste MCP client config is printed alongside the secrets. ## Usage ## Options Option Description Required Default `` Agent credential ID Yes - `--client ` MCP client to emit config for: claude (default), claude-desktop, cursor, vscode, cline, windsurf, or all No `claude` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the new connection string, MCP URL, MCP token, and a ready-to-paste MCP client config once. With --json, returns the full secrets object. --- # agents show URL: https://pgbeam.com/docs/cli/agents/show Description: Get an agent credential Returns a single agent credential. Secrets are never included. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # agents usage URL: https://pgbeam.com/docs/cli/agents/usage Description: Break down project usage by agent credential Aggregate the audit trail into per-agent usage for a window: statements by decision, rows and bytes returned, the cache outcome breakdown, and latency percentiles. Without --start and --end the window is the last 30 days, and it cannot exceed 92 days because the report reads every entry in it. Grouped by credential, not by session, because a session ID identifies one connection rather than an agent or a run. Usage recorded against no credential is reported as its own line rather than dropped, so the agent lines plus unattributed always equal the totals. The command reports usage and prices nothing: overage is computed on the organization's total against a plan limit, so no single agent causes it independently of the others. The plan's limits and marginal rates are included in --json output for a caller that wants to apply its own pricing policy. ## Usage ## Options Option Description Required Default `--start ` Only entries at or after this ISO 8601 timestamp (inclusive lower bound) No - `--end ` Only entries strictly older than this ISO 8601 timestamp (upper bound) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints one line per agent credential with statement counts by decision, rows and bytes returned, and latency percentiles, followed by the unattributed line and the totals. Warns when the trail lost entries in the window, because the totals are then a floor rather than a measurement. --- # analytics insights URL: https://pgbeam.com/docs/cli/analytics/insights Description: Show project query insights Display query performance insights for the linked project, including cache hit rate, average and P99 latency, and the top queries by call count. Use `--range` to adjust the time window. ## Usage ## Options Option Description Required Default `--range ` Time window for insights: 1h, 6h, 24h, or 7d No `24h` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays cache hit rate, average latency, and P99 latency, followed by a table of top queries with columns: Query (truncated), Count, Avg (ms), and Cache Hits. With `--json`, returns the full insights response. --- # analytics metrics URL: https://pgbeam.com/docs/cli/analytics/metrics Description: Show project metrics Display real-time performance metrics for the linked project, including query counts, cache hits, active connections, and latency percentiles. Results are broken down by region. Use `--limit` to control how many snapshots to return and `--region` to filter by a specific region. ## Usage ## Options Option Description Required Default `--limit ` Maximum number of metric snapshots to return No `10` `--region ` Filter results to a specific region (e.g. us-east-1) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: Region, Queries, Cache Hits, Connections, Avg (ms), and P99 (ms). With `--json`, returns the full metrics snapshot array. --- # analytics plans URL: https://pgbeam.com/docs/cli/analytics/plans Description: List available plans List all available PgBeam subscription plans with their pricing and resource limits. Use this to compare plans before upgrading or to check what limits apply to each tier. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: Plan, Label, Price, Projects, Databases, Connections, and Queries/Day. With `--json`, returns the full plans array from the API. --- # analytics spend-limit URL: https://pgbeam.com/docs/cli/analytics/spend-limit Description: Set or remove the organization monthly spend cap Set a monthly USD spend cap for the active organization, or remove it with `--remove`. When the cap is reached, usage-based features are paused until the next billing period. Pass the amount in dollars (e.g. 250 for $250/mo). ## Usage ## Options Option Description Required Default `` Monthly spend cap in USD (e.g. 250). Omit when using --remove. No - `--remove` Remove the spend cap entirely No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Confirms the new spend cap (or its removal) and prints the current value. With `--json`, returns the updated organization plan object. --- # annotations delete URL: https://pgbeam.com/docs/cli/annotations/delete Description: Delete a schema annotation Removes a single annotation identified by its natural key. Omit column\_name to delete a table-level annotation, and omit schema\_name to match the unqualified form. ## Usage ## Options Option Description Required Default `--table-name ` Relation (table or view) the annotation describes. Yes - `--schema-name ` Optional schema. Omit to match the unqualified form. No - `--column-name ` Optional column. Omit to delete a table-level annotation. No - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # annotations list URL: https://pgbeam.com/docs/cli/annotations/list Description: List schema annotations Lists the project's human-written table and column descriptions. These are surfaced to connected agents through the MCP schema catalog. ## Usage ## Options Option Description Required Default `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # annotations set URL: https://pgbeam.com/docs/cli/annotations/set Description: Create or replace a schema annotation Attaches an operator-written description to a table (omit column\_name) or a column. Keyed by (schema\_name, table\_name, column\_name); an existing annotation with the same key is replaced. ## Usage ## Options Option Description Required Default `--schema-name ` Optional schema. Null or empty matches the unqualified form. No - `--table-name ` Relation (table or view) the annotation describes. Yes - `--column-name ` Optional column. Null describes the table itself. No - `--description ` The operator-written description text. Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # anomalies ack URL: https://pgbeam.com/docs/cli/anomalies/ack Description: Acknowledge one or more anomaly alerts Acknowledge anomaly-detection alerts. Pass one or more alert IDs, or use `--all` to acknowledge every open alert for the linked project (mirrors the dashboard's bulk acknowledge). Marks each alert as acknowledged, indicating it has been seen and is being handled. ## Usage ## Options Option Description Required Default `` Anomaly alert ID(s) No - `--all` Acknowledge every open anomaly alert in the project No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Confirms each anomaly was acknowledged; bulk runs end with an acknowledged/failed summary and exit non-zero if any update failed. --- # anomalies list URL: https://pgbeam.com/docs/cli/anomalies/list Description: List anomaly-detection alerts for a project List anomaly-detection alerts for the linked project. Shows each alert's ID, severity, kind, title, status, and creation time. Use `--status` to filter by open, acknowledged, or resolved alerts. ## Usage ## Options Option Description Required Default `--status ` Filter by status: open, acknowledged, or resolved No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: ID, Severity, Kind, Title, Status, and Created. With `--json`, returns the full list of anomaly alerts. --- # anomalies resolve URL: https://pgbeam.com/docs/cli/anomalies/resolve Description: Resolve an anomaly alert Resolve an anomaly-detection alert by ID. Marks the alert as resolved, indicating the underlying issue has been addressed. ## Usage ## Options Option Description Required Default `` Anomaly alert ID Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Confirms the anomaly was resolved. --- # api ls URL: https://pgbeam.com/docs/cli/api/ls Description: List all API endpoints List all available PgBeam API endpoints, grouped by tag. Shows the HTTP method, path, and operation name for each endpoint. Useful for discovering API operations before using `pgbeam api request` or `pgbeam api schema`. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays endpoints grouped by tag, with each entry showing the HTTP method, path, and operation name. With `--json`, returns an array of endpoint objects with method, path, tag, and operation fields. --- # api request URL: https://pgbeam.com/docs/cli/api/request Description: Make a raw API request Make a direct HTTP request to the PgBeam API. Supports path parameter interpolation — if the path matches a known API route template, path parameters are extracted automatically. Use `--data` (or `-d`) to send a JSON request body. Every request is authenticated via the active profile (or `--token` / `PGBEAM_API_KEY`), including reads like `/v1/regions`. ## Usage ## Options Option Description Required Default `` HTTP method: GET, POST, PATCH, PUT, or DELETE Yes - `` API path (e.g. /v1/projects, /v1/regions) Yes - `--data `, `-d` JSON request body to send with the request No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Outputs the API response as formatted JSON. Exits with a non-zero code on HTTP errors. --- # api schema URL: https://pgbeam.com/docs/cli/api/schema Description: Show operation schema Show the contract schema for an API operation: HTTP method and path, every parameter (name, location, required, type), the request body shape, and the success response shape. You can look up operations by their `tag.method` name (e.g. `projects.listProjects`), by operationId, or by route string. ## Usage ## Options Option Description Required Default `` Operation name in tag.method format (e.g. projects.listProjects), operationId, or route string Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays the operation, tag, HTTP method, path, parameters (name, location, required, type), request body shape, and response shape. With `--json`, returns the full operation schema object. --- # approvals approve URL: https://pgbeam.com/docs/cli/approvals/approve Description: Approve a held statement Approve a held statement approval request by ID. The statement is released for execution. Optionally attach a reason recorded in the audit trail. ## Usage ## Options Option Description Required Default `` Approval request ID Yes - `--reason ` Reason recorded in the audit trail No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Confirms the statement was approved. --- # approvals list URL: https://pgbeam.com/docs/cli/approvals/list Description: List statement approval requests for a project List human-in-the-loop statement approval requests for the linked project. Optionally filter by status. Shows each request's ID, statement kind, status, request time, and a truncated SQL preview. ## Usage ## Options Option Description Required Default `--status ` Filter by status (one of: pending, approved, rejected, expired, executed, failed) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: ID, Kind, Status, Requested, and SQL. --- # approvals reject URL: https://pgbeam.com/docs/cli/approvals/reject Description: Reject a held statement Reject a held statement approval request by ID. The statement is denied and will not execute. Optionally attach a reason recorded in the audit trail. ## Usage ## Options Option Description Required Default `` Approval request ID Yes - `--reason ` Reason recorded in the audit trail No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Confirms the statement was rejected. --- # audit export URL: https://pgbeam.com/docs/cli/audit/export Description: Export agent audit logs as CSV Stream the linked project's agent audit entries as a CSV file, newest first, honoring the same credential, event, decision, source, and date-range filters as `audit list`. The full filtered set is streamed (no pagination), suitable for spreadsheets, SIEM ingestion, and compliance archives. Writes to stdout by default, or to a file with `--output`. The API emits CSV only; the wire/mcp/rest/control-formatted views are selected with `--source`, not a separate output format. ## Usage ## Options Option Description Required Default `--credential ` Filter to one agent credential ID No - `--event ` Filter to one event type (e.g. blocked, masked, query) No - `--decision ` Coarse outcome filter: allow, block, mask, or truncate No - `--source ` Filter by statement origin: wire, mcp, rest, or control No - `--start ` Return entries at or after this ISO 8601 timestamp (inclusive lower bound) No - `--end ` Return entries strictly older than this ISO 8601 timestamp (upper bound) No - `--output `, `-o` Write the CSV to this file instead of stdout No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Writes CSV to stdout, or to the file named by --output (with a confirmation message). Columns include id, ts, event, source, credential\_id, decision\_rule, sql, and more. --- # audit list URL: https://pgbeam.com/docs/cli/audit/list Description: List agent audit log entries List agent statement audit entries for the linked project, newest first. Filter by credential or event type (e.g. blocked) to focus on policy violations. ## Usage ## Options Option Description Required Default `--credential ` Filter to one agent credential ID No - `--event ` Filter to one event type (e.g. blocked) No - `--limit ` Maximum entries to return (default 20) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: Time, Event, Kind, Rule, and SQL. --- # audit session URL: https://pgbeam.com/docs/cli/audit/session Description: Summarize one agent session's audit entries Group one session's audit entries into a single summary: the credentials and origins involved, the window it spans, how many statements were allowed, blocked, masked and truncated, the rows and bytes it moved, and the tables it read, wrote and was refused. Session IDs come from the session\_id field of `pgbeam audit list --json`. The summary is computed from the audit log with no model involved, so the same entries always summarize the same way, and it carries table names and counts only, never row values. A session ID is unique per connection within a proxy instance and not over time, so narrow a reused one with --start and --end. ## Usage ## Options Option Description Required Default `` Session ID from an audit entry Yes - `--start ` Only entries at or after this ISO 8601 timestamp (inclusive lower bound) No - `--end ` Only entries strictly older than this ISO 8601 timestamp (upper bound) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the session window, credentials and sources, the allowed/blocked/masked/truncated statement counts, rows and bytes returned, and the tables read, written, and blocked. --- # audit verify URL: https://pgbeam.com/docs/cli/audit/verify Description: Verify the tamper-evident audit chain Recomputes the project's audit hash chain over an optional time range and reports whether it is intact. Each audit entry is linked to its predecessor with a SHA-256 hash, so editing or deleting any row breaks the chain. On a break, the response reports the first sequence number where a tampered or deleted entry was detected. Requires the same audit:read permission as the list and export endpoints. ## Usage ## Options Option Description Required Default `--start ` Return entries at or after this timestamp (inclusive lower bound). No - `--end ` Return entries strictly older than this timestamp (cursor / upper bound). No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # auth list URL: https://pgbeam.com/docs/cli/auth/list Description: List authentication profiles List all saved authentication profiles with their method, organization, and email. The currently active profile is marked with an asterisk (`*`). If no profiles are configured, prints instructions to run `pgbeam auth login`. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: active indicator, profile name, auth method, organization ID, and email. With `--json`, returns an array of profile objects. --- # auth login URL: https://pgbeam.com/docs/cli/auth/login Description: Authenticate with PgBeam Authenticate with PgBeam to access your projects and databases. Login uses an API key, which you generate from the PgBeam dashboard under Settings > API Keys; running the command prompts you to paste it. The key is verified against the API before it is stored (an invalid key fails the login), and your organization is resolved automatically: a single visible organization is selected for you, multiple organizations prompt a pick. Credentials are stored in a local profile on disk (`~/.config/pgbeam/`). You can maintain multiple profiles for different environments using the `--profile` flag. ## Usage ## Options Option Description Required Default `--api-key` Authenticate with an API key (the default and only method) No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output On success, prints a confirmation with the authenticated profile name and the selected organization, ready for `pgbeam projects list`. The token is stored locally and used for all subsequent commands. A key the API rejects (401) is not stored and the command exits non-zero. --- # auth logout URL: https://pgbeam.com/docs/cli/auth/logout Description: Remove authentication profile Remove stored authentication credentials. By default, removes the currently active profile (or the one specified with `--profile`). Use `--all` to remove every saved profile at once. A confirmation prompt is shown before deletion unless `--yes` is passed. ## Usage ## Options Option Description Required Default `--all` Remove all saved profiles instead of just the active one No `false` `--yes`, `-y` Skip the confirmation prompt No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming which profile was removed (e.g. `Profile "default" removed.`). If `--all` is used, confirms all profiles were removed. --- # auth status URL: https://pgbeam.com/docs/cli/auth/status Description: Show current authentication status Display the credential the CLI would use (masked), where it came from (profile, flag, or environment), the authentication method, organization, and email. When the API is reachable, the credential is verified live with a cheap authenticated call; offline, the stored details are shown unverified. If not authenticated, prints a warning with instructions to log in. Also available as the `pgbeam whoami` alias. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays profile name (or credential source), method, masked key, email, organization, and live verification result. With `--json`, returns an object with `authenticated`, `verified`, `profile`, `source`, `method`, `key`, `orgId`, `orgName`, and `email` fields. Exits non-zero when the credential is missing or rejected by the API. --- # auth switch URL: https://pgbeam.com/docs/cli/auth/switch Description: Switch active authentication profile Switch the active authentication profile. If no profile name is provided, an interactive selector is shown listing all available profiles. The active profile determines which API token and organization are used for subsequent commands. ## Usage ## Options Option Description Required Default `` Name of the profile to switch to. If omitted, an interactive selector is shown. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a confirmation message (e.g. `Switched to profile "production".`). If the profile is not found, exits with an error. --- # whoami URL: https://pgbeam.com/docs/cli/auth/whoami Description: Show current user and organization info. Display the currently authenticated user and active organization. Alias for `pgbeam auth status`. ## Usage --- # branches discard URL: https://pgbeam.com/docs/cli/branches/discard Description: Discard a sandbox branch Marks an ephemeral sandbox branch as discarded for teardown. ## Usage ## Options Option Description Required Default `` Yes - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # branches list URL: https://pgbeam.com/docs/cli/branches/list Description: List sandbox branches Lists ephemeral sandbox branches for the project's databases. ## Usage ## Options Option Description Required Default `--status ` Filter to a single status. One of: pending, ready, error, discarded. No - `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # db add URL: https://pgbeam.com/docs/cli/db/add Description: Add a database connection Add a new database connection to the linked project. PgBeam will use these credentials to connect to your upstream PostgreSQL server. Without the required flags, the command runs interactively and prompts for host, name, username, password, and SSL mode. Advanced flags (role, pool region, query timeout, read routing, and cache/pool config) are optional and default to the platform defaults. After adding, use `pgbeam db test` to verify connectivity. ## Usage ## Options Option Description Required Default `--host ` Hostname or IP address of the PostgreSQL server No - `--port ` Port number of the PostgreSQL server No `5432` `--name ` Name of the database on the server No - `--username ` Username for authenticating with the database No - `--password ` Password for authenticating with the database No - `--ssl-mode ` SSL connection mode: disable, require, verify-ca, or verify-full No - `--role ` Database role: primary (receives writes) or replica (receives reads) No - `--pool-region ` Region where the connection pool is maintained (near the database). Empty means direct connection. No - `--query-timeout-ms ` Query timeout in milliseconds. 0 means disabled (default). No - `--auto-read-routing` Auto-route SELECT queries to read replicas No - `--cache-enabled` Enable query result caching for this database No - `--cache-ttl ` Time-to-live for cached query results, in seconds No - `--pool-mode ` Connection pool mode: transaction, session, or statement No - `--pool-size ` Maximum number of connections in the pool No - `--min-pool-size ` Minimum number of idle connections maintained in the pool No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the new database ID, name, and host:port. Suggests running `pgbeam db test ` to verify the connection. With `--json`, returns the full database object. --- # db delete URL: https://pgbeam.com/docs/cli/db/delete Description: Delete a database Removes a database registration from the project. ## Usage ## Options Option Description Required Default `` Yes - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # db inspect URL: https://pgbeam.com/docs/cli/db/inspect Description: Get a database Returns a single database by ID. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # db list URL: https://pgbeam.com/docs/cli/db/list Description: List databases Lists all databases registered for the project. ## Usage ## Options Option Description Required Default `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # db scan-pii URL: https://pgbeam.com/docs/cli/db/scan-pii Description: Scan a database for likely-PII columns Connects to the upstream database read-only, inspects information\_schema and samples column values against PII heuristics, and returns ranked masking suggestions. Suggestions are advisory — the operator reviews them and applies the ones they want into a policy profile's masking rules. Nothing is auto-applied. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # db schema-catalog URL: https://pgbeam.com/docs/cli/db/schema-catalog Description: Read a database's schema catalog Connects to the upstream database read-only and returns its user relations (tables and views) and columns. Powers table/column autocomplete and view-aware warnings in the policy editor — relation kind distinguishes a view (whose masking/row-filters apply to the view itself, not its base tables) from a base table, and a per-column is\_binary flag flags columns that mask to NULL. System schemas are excluded; nothing is persisted. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # db test URL: https://pgbeam.com/docs/cli/db/test Description: Test database connection Attempts to connect to the upstream database using the stored credentials and returns the result. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # db update URL: https://pgbeam.com/docs/cli/db/update Description: Update database settings Update the configuration of an existing database connection. Supports changing the display name, cache settings (enable/disable, TTL), and connection pool settings (mode, size). At least one update flag must be provided. Current settings are preserved for any flag not specified. ## Usage ## Options Option Description Required Default `` ID of the database to update Yes - `--name ` New display name for the database No - `--cache-enabled` Enable or disable query result caching for this database No - `--cache-ttl ` Time-to-live for cached query results, in seconds No - `--pool-mode ` Connection pool mode: transaction, session, or statement No - `--pool-size ` Maximum number of connections in the pool (default: 10) No - `--min-pool-size ` Minimum number of idle connections maintained in the pool (default: 1) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming the database was updated. With `--json`, returns the updated database object. --- # honeytokens create URL: https://pgbeam.com/docs/cli/honeytokens/create Description: Register a honeytoken Registers a decoy (canary) relation for the project. Any agent statement that references it is blocked and recorded as a canary\_tripped audit event. ## Usage ## Options Option Description Required Default `--schema-name ` Optional schema. Null or empty matches the unqualified/public form. No - `--relation-name ` Relation (table or view) name of the decoy. Yes - `--action ` Response when the honeytoken is tripped. One of: audit\_only, kill. Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # honeytokens delete URL: https://pgbeam.com/docs/cli/honeytokens/delete Description: Delete a honeytoken Removes a honeytoken from the project. ## Usage ## Options Option Description Required Default `` Yes - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # honeytokens list URL: https://pgbeam.com/docs/cli/honeytokens/list Description: List honeytokens Lists the project's honeytokens. ## Usage ## Options Option Description Required Default `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # honeytokens show URL: https://pgbeam.com/docs/cli/honeytokens/show Description: Get a honeytoken Returns a single honeytoken by ID. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # honeytokens update URL: https://pgbeam.com/docs/cli/honeytokens/update Description: Update a honeytoken Updates a honeytoken's relation or action. ## Usage ## Options Option Description Required Default `` Yes - `--schema-name ` Optional schema. Null or empty matches the unqualified/public form. No - `--relation-name ` Relation (table or view) name of the decoy. Yes - `--action ` Response when the honeytoken is tripped. One of: audit\_only, kill. Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # migrations lint URL: https://pgbeam.com/docs/cli/migrations/lint Description: Lint a migration for unsafe DDL Lint migration SQL for unsafe DDL patterns before applying it. Detects operations that can lock tables, break replication, or cause downtime (such as adding NOT NULL columns without a default, dropping columns, or rewriting large tables) and reports findings with severity, the offending statement, and a remediation hint. Provide SQL inline as an argument or from a file with --file. ## Usage ## Options Option Description Required Default `` Inline SQL to lint No - `--file ` Path to a .sql file to lint No - `--database ` Database ID to scope the lint to No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints whether the migration is safe and lists any findings with their severity, rule, message, hint, and offending statement. With `--json`, returns an object with `safe` and `findings`. --- # orgs activity URL: https://pgbeam.com/docs/cli/orgs/activity Description: Show organization activity feed. Show the recent activity feed for the active organization, including member actions and configuration changes. ## Usage ## Examples --- # orgs list URL: https://pgbeam.com/docs/cli/orgs/list Description: List organizations visible to your credential List the organizations your credential can access, fetched live from the API. An organization-scoped key (pbo\_) shows exactly its own organization; an account key or session shows every organization you are a member of. The active organization is marked. When the API is unreachable, falls back to the organizations recorded in your locally saved profiles. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: active indicator, organization ID, name, slug, and your role. With `--json`, returns an array of organization entries. --- # orgs plan URL: https://pgbeam.com/docs/cli/orgs/plan Description: Show organization plan details Display the subscription plan and resource limits for the active organization. Shows the plan name, subscription status, billing period, and limits for projects, databases, connections, and queries. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays the organization ID, plan name, subscription status, period end date, and a breakdown of limits (projects, databases, connections, queries/day, queries/sec). With `--json`, returns the full plan object. --- # orgs switch URL: https://pgbeam.com/docs/cli/orgs/switch Description: Switch active organization Switch the active organization for the current authentication profile. All subsequent commands that require an organization will use this org. If no org ID is provided, your organizations are fetched from the API and you pick one interactively (a single visible organization is selected automatically). When the API is unreachable, you are prompted to enter an ID by hand; copy it from the dashboard under Settings > Organization. ## Usage ## Options Option Description Required Default `` Organization ID to switch to. If omitted, you pick from a list. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a confirmation message (e.g. `Switched to organization org_xxx.`). --- # orgs usage URL: https://pgbeam.com/docs/cli/orgs/usage Description: Show organization usage Display aggregated usage metrics for the active organization over a date range. Shows daily breakdowns of total queries, cache hits, and data transferred across all projects. Defaults to the current calendar month if no date range is specified. ## Usage ## Options Option Description Required Default `--start-date ` Start of the date range in YYYY-MM-DD format. Defaults to the first day of the current month. No - `--end-date ` End of the date range in YYYY-MM-DD format. Defaults to today. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays total queries and data transferred, followed by a day-by-day table with columns: Day, Queries, Cache Hits, and Data. With `--json`, returns the full usage response. --- # platform health URL: https://pgbeam.com/docs/cli/platform/health Description: Check API health status Check the health status of the PgBeam API. Returns the API status and version. This is a public endpoint that does not require authentication. Useful for verifying connectivity and checking which API version is running. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays the API status (e.g. `ok`) and version number. With `--json`, returns the full health response object. --- # platform regions URL: https://pgbeam.com/docs/cli/platform/regions Description: List available regions List all available PgBeam data plane regions. Shows each region's ID, display name, and cloud provider. This is a public endpoint that does not require authentication. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: ID, Name, and Provider. With `--json`, returns the full regions array. --- # policies create URL: https://pgbeam.com/docs/cli/policies/create Description: Create a policy profile Create a policy profile. Provide a name and access mode, then author the rules with flags (`--allow`, `--deny`, `--mask`, budget flags, and the write-safety flags `--write-mode`, `--approval-mode`, `--approval-timeout-seconds`, `--approval-auto-max-rows`, `--migration-safety`) or pass a JSON file describing the full profile (statement rules, allow/deny lists, masking, budgets). Fields set via `--file` are overlaid by any individual flags. The resolved profile is validated against the API schema before anything is sent; `--dry-run` prints the resolved profile JSON without calling the API. ## Usage ## Options Option Description Required Default `--name ` Policy profile name Yes - `--mode ` Access mode: read\_only or read\_write No - `--write-mode ` How writes are handled: normal, rollback, or sandbox No - `--approval-mode ` Which statements need approval: off, writes, ddl, or all No - `--approval-timeout-seconds ` How long a held statement waits for a decision before expiring No - `--approval-auto-max-rows ` Statements touching at most this many rows are auto-approved (0 disables) No - `--migration-safety ` Migration safety mode: off, warn, or block No - `--table-allowlist ` Comma-separated relations to allow No - `--table-denylist ` Comma-separated relations to deny No - `--allow ` Relation to allowlist (repeatable, or comma-separated) No - `--deny ` Relation to denylist (repeatable, or comma-separated) No - `--mask ` Masking rule as table.column=kind, where kind is redact, null, or hash (repeatable) No - `--max-rows ` Max rows returned per query (0 means unlimited) No - `--max-affected-rows ` Hard cap on rows a single write may affect; over-cap writes are rolled back and blocked (0 means unlimited) No - `--budget-queries-per-hour ` Max queries per rolling hour (0 means unlimited) No - `--budget-queries-per-day ` Max queries per day (0 means unlimited) No - `--egress-bytes-per-day ` Per-day egress budget in bytes (0 means unlimited) No - `--statement-timeout-ms ` Upstream statement timeout for agent sessions (0 uses the project default) No - `--file ` Path to a JSON file with the full profile body No - `--dry-run` Print the resolved profile JSON that would be sent, without calling the API No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the created policy profile. With --dry-run, prints the resolved profile JSON that would be sent and exits without calling the API. --- # policies delete URL: https://pgbeam.com/docs/cli/policies/delete Description: Delete a policy profile Deletes a policy profile. Fails if agent credentials still reference it. ## Usage ## Options Option Description Required Default `` Yes - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # policies dry-eval URL: https://pgbeam.com/docs/cli/policies/dry-eval Description: Dry-eval a SQL statement against a policy Evaluate a single SQL statement against a policy and print the decision the proxy would make: allow, block, mask, or row-filter. Supply exactly one of `--policy` (an existing saved policy ID) or `--draft` (a JSON file describing an unsaved draft policy). The evaluation reuses the data plane's own policy engine, so a what-if verdict matches real enforcement. Stateful checks a single-statement preview cannot model (per-region budgets, approvals, write routing) are reported as informational notes. ## Usage ## Options Option Description Required Default `--sql ` The single SQL statement to evaluate Yes - `--policy ` ID of an existing saved policy to evaluate against No - `--draft ` Path to a JSON file with a draft policy body to evaluate against No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the verdict (allow/block/mask/row-filter), the rule, reason, any masked columns, injected row-filter predicate, and informational notes. With --json, returns the full result object. --- # policies lint URL: https://pgbeam.com/docs/cli/policies/lint Description: Check a policy profile for risky configuration Statically check a policy profile for risky combinations before you attach it to a credential, without running any SQL. Supply exactly one of `--policy` (an existing saved policy ID) or `--draft` (a JSON file describing an unsaved draft policy). The linter reasons about the policy's own shape: it flags read-write access with no table allowlist, writes that commit with no affected-row cap or approval, missing query budgets, PII masking with no read ceiling, masking or row-filter rules on tables the policy makes unreachable, write settings that are inert on a read-only policy, and redundant allow/deny overlaps. It complements `policies dry-eval` (a single statement) and `policies replay` (recorded traffic). Pass `--strict` to exit non-zero when any warning-or-worse finding is present, for use as a CI gate. ## Usage ## Options Option Description Required Default `--policy ` ID of an existing saved policy to lint No - `--draft ` Path to a JSON file with a draft policy body to lint No - `--strict` Exit non-zero when any warning-or-worse finding is present No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints each finding with its severity, code, message, and a suggested fix, then a summary count. With --json, returns \{ findings, summary }. With --strict, exits 1 when any warning or error finding is present. --- # policies list URL: https://pgbeam.com/docs/cli/policies/list Description: List policy profiles Lists all policy profiles for the project. ## Usage ## Options Option Description Required Default `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # policies replay URL: https://pgbeam.com/docs/cli/policies/replay Description: Replay recorded agent traffic against a policy Replay the project's recorded agent audit traffic against a candidate policy and print what would change: which queries that ran would now be blocked, which blocked queries would now be permitted, and which results would be masked or row-filtered. Supply exactly one of `--policy` (an existing saved policy ID) or `--draft` (a JSON file describing an unsaved draft policy). Traffic is deduplicated by normalized query shape, newest first, and every statement is evaluated through the data plane's own policy engine, so verdicts match real enforcement. The replay reads only the audit log; it never connects to the upstream database. By default it covers every credential in the project, including credentials bound to other policies, whose behaviour saving this candidate cannot change; pass `--bound-policy` to narrow it to the credentials a policy actually governs, which is usually the question you want answered before editing a live policy. ## Usage ## Options Option Description Required Default `--policy ` ID of an existing saved policy to replay against No - `--draft ` Path to a JSON file with a draft policy body to replay against No - `--credential ` Restrict the replay to traffic recorded for one agent credential No - `--bound-policy ` Restrict the replay to traffic from the credentials bound to this policy ID (mutually exclusive with --credential) No - `--start ` Start of the traffic window (RFC3339; default 7 days before the end) No - `--end ` End of the traffic window (RFC3339; default now) No - `--limit ` Maximum distinct queries to replay, newest first (1-500; default 200) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a summary (queries replayed, would-block/mask/row-filter counts, newly blocked and newly allowed changes) followed by the changed queries. With --json, returns the full result object including every per-query decision. --- # policies show URL: https://pgbeam.com/docs/cli/policies/show Description: Get a policy profile Returns a single policy profile by ID. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # policies update URL: https://pgbeam.com/docs/cli/policies/update Description: Update a policy profile Update a policy profile. Changes hot-reload to active agent sessions. Pass individual flags to change specific fields, or `--file` to supply the full profile body as JSON. Because the API replaces the whole profile, unspecified fields are read from the current profile first so single-flag edits are non-destructive. Fields set via `--file` are overlaid by any individual flags. The resolved profile is validated against the API schema before it is sent; `--dry-run` prints the resolved profile JSON without applying the update. ## Usage ## Options Option Description Required Default `` Policy profile ID Yes - `--name ` New policy profile name No - `--mode ` Access mode: read\_only or read\_write No - `--write-mode ` How writes are handled: normal, rollback, or sandbox No - `--approval-mode ` Which statements need approval: off, writes, ddl, or all No - `--approval-timeout-seconds ` How long a held statement waits for a decision before expiring No - `--approval-auto-max-rows ` Statements touching at most this many rows are auto-approved (0 disables) No - `--migration-safety ` Migration safety mode: off, warn, or block No - `--table-allowlist ` Comma-separated relations to allow (replaces the current list) No - `--table-denylist ` Comma-separated relations to deny (replaces the current list) No - `--allow ` Relation to allowlist (repeatable, or comma-separated; replaces the current list) No - `--deny ` Relation to denylist (repeatable, or comma-separated; replaces the current list) No - `--mask ` Masking rule as table.column=kind, where kind is redact, null, or hash (repeatable; replaces the current rules) No - `--max-rows ` Max rows returned per query (0 means unlimited) No - `--max-affected-rows ` Hard cap on rows a single write may affect; over-cap writes are rolled back and blocked (0 means unlimited) No - `--budget-queries-per-hour ` Max queries per rolling hour (0 means unlimited) No - `--budget-queries-per-day ` Max queries per day (0 means unlimited) No - `--egress-bytes-per-day ` Per-day egress budget in bytes (0 means unlimited) No - `--statement-timeout-ms ` Upstream statement timeout for agent sessions (0 uses the project default) No - `--file ` Path to a JSON file with the full profile body No - `--dry-run` Print the resolved profile JSON that would be sent, without applying the update No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message. With --json, returns the updated policy profile. --- # projects create URL: https://pgbeam.com/docs/cli/projects/create Description: Create a new project Create a new PgBeam project in your organization. A project groups one or more database connections under a single proxy endpoint. Without flags, the command runs interactively and prompts for all required values including the upstream database connection details and SSL mode. ## Usage ## Options Option Description Required Default `--name ` Display name for the project No - `--host ` Hostname or IP address of the upstream PostgreSQL server No - `--port ` Port number of the upstream PostgreSQL server No `5432` `--database ` Name of the database on the upstream server No - `--username ` Username for authenticating with the upstream database No - `--password ` Password for authenticating with the upstream database No - `--ssl-mode ` SSL connection mode: disable, require, verify-ca, or verify-full No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the new project ID, name, and database host. Suggests running `pgbeam link` as a next step. With `--json`, returns the full project and database objects. --- # projects delete URL: https://pgbeam.com/docs/cli/projects/delete Description: Delete a project Soft-deletes a project and all associated databases. ## Usage ## Options Option Description Required Default `` No - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # projects inspect URL: https://pgbeam.com/docs/cli/projects/inspect Description: Get a project Returns a single project by ID. ## Usage ## Options Option Description Required Default `` No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # link URL: https://pgbeam.com/docs/cli/projects/link Description: Link current directory to a PgBeam project Link the current working directory to a PgBeam project by creating a `.pgbeam` configuration file. This saves the project ID so subsequent commands (like `pgbeam db list` or `pgbeam projects inspect`) automatically use the linked project without requiring `--project`. An interactive selector is shown to choose from your organization's projects. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message with the linked project ID and suggests `pgbeam db list` as a next step. A `.pgbeam` file is created in the current directory. --- # projects list URL: https://pgbeam.com/docs/cli/projects/list Description: List projects Lists projects filtered by organization. Requires org\_id query parameter. ## Usage ## Options Option Description Required Default `--sort-by ` Sort field for projects list. One of: name, created\_at, active\_connections. No - `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # unlink URL: https://pgbeam.com/docs/cli/projects/unlink Description: Remove project link from current directory Remove the project link from the current directory by deleting the `.pgbeam` configuration file. After unlinking, commands that require a project will need the `--project` flag or a new `pgbeam link`. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message if a link was removed, or a warning if no project was linked. --- # projects update URL: https://pgbeam.com/docs/cli/projects/update Description: Update project settings Update the settings of an existing project. If no project ID is provided, uses the linked project in the current directory. At least one update flag must be provided. `--agents-disabled` is the project kill-switch: setting it true blocks ALL agent-credential connections (live sessions drop within seconds); passthrough/human connections are unaffected. `--allowed-cidrs` replaces the IP allowlist; pass an empty string to allow all. ## Usage ## Options Option Description Required Default `` Project ID to update. Uses the linked project if omitted. No - `--name ` New display name for the project No - `--description ` New project description No - `--tags ` Comma-separated labels (replaces the current set) No - `--status ` Project lifecycle status: active, suspended, or deleted No - `--allowed-cidrs ` Comma-separated CIDR ranges for the IP allowlist (replaces the current set). Pass an empty string to allow all. No - `--default-policy-profile-id ` Policy profile enforced on passthrough/human connections. Pass an empty string to clear. No - `--agents-disabled ` Project kill-switch. true blocks all agent-credential connections; false re-enables. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming the project was updated. With `--json`, returns the updated project object. --- # projects usage URL: https://pgbeam.com/docs/cli/projects/usage Description: Show project usage Display usage metrics for the linked project over a date range. Shows daily breakdowns of total queries, cache hits, and data transferred by region. Defaults to the current calendar month if no date range is specified. ## Usage ## Options Option Description Required Default `--start-date ` Start of the date range in YYYY-MM-DD format. Defaults to the first day of the current month. No - `--end-date ` End of the date range in YYYY-MM-DD format. Defaults to today. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays total queries and data transferred, followed by a day-by-day table with columns: Day, Region, Queries, Cache Hits, and Data. With `--json`, returns the full usage response from the API. --- # webhooks create URL: https://pgbeam.com/docs/cli/webhooks/create Description: Create a webhook endpoint Create a webhook endpoint for the linked project. PgBeam delivers event and audit notifications to the given URL using the selected format. Subscribe to specific event types with `--event` (repeatable or comma-separated); omit it to receive all events. ## Usage ## Options Option Description Required Default `` Destination URL for webhook deliveries. If omitted, you will be prompted. No - `--format ` Delivery format: json, splunk\_hec, datadog, or elastic. No `json` `--event ` Event type(s) to subscribe to. Comma-separated. Omit to receive all events. No - `--secret ` Shared secret used to sign webhook payloads. No - `--description ` Human-readable description for the webhook endpoint. No - `--disabled` Create the webhook in a disabled state. No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message with the new webhook ID and its URL. With `--json`, returns the full webhook object from the API. --- # webhooks delete URL: https://pgbeam.com/docs/cli/webhooks/delete Description: Delete a webhook endpoint Delete a webhook endpoint from the linked project. PgBeam stops delivering events to it immediately. This action cannot be undone. A confirmation prompt is shown unless `--yes` is passed. ## Usage ## Options Option Description Required Default `` ID of the webhook endpoint to delete Yes - `--yes`, `-y` Skip the confirmation prompt No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming the webhook was deleted. --- # webhooks list URL: https://pgbeam.com/docs/cli/webhooks/list Description: List webhook endpoints List all webhook endpoints configured for the linked project. Shows each endpoint's ID, URL, delivery format, enabled state, and subscribed event types. ## Usage All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: ID, URL, Format, Enabled (yes/no), and Events ('all' when no specific event types are set). With `--json`, returns the full webhook list from the API. --- # webhooks show URL: https://pgbeam.com/docs/cli/webhooks/show Description: Show a webhook endpoint Display the full configuration of a single webhook endpoint, including its URL, delivery format, subscribed event types, enabled state, description, and timestamps. ## Usage ## Options Option Description Required Default `` ID of the webhook endpoint to show Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints each field of the webhook endpoint on its own line. With `--json`, returns the full webhook object from the API. --- # webhooks test URL: https://pgbeam.com/docs/cli/webhooks/test Description: Send a test delivery to a webhook endpoint Trigger a test delivery to a webhook endpoint to verify its URL, format, and signing secret are configured correctly. PgBeam sends a sample payload and reports the result. ## Usage ## Options Option Description Required Default `` ID of the webhook endpoint to test Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming the test delivery was sent. With `--json`, returns the test result from the API. --- # webhooks update URL: https://pgbeam.com/docs/cli/webhooks/update Description: Update a webhook endpoint Update the configuration of an existing webhook endpoint. Only the fields you provide are changed; current settings are preserved for any flag not specified. Use `--event` to replace the subscribed event types (comma-separated) and `--enabled` to toggle delivery. ## Usage ## Options Option Description Required Default `` ID of the webhook endpoint to update Yes - `--url ` New destination URL for webhook deliveries. No - `--format ` New delivery format: json, splunk\_hec, datadog, or elastic. No - `--event ` Replace subscribed event type(s). Comma-separated. No - `--secret ` New shared secret used to sign webhook payloads. No - `--description ` New human-readable description for the webhook endpoint. No - `--enabled` Enable (true) or disable (false) the webhook endpoint. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming the webhook was updated. With `--json`, returns the full updated webhook object from the API. --- # ExportAccountData URL: https://pgbeam.com/docs/go-sdk/account/exportAccountData Description: Export account data Returns all personal data associated with the authenticated user in a structured JSON format. Supports GDPR data portability and CCPA right to know. Audit logs are limited to the most recent 1000 entries. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context ## Response `(*pgbeam.AccountExport, error)`: account data export. ## Example ## Errors Status Description 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # GetOnboardingProgress URL: https://pgbeam.com/docs/go-sdk/account/getOnboardingProgress Description: Get onboarding progress Returns the onboarding checklist progress for an organization. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. ## Response `(*pgbeam.OnboardingProgress, error)`: onboarding progress. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ListOrganizations URL: https://pgbeam.com/docs/go-sdk/account/listOrganizations Description: List organizations Lists the organizations visible to the caller's credential. An organization-scoped API key (pbo\_) returns exactly the organization it belongs to. A user credential (account-scoped API key or dashboard session token) returns the organizations the user is a member of, including the caller's role in each. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context ## Response `(*pgbeam.ListOrganizationsResponse, error)`: organizations visible to the caller. ## Example ## Errors Status Description 401 Missing or invalid authentication. 429 Rate limited. Try again later. --- # UpdateOnboardingProgress URL: https://pgbeam.com/docs/go-sdk/account/updateOnboardingProgress Description: Update onboarding progress Mark an onboarding step as complete or dismiss the checklist. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. req `pgbeam.UpdateOnboardingRequest` Yes Request body req.Step `*string` No The onboarding step to mark as complete. req.Dismiss `*bool` No Set to true to dismiss the onboarding checklist. ## Response `(*pgbeam.OnboardingProgress, error)`: updated onboarding progress. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # CreateAgentCredential URL: https://pgbeam.com/docs/go-sdk/agents/createAgentCredential Description: Create an agent credential Issues a scoped Postgres login and hosted MCP token for an AI agent. The connection string and MCP token are returned once and cannot be retrieved again. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.CreateAgentCredentialRequest` Yes Request body req.Name `string` Yes Human-readable label for the credential. req.PolicyProfileID `string` Yes The policy profile to enforce for this credential. req.PrincipalType `*string` No Whether this credential represents an autonomous agent or a human operator. req.ExpiresAt `*string` No Optional expiry. When set, the credential becomes unusable at this time (must be in the future). Omit or set null for a credential that never expires. ## Response `(*pgbeam.AgentCredentialSecrets, error)`: agent credential created. secrets shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Agent credential quota reached for the organization plan. 404 Resource not found. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # ExportAuditLogs URL: https://pgbeam.com/docs/go-sdk/agents/exportAuditLogs Description: Export agent audit logs as CSV Streams the project's agent audit entries as a CSV file, newest first, honoring the same credential, event, decision, source and date-range filters as the list endpoint. The full filtered set is streamed (no pagination); the result is suitable for spreadsheets, SIEM ingestion, and compliance archives. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ExportAuditLogsParams` No Query parameters params.CredentialID `string` No Filter to a single agent credential. params.Event `string` No Filter to a single event type (e.g. blocked, masked, query). params.Decision `pgbeam.AuditDecision` No Coarse outcome filter that groups events. `allow` = query; `block` = blocked, budget\_exhausted, auth\_failed, credential\_expired; `mask` = masked; `truncate` = truncated. params.Source `pgbeam.AuditSource` No Filter by statement origin (wire, mcp, rest, or control). params.Start `string` No Return entries at or after this timestamp (inclusive lower bound). params.End `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `(*pgbeam.unknown, error)`: the result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetAgentCredential URL: https://pgbeam.com/docs/go-sdk/agents/getAgentCredential Description: Get an agent credential Returns a single agent credential. Secrets are never included. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). agentID `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). ## Response `(*pgbeam.AgentCredential, error)`: the agent credential (no secrets). ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # GetAgentUsageBreakdown URL: https://pgbeam.com/docs/go-sdk/agents/getAgentUsageBreakdown Description: Break down project usage by agent credential Aggregates the audit trail into per-agent usage for a window: statements by decision, rows and bytes returned, the cache outcome breakdown, and latency percentiles. Read-only, derived entirely from entries the gateway already records. Grouped by credential, not by session. `session_id` is 32 bits of randomness minted per connection, so it identifies a connection rather than an agent or a run, and at scale it collides; the credential is the only stable identity in the trail. This endpoint reports usage and deliberately attributes no dollar figure to an agent. Overage is computed on the organization's total against a plan limit, so no single agent causes it independently of the others, and any per-agent split of that bill is a policy choice rather than a measurement. The organization's limits and marginal rates are returned alongside the usage so a caller can apply its own policy, with both meanings of a zero limit already resolved. Three things are reported rather than assumed. Usage recorded against no credential is its own line, so agents plus unattributed equals totals exactly. Latency covers only entries that ran and carried a finite value: every refusal writes a literal zero because there was nothing to time, and counting those would drag an agent's percentiles toward zero in proportion to how often it was refused, so the heavily blocked agent would report the fastest queries. And gap markers left by undelivered entries set `complete` to false, since a total over a trail with holes in it is a floor, not a measurement. Both `start` and `end` are optional. Omitting `end` means now; omitting `start` means 30 days before the end. The window is half-open and is capped at 92 days, because this aggregate reads every row in the window on the request path and an unbounded one would sort a year of latencies per group. `requested_start` and `requested_end` echo the window that was actually used, so a caller that pinned neither still knows what the totals cover. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.GetAgentUsageBreakdownParams` No Query parameters params.Start `string` No Return entries at or after this timestamp (inclusive lower bound). params.End `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `(*pgbeam.AgentUsageReport, error)`: per-agent usage for the window. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetAuditSessionSummary URL: https://pgbeam.com/docs/go-sdk/agents/getAuditSessionSummary Description: Summarize one agent session Groups a session's audit entries into one deterministic summary: the credentials and origins involved, the window it spans, how many statements were allowed, blocked, masked and truncated, the rows and bytes it moved, and the tables it read, wrote and was refused. No model is involved, so the same entries always summarize the same way. Returns metadata only (table names and counts), never row values, and requires the same audit:read permission the list and export endpoints do. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). sessionID `string` Yes Session identifier from an audit entry's session\_id field. Unique per connection within a proxy instance, not over time. params `*pgbeam.GetAuditSessionSummaryParams` No Query parameters params.Start `string` No Return entries at or after this timestamp (inclusive lower bound). params.End `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `(*pgbeam.AuditSessionSummary, error)`: session summary. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ListAgentCredentials URL: https://pgbeam.com/docs/go-sdk/agents/listAgentCredentials Description: List agent credentials Lists agent credentials for the project. Secrets are never returned. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListAgentCredentialsParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListAgentCredentialsResponse, error)`: list of agent credentials. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ListAuditLogs URL: https://pgbeam.com/docs/go-sdk/agents/listAuditLogs Description: List agent audit logs Returns agent statement audit entries for the project, newest first, with optional credential, event, decision, source and date-range filters. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListAuditLogsParams` No Query parameters params.CredentialID `string` No Filter to a single agent credential. params.Event `string` No Filter to a single event type (e.g. blocked, masked, query). params.Decision `pgbeam.AuditDecision` No Coarse outcome filter that groups events. `allow` = query; `block` = blocked, budget\_exhausted, auth\_failed, credential\_expired; `mask` = masked; `truncate` = truncated. params.Source `pgbeam.AuditSource` No Filter by statement origin (wire, mcp, rest, or control). params.Start `string` No Return entries at or after this timestamp (inclusive lower bound). params.End `string` No Return entries strictly older than this timestamp (cursor / upper bound). params.Before `string` No Return entries strictly older than this timestamp (keyset pagination cursor). params.PageSize `int` No Maximum number of items to return (1-100, default 20). ## Response `(*pgbeam.ListAuditLogsResponse, error)`: page of audit entries. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # RevokeAgentCredential URL: https://pgbeam.com/docs/go-sdk/agents/revokeAgentCredential Description: Revoke an agent credential Permanently revokes the credential and drops any live connections. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). agentID `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # RotateAgentCredential URL: https://pgbeam.com/docs/go-sdk/agents/rotateAgentCredential Description: Rotate an agent credential's secrets Generates a new Postgres password and MCP token for the credential in place, keeping the same id, username, name, and policy. Live connections using the old password are dropped within seconds. The new secrets are returned once and cannot be retrieved again. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). agentID `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). ## Response `(*pgbeam.AgentCredentialSecrets, error)`: secrets rotated. new secrets shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 The credential is revoked and cannot be rotated. --- # UpdateAgentCredentialStatus URL: https://pgbeam.com/docs/go-sdk/agents/updateAgentCredentialStatus Description: Enable or disable an agent credential Toggles the kill-switch. Disabling drops live connections within seconds. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). agentID `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). req `pgbeam.UpdateAgentCredentialStatusRequest` Yes Request body req.Status `string` Yes Set active to re-enable or disabled to kill-switch. Use DELETE to revoke permanently. ## Response `(*pgbeam.AgentCredential, error)`: updated agent credential. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # VerifyAuditChain URL: https://pgbeam.com/docs/go-sdk/agents/verifyAuditChain Description: Verify the tamper-evident audit chain Recomputes the project's audit hash chain over an optional time range and reports whether it is intact. Each audit entry is linked to its predecessor with a SHA-256 hash, so editing or deleting any row breaks the chain. On a break, the response reports the first sequence number where a tampered or deleted entry was detected. Requires the same audit:read permission as the list and export endpoints. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.VerifyAuditChainParams` No Query parameters params.Start `string` No Return entries at or after this timestamp (inclusive lower bound). params.End `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `(*pgbeam.AuditChainVerification, error)`: chain verification result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetOrganizationPlan URL: https://pgbeam.com/docs/go-sdk/analytics/getOrganizationPlan Description: Get organization plan Returns the current plan and limits for the organization. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. ## Response `(*pgbeam.OrganizationPlan, error)`: organization plan details. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # GetOrganizationUsage URL: https://pgbeam.com/docs/go-sdk/analytics/getOrganizationUsage Description: Get organization usage Returns daily usage data aggregated across all projects in the organization. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. params `*pgbeam.GetOrganizationUsageParams` Yes Query parameters params.StartDate `string` Yes Start date (inclusive, YYYY-MM-DD). params.EndDate `string` Yes End date (inclusive, YYYY-MM-DD). ## Response `(*pgbeam.UsageResponse, error)`: daily usage data. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # GetProjectInsights URL: https://pgbeam.com/docs/go-sdk/analytics/getProjectInsights Description: Get query insights for a project Returns aggregated query-level analytics for a project including top queries by count, cache hit/miss summary, and latency statistics. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.GetProjectInsightsParams` No Query parameters params.Range `string` No Time range to query. Defaults to 24h. params.Limit `int` No Maximum number of top queries to return (1-100). ## Response `(*pgbeam.ProjectInsights, error)`: query insights for the project. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # GetProjectUsage URL: https://pgbeam.com/docs/go-sdk/analytics/getProjectUsage Description: Get project usage Returns daily usage data for a specific project, broken down by region. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.GetProjectUsageParams` Yes Query parameters params.StartDate `string` Yes Start date (inclusive, YYYY-MM-DD). params.EndDate `string` Yes End date (inclusive, YYYY-MM-DD). ## Response `(*pgbeam.ProjectUsageResponse, error)`: daily usage data by region. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # GetVercelInstallation URL: https://pgbeam.com/docs/go-sdk/analytics/getVercelInstallation Description: Get Vercel Marketplace installation status Returns the Vercel Marketplace installation for the organization, including its provisioned resources and their current-period usage. Returns 404 when the organization was not provisioned through the Vercel Marketplace. Powers the dashboard's Vercel integration page. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. ## Response `(*pgbeam.VercelInstallationStatus, error)`: vercel installation status. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ListPlans URL: https://pgbeam.com/docs/go-sdk/analytics/listPlans Description: List available plans Returns all available plan tiers with their limits and pricing. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context ## Response `(*pgbeam.ListPlansResponse, error)`: list of available plans. ## Example ## Errors Status Description 401 Missing or invalid authentication. 429 Rate limited. Try again later. --- # SubmitCancellationFeedback URL: https://pgbeam.com/docs/go-sdk/analytics/submitCancellationFeedback Description: Submit cancellation feedback Records optional feedback when a user cancels their subscription. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. req `pgbeam.CancellationFeedbackRequest` Yes Request body req.Reason `*string` No Predefined cancellation reason. req.Feedback `*string` No Free-text feedback from the user. ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # UpdateSpendLimit URL: https://pgbeam.com/docs/go-sdk/analytics/updateSpendLimit Description: Update spend limit Sets the monthly spend limit for an organization. Null removes the limit. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. req `pgbeam.UpdateSpendLimitRequest` Yes Request body req.SpendLimit `*float64` No Monthly spend limit in dollars. Null to remove the limit. ## Response `(*pgbeam.OrganizationPlan, error)`: spend limit updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # ListAnomalyAlerts URL: https://pgbeam.com/docs/go-sdk/anomalies/listAnomalyAlerts Description: List anomaly alerts Lists anomaly alerts for the project, newest first, optionally filtered by status. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListAnomalyAlertsParams` No Query parameters params.Status `string` No Filter to a single status. params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListAnomalyAlertsResponse, error)`: page of anomaly alerts. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # UpdateAnomalyAlert URL: https://pgbeam.com/docs/go-sdk/anomalies/updateAnomalyAlert Description: Triage an anomaly alert Updates the triage status of an anomaly alert (acknowledge or resolve). ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). anomalyID `string` Yes Unique anomaly alert identifier (prefixed, e.g. ano\_xxx). req `pgbeam.UpdateAnomalyAlertRequest` Yes Request body req.Status `string` Yes New triage state for the alert. ## Response `(*pgbeam.AnomalyAlert, error)`: the updated anomaly alert. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # ApproveApprovalRequest URL: https://pgbeam.com/docs/go-sdk/approvals/approveApprovalRequest Description: Approve a held statement Approves a pending approval request, releasing the held statement. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). approvalID `string` Yes Unique approval request identifier (prefixed, e.g. apr\_xxx). req `pgbeam.ApprovalDecisionRequest` Yes Request body req.Reason `*string` No Human-readable note explaining the decision. ## Response `(*pgbeam.ApprovalRequest, error)`: the updated approval request. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Resource already exists or conflicts with current state. --- # ListApprovalRequests URL: https://pgbeam.com/docs/go-sdk/approvals/listApprovalRequests Description: List approval requests Lists approval requests for the project, newest first, optionally filtered by status. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListApprovalRequestsParams` No Query parameters params.Status `string` No Filter to a single status. params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListApprovalRequestsResponse, error)`: page of approval requests. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # RejectApprovalRequest URL: https://pgbeam.com/docs/go-sdk/approvals/rejectApprovalRequest Description: Reject a held statement Rejects a pending approval request, denying the held statement. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). approvalID `string` Yes Unique approval request identifier (prefixed, e.g. apr\_xxx). req `pgbeam.ApprovalDecisionRequest` Yes Request body req.Reason `*string` No Human-readable note explaining the decision. ## Response `(*pgbeam.ApprovalRequest, error)`: the updated approval request. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Resource already exists or conflicts with current state. --- # DiscardDatabaseBranch URL: https://pgbeam.com/docs/go-sdk/branches/discardDatabaseBranch Description: Discard a sandbox branch Marks an ephemeral sandbox branch as discarded for teardown. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). branchID `string` Yes Unique sandbox branch identifier (prefixed, e.g. brn\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # ListDatabaseBranches URL: https://pgbeam.com/docs/go-sdk/branches/listDatabaseBranches Description: List sandbox branches Lists ephemeral sandbox branches for the project's databases. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListDatabaseBranchesParams` No Query parameters params.Status `string` No Filter to a single status. params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListDatabaseBranchesResponse, error)`: page of sandbox branches. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # CreateDatabase URL: https://pgbeam.com/docs/go-sdk/databases/createDatabase Description: Add a database Registers a new upstream PostgreSQL database for the project. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.CreateDatabaseRequest` Yes Request body req.Host `string` Yes PostgreSQL host. req.Port `int` Yes PostgreSQL port. req.Name `string` Yes PostgreSQL database name. req.Username `string` Yes PostgreSQL username. req.Password `string` Yes PostgreSQL password. Stored encrypted at rest. req.SSLMode `*pgbeam.SSLMode` No PostgreSQL SSL connection mode. req.Role `*pgbeam.DatabaseRole` No Database role. Primary receives writes, replicas receive reads. req.PoolRegion `*string` No Region where the connection pool is maintained (near the database). When set and different from the client's edge region, queries are relayed through the pool region's data plane. Empty means direct connection. req.QueryTimeoutMs `*int` No Query timeout in milliseconds. 0 means disabled (default). req.AutoReadRouting `*bool` No Auto-route SELECT queries to read replicas. req.CacheConfig `*pgbeam.CacheConfig` No Query cache configuration. req.PoolConfig `*pgbeam.PoolConfig` No Connection pool configuration. ## Response `(*pgbeam.Database, error)`: database created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # DeleteDatabase URL: https://pgbeam.com/docs/go-sdk/databases/deleteDatabase Description: Delete a database Removes a database registration from the project. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetDatabase URL: https://pgbeam.com/docs/go-sdk/databases/getDatabase Description: Get a database Returns a single database by ID. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `(*pgbeam.Database, error)`: database found. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetSchemaCatalog URL: https://pgbeam.com/docs/go-sdk/databases/getSchemaCatalog Description: Read a database's schema catalog Connects to the upstream database read-only and returns its user relations (tables and views) and columns. Powers table/column autocomplete and view-aware warnings in the policy editor — relation kind distinguishes a view (whose masking/row-filters apply to the view itself, not its base tables) from a base table, and a per-column is\_binary flag flags columns that mask to NULL. System schemas are excluded; nothing is persisted. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `(*pgbeam.SchemaCatalog, error)`: schema catalog. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ListDatabases URL: https://pgbeam.com/docs/go-sdk/databases/listDatabases Description: List databases Lists all databases registered for the project. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListDatabasesParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListDatabasesResponse, error)`: list of databases. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ScanDatabaseForPii URL: https://pgbeam.com/docs/go-sdk/databases/scanDatabaseForPii Description: Scan a database for likely-PII columns Connects to the upstream database read-only, inspects information\_schema and samples column values against PII heuristics, and returns ranked masking suggestions. Suggestions are advisory — the operator reviews them and applies the ones they want into a policy profile's masking rules. Nothing is auto-applied. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `(*pgbeam.ScanPiiResult, error)`: pii scan result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # TestDatabaseConnection URL: https://pgbeam.com/docs/go-sdk/databases/testDatabaseConnection Description: Test database connection Attempts to connect to the upstream database using the stored credentials and returns the result. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `(*pgbeam.TestConnectionResult, error)`: connection test result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # UpdateDatabase URL: https://pgbeam.com/docs/go-sdk/databases/updateDatabase Description: Update a database Partially updates a database connection. Only provided fields are modified. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). req `pgbeam.UpdateDatabaseRequest` Yes Request body req.Host `*string` No Updated PostgreSQL host. req.Port `*int` No Updated PostgreSQL port. req.Name `*string` No Updated PostgreSQL database name. req.Username `*string` No Updated PostgreSQL username. req.Password `*string` No Updated PostgreSQL password. req.SSLMode `*pgbeam.SSLMode` No PostgreSQL SSL connection mode. req.Role `*pgbeam.DatabaseRole` No Database role. Primary receives writes, replicas receive reads. req.PoolRegion `*string` No Region where the connection pool is maintained (near the database). When set and different from the client's edge region, queries are relayed through the pool region's data plane. Empty means direct connection. req.QueryTimeoutMs `*int` No Query timeout in milliseconds. 0 means disabled. req.AutoReadRouting `*bool` No Auto-route SELECT queries to read replicas. req.CacheConfig `*pgbeam.CacheConfig` No Query cache configuration. req.PoolConfig `*pgbeam.PoolConfig` No Connection pool configuration. ## Response `(*pgbeam.Database, error)`: database updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # CreateHoneytoken URL: https://pgbeam.com/docs/go-sdk/honeytokens/createHoneytoken Description: Register a honeytoken Registers a decoy (canary) relation for the project. Any agent statement that references it is blocked and recorded as a canary\_tripped audit event. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.HoneytokenInput` Yes Request body req.SchemaName `*string` No Optional schema. Null or empty matches the unqualified/public form. req.RelationName `string` Yes Relation (table or view) name of the decoy. req.Action `string` Yes Response when the honeytoken is tripped. ## Response `(*pgbeam.Honeytoken, error)`: honeytoken registered. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # DeleteHoneytoken URL: https://pgbeam.com/docs/go-sdk/honeytokens/deleteHoneytoken Description: Delete a honeytoken Removes a honeytoken from the project. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). honeytokenID `string` Yes Unique honeytoken identifier (prefixed, e.g. hnt\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # GetHoneytoken URL: https://pgbeam.com/docs/go-sdk/honeytokens/getHoneytoken Description: Get a honeytoken Returns a single honeytoken by ID. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). honeytokenID `string` Yes Unique honeytoken identifier (prefixed, e.g. hnt\_xxx). ## Response `(*pgbeam.Honeytoken, error)`: the honeytoken. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # ListHoneytokens URL: https://pgbeam.com/docs/go-sdk/honeytokens/listHoneytokens Description: List honeytokens Lists the project's honeytokens. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListHoneytokensParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListHoneytokensResponse, error)`: list of honeytokens. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # UpdateHoneytoken URL: https://pgbeam.com/docs/go-sdk/honeytokens/updateHoneytoken Description: Update a honeytoken Updates a honeytoken's relation or action. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). honeytokenID `string` Yes Unique honeytoken identifier (prefixed, e.g. hnt\_xxx). req `pgbeam.HoneytokenInput` Yes Request body req.SchemaName `*string` No Optional schema. Null or empty matches the unqualified/public form. req.RelationName `string` Yes Relation (table or view) name of the decoy. req.Action `string` Yes Response when the honeytoken is tripped. ## Response `(*pgbeam.Honeytoken, error)`: updated honeytoken. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # HandleSlackSupportEvent URL: https://pgbeam.com/docs/go-sdk/internal/handleSlackSupportEvent Description: Handle a Slack support event Receives a forwarded Slack event from the dashboard webhook handler and creates a support message. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context req `pgbeam.SlackEventPayload` Yes Request body req.ChannelID `string` Yes Slack channel ID where the message was posted. req.ThreadTs `string` Yes Slack thread timestamp identifying the support case thread. req.UserID `string` Yes Slack user ID of the message author. req.Text `string` Yes Message text from Slack. ## Response `(*pgbeam.unknown, error)`: the result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. --- # LintMigration URL: https://pgbeam.com/docs/go-sdk/migrations/lintMigration Description: Lint a migration Analyzes a migration script for unsafe schema changes and returns findings. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.MigrationLintRequest` Yes Request body req.SQL `string` Yes The migration SQL to analyze. May contain multiple statements. req.DatabaseID `*string` No Optional database to scope the lint to. ## Response `(*pgbeam.MigrationLintResponse, error)`: lint results. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # CreateSelfHostEnrollment URL: https://pgbeam.com/docs/go-sdk/platform/createSelfHostEnrollment Description: Issue a self-host enrollment token Issues an enrollment token a self-hosted (BYOC) proxy uses to authenticate to the control plane's config/audit gRPC stream. The token is returned once and cannot be retrieved again. Requires the Scale or enterprise plan. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. req `pgbeam.CreateSelfHostEnrollmentRequest` Yes Request body req.RegionLabel `*string` No Operator-supplied label for where the proxy runs. req.Description `*string` No Optional human-readable note. req.ExpiresAt `*string` No Optional expiry. When set, the enrollment token stops authenticating new proxy connections at this time (must be in the future). Omit or set null for a token that never expires. ## Response `(*pgbeam.SelfHostEnrollmentSecret, error)`: enrollment created. token shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 The organization's plan is not entitled to self-host. 429 Rate limited. Try again later. --- # GetHealth URL: https://pgbeam.com/docs/go-sdk/platform/getHealth Description: Health check Returns the health status of the API server. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context ## Response `(*pgbeam.HealthResponse, error)`: service is healthy. ## Example ## Errors Status Description 429 Rate limited. Try again later. --- # ListRegions URL: https://pgbeam.com/docs/go-sdk/platform/listRegions Description: List available regions Returns all active data plane regions. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context ## Response `(*pgbeam.ListRegionsResponse, error)`: list of regions. ## Example ## Errors Status Description 401 Missing or invalid authentication. 429 Rate limited. Try again later. --- # ListSelfHostEnrollments URL: https://pgbeam.com/docs/go-sdk/platform/listSelfHostEnrollments Description: List self-host enrollments Lists an organization's self-host enrollments. Tokens are never returned. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. ## Response `(*pgbeam.ListSelfHostEnrollmentsResponse, error)`: list of enrollments. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. --- # RevokeSelfHostEnrollment URL: https://pgbeam.com/docs/go-sdk/platform/revokeSelfHostEnrollment Description: Revoke a self-host enrollment Revokes an enrollment so its token can no longer authenticate a proxy. Connected proxies keep their last-known config until they reconnect. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. enrollmentID `string` Yes Unique enrollment identifier. ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # RotateSelfHostEnrollment URL: https://pgbeam.com/docs/go-sdk/platform/rotateSelfHostEnrollment Description: Rotate a self-host enrollment token Mints a new enrollment token in place, keeping the same enrollment id, metadata, and expiry. The swap is atomic: the old token stops authenticating new proxy connections the moment this call returns. An already-connected proxy keeps its existing gRPC streams until it disconnects, then must present the new token to reconnect. The new token is returned once and cannot be retrieved again. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. enrollmentID `string` Yes Unique enrollment identifier. ## Response `(*pgbeam.SelfHostEnrollmentSecret, error)`: token rotated. new token shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 The enrollment is revoked and cannot be rotated. --- # CreatePolicyProfile URL: https://pgbeam.com/docs/go-sdk/policies/createPolicyProfile Description: Create a policy profile Creates a policy profile that can be attached to agent credentials. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.PolicyProfileInput` Yes Request body req.Name `string` Yes Human-readable name for the policy profile. req.AccessMode `*string` No read\_only blocks all data and schema mutations. req.StatementRules `*pgbeam.StatementRules` No Per-statement-kind allow/deny lists. Empty allow means all kinds permitted by the access mode. req.TableAllowlist `*[]string` No If non-empty, only these relations are reachable. A bare entry grants the public schema only; list another schema in full, as in billing.orders. req.TableDenylist `*[]string` No Relations explicitly blocked. A bare entry blocks that relation in every schema. req.MaskingRules `*[]pgbeam.MaskingRule` No Column masking rules applied to query results. req.BudgetQueriesPerHour `*int` No Max queries per rolling hour window. 0 means unlimited. req.BudgetQueriesPerDay `*int` No Max queries per day window. 0 means unlimited. req.MaxRows `*int` No Max rows returned per query. 0 means unlimited. req.StatementTimeoutMs `*int` No Upstream statement timeout for agent sessions. 0 uses the project default. req.RowFilters `*[]pgbeam.RowFilter` No Per-relation row filters ANDed into agent reads. req.WriteMode `*string` No How writes are handled. normal commits, rollback auto-rolls back, sandbox routes to an ephemeral branch. req.ApprovalMode `*string` No Which statement classes require human approval before execution. req.ApprovalAutoMaxRows `*int` No Statements touching at most this many rows are auto-approved. 0 means none. req.ApprovalTimeoutSeconds `*int` No How long a held statement waits for a decision before expiring. req.MigrationSafety `*string` No Migration safety mode. warn surfaces findings, block refuses unsafe DDL. req.EgressBytesPerDay `*int` No Per-day egress budget in bytes. 0 means unlimited. req.MaxAffectedRows `*int` No Hard cap on rows a single write (INSERT/UPDATE/DELETE) may affect. A write whose affected-row count would exceed this is executed inside a transaction, checked, and rolled back so nothing persists, then blocked. Enforced independently of human approval. 0 means unlimited. ## Response `(*pgbeam.PolicyProfile, error)`: policy profile created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # DeletePolicyProfile URL: https://pgbeam.com/docs/go-sdk/policies/deletePolicyProfile Description: Delete a policy profile Deletes a policy profile. Fails if agent credentials still reference it. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). policyID `string` Yes Unique policy profile identifier (prefixed, e.g. pol\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Policy profile is still referenced by agent credentials. --- # DryEvalPolicy URL: https://pgbeam.com/docs/go-sdk/policies/dryEvalPolicy Description: Dry-eval a policy against a SQL statement Evaluates a single SQL statement against a policy (either a draft policy supplied inline or an existing policy referenced by id) and returns the decision the proxy would make: allow, block, mask, or row-filter. The evaluation reuses the data plane's own policy engine (the same parser, allow/block rules, row-filter rewriter, and masking analysis enforced on live agent sessions), so a what-if verdict matches real enforcement. Stateful checks a single-statement preview cannot model (per-region query and egress budgets, human approvals, and rollback/sandbox write routing) are reported as informational notes, not verdicts. This is a pure compute endpoint; it does not connect to the upstream database and persists nothing. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.DryEvalInput` Yes Request body req.SQL `string` Yes The single SQL statement to evaluate. req.PolicyID `*string` No ID of an existing saved policy profile to evaluate against. req.Policy `*pgbeam.PolicyProfileInput` No Mutable fields of a policy profile (used for create and update). ## Response `(*pgbeam.DryEvalResult, error)`: the dry-eval decision. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetPolicyProfile URL: https://pgbeam.com/docs/go-sdk/policies/getPolicyProfile Description: Get a policy profile Returns a single policy profile by ID. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). policyID `string` Yes Unique policy profile identifier (prefixed, e.g. pol\_xxx). ## Response `(*pgbeam.PolicyProfile, error)`: the policy profile. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # ListPolicyProfiles URL: https://pgbeam.com/docs/go-sdk/policies/listPolicyProfiles Description: List policy profiles Lists all policy profiles for the project. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListPolicyProfilesParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListPolicyProfilesResponse, error)`: list of policy profiles. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # RecommendAgentPolicy URL: https://pgbeam.com/docs/go-sdk/policies/recommendAgentPolicy Description: Recommend a least-privilege policy from recorded traffic Derives the tightest policy that would still pass every statement this agent credential has legitimately run, using its recorded audit history over a lookback window (default 30 days). The candidate's table allowlist is the union of relations actually referenced, its statement-kind allow set is the observed set, it downgrades to read-only when no writes were seen, and its max\_rows ceiling comes from an observed high-percentile row count. The candidate is proven safe by replaying it through the data plane's own policy engine against the same history: a good recommendation has replay.summary.newly\_blocked == 0. This endpoint is advisory only. It reads the audit log, never connects to the upstream database, and never creates, updates, or mutates any policy or credential; the operator loads the candidate into the editor and saves it themselves. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). agentID `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). req `pgbeam.PolicyRecommendationInput` Yes Request body req.LookbackDays `*int` No How many days of recorded audit history to analyze. req.Limit `*int` No Maximum number of distinct query shapes to analyze and replay, newest first. Traffic is deduplicated by normalized query hash. ## Response `(*pgbeam.PolicyRecommendation, error)`: the recommended candidate policy and its replay proof. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ReplayPolicy URL: https://pgbeam.com/docs/go-sdk/policies/replayPolicy Description: Replay recorded agent traffic against a policy Replays the project's recorded agent audit traffic against a candidate policy (either a draft supplied inline or an existing policy referenced by id) and reports what would change: which queries that ran would now be blocked, which blocked queries would now be permitted, and which results would be masked or row-filtered. Traffic is deduplicated by normalized query shape, newest first, and every statement is evaluated through the data plane's own policy engine, so the verdicts match real enforcement. Stateful checks (budgets, approvals, write-mode routing) are reported as informational notes on each result, not verdicts. This endpoint reads only the audit log; it never connects to the upstream database and persists nothing. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.PolicyReplayInput` Yes Request body req.PolicyID `*string` No ID of an existing saved policy profile to replay against. req.Policy `*pgbeam.PolicyProfileInput` No Mutable fields of a policy profile (used for create and update). req.CredentialID `*string` No Restrict the replay to traffic recorded for one agent credential. req.BoundPolicyID `*string` No Restrict the replay to traffic recorded for the agent credentials currently bound to this policy profile. Use it to preview a change to a live policy against the traffic that policy actually governs: without it the replay covers every credential in the project, including credentials bound to other profiles, whose behaviour saving this candidate cannot change. Mutually exclusive with credential\_id. req.StartTs `*string` No Start of the traffic window (inclusive). Defaults to 7 days before end\_ts. req.EndTs `*string` No End of the traffic window (exclusive). Defaults to now. req.Limit `*int` No Maximum number of distinct queries to replay, newest first. Traffic is deduplicated by normalized query hash before evaluation. ## Response `(*pgbeam.PolicyReplayResult, error)`: the replay summary and per-query decisions. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # UpdatePolicyProfile URL: https://pgbeam.com/docs/go-sdk/policies/updatePolicyProfile Description: Update a policy profile Updates a policy profile. Changes hot-reload to active agent sessions. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). policyID `string` Yes Unique policy profile identifier (prefixed, e.g. pol\_xxx). req `pgbeam.PolicyProfileInput` Yes Request body req.Name `string` Yes Human-readable name for the policy profile. req.AccessMode `*string` No read\_only blocks all data and schema mutations. req.StatementRules `*pgbeam.StatementRules` No Per-statement-kind allow/deny lists. Empty allow means all kinds permitted by the access mode. req.TableAllowlist `*[]string` No If non-empty, only these relations are reachable. A bare entry grants the public schema only; list another schema in full, as in billing.orders. req.TableDenylist `*[]string` No Relations explicitly blocked. A bare entry blocks that relation in every schema. req.MaskingRules `*[]pgbeam.MaskingRule` No Column masking rules applied to query results. req.BudgetQueriesPerHour `*int` No Max queries per rolling hour window. 0 means unlimited. req.BudgetQueriesPerDay `*int` No Max queries per day window. 0 means unlimited. req.MaxRows `*int` No Max rows returned per query. 0 means unlimited. req.StatementTimeoutMs `*int` No Upstream statement timeout for agent sessions. 0 uses the project default. req.RowFilters `*[]pgbeam.RowFilter` No Per-relation row filters ANDed into agent reads. req.WriteMode `*string` No How writes are handled. normal commits, rollback auto-rolls back, sandbox routes to an ephemeral branch. req.ApprovalMode `*string` No Which statement classes require human approval before execution. req.ApprovalAutoMaxRows `*int` No Statements touching at most this many rows are auto-approved. 0 means none. req.ApprovalTimeoutSeconds `*int` No How long a held statement waits for a decision before expiring. req.MigrationSafety `*string` No Migration safety mode. warn surfaces findings, block refuses unsafe DDL. req.EgressBytesPerDay `*int` No Per-day egress budget in bytes. 0 means unlimited. req.MaxAffectedRows `*int` No Hard cap on rows a single write (INSERT/UPDATE/DELETE) may affect. A write whose affected-row count would exceed this is executed inside a transaction, checked, and rolled back so nothing persists, then blocked. Enforced independently of human approval. 0 means unlimited. ## Response `(*pgbeam.PolicyProfile, error)`: updated policy profile. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # CreateCustomDomain URL: https://pgbeam.com/docs/go-sdk/projects/createCustomDomain Description: Add a custom domain Registers a new custom domain for the project. Returns DNS verification instructions. Requires a Scale or Enterprise plan. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.CreateCustomDomainRequest` Yes Request body req.Domain `string` Yes The custom domain name to add (e.g., db.example.com). ## Response `(*pgbeam.CustomDomain, error)`: custom domain created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Custom domains require a Scale or Enterprise plan. 404 Resource not found. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # CreateProject URL: https://pgbeam.com/docs/go-sdk/projects/createProject Description: Create a project Creates a new project within the specified organization. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context req `pgbeam.CreateProjectRequest` Yes Request body req.Name `string` Yes Human-readable project name. req.OrgID `string` Yes Better Auth organization ID. req.Description `*string` No Optional project description. req.Tags `*[]string` No User-defined labels to attach to the project. req.Cloud `*string` No Cloud provider for the project. req.SelfHosted `*bool` No Mark this project as running on a self-hosted (BYOC) data plane in the customer's own VPC/cluster. Requires the Scale or enterprise plan. req.Database `pgbeam.CreateDatabaseRequest` Yes Request body for registering an upstream database. ## Response `(*pgbeam.CreateProjectResponse, error)`: project created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # CreateReplica URL: https://pgbeam.com/docs/go-sdk/projects/createReplica Description: Add a replica Adds a read replica to a database. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). req `pgbeam.CreateReplicaRequest` Yes Request body req.Host `string` Yes PostgreSQL replica host. req.Port `int` Yes PostgreSQL replica port. req.SSLMode `*pgbeam.SSLMode` No PostgreSQL SSL connection mode. ## Response `(*pgbeam.Replica, error)`: replica created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # DeleteCustomDomain URL: https://pgbeam.com/docs/go-sdk/projects/deleteCustomDomain Description: Delete a custom domain Removes a custom domain from the project and revokes its TLS certificate. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). domainID `string` Yes Unique custom domain identifier (prefixed, e.g. dom\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # DeleteProject URL: https://pgbeam.com/docs/go-sdk/projects/deleteProject Description: Delete a project Soft-deletes a project and all associated databases. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # DeleteReplica URL: https://pgbeam.com/docs/go-sdk/projects/deleteReplica Description: Delete a replica Removes a read replica from a database. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). replicaID `string` Yes Unique replica identifier (prefixed, e.g. rep\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetProject URL: https://pgbeam.com/docs/go-sdk/projects/getProject Description: Get a project Returns a single project by ID. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). ## Response `(*pgbeam.Project, error)`: project found. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # GetProjectMetrics URL: https://pgbeam.com/docs/go-sdk/projects/getProjectMetrics Description: Get project metrics Returns recent project metrics snapshots, optionally filtered by region. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.GetProjectMetricsParams` No Query parameters params.Limit `int` No Maximum number of recent snapshots to return. params.Region `string` No Filter metrics by region code. ## Response `(*pgbeam.ProjectMetricsResponse, error)`: metrics snapshots ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # ListCacheRules URL: https://pgbeam.com/docs/go-sdk/projects/listCacheRules Description: List cache rules Returns the cache rules for a database, showing all observed query shapes with their stats and cache recommendations. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). params `*pgbeam.ListCacheRulesParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListCacheRulesResponse, error)`: cache rule entries. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ListCustomDomains URL: https://pgbeam.com/docs/go-sdk/projects/listCustomDomains Description: List custom domains Lists all custom domains registered for the project. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListCustomDomainsParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListCustomDomainsResponse, error)`: list of custom domains. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # ListProjects URL: https://pgbeam.com/docs/go-sdk/projects/listProjects Description: List projects Lists projects filtered by organization. Requires org\_id query parameter. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context params `*pgbeam.ListProjectsParams` Yes Query parameters params.OrgID `string` Yes Organization ID to filter projects. params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. params.SortBy `string` No Sort field for projects list. ## Response `(*pgbeam.ListProjectsResponse, error)`: list of projects. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # ListReplicas URL: https://pgbeam.com/docs/go-sdk/projects/listReplicas Description: List replicas Lists all read replicas for a database. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `(*pgbeam.ListReplicasResponse, error)`: list of replicas. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # UpdateCacheRule URL: https://pgbeam.com/docs/go-sdk/projects/updateCacheRule Description: Update cache rule Enable or disable caching for a specific query shape, with optional TTL and SWR overrides. Requires the query to exist in the cache rules. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). databaseID `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). queryHash `string` Yes xxhash64 hex of the normalized SQL. req `pgbeam.UpdateCacheRuleRequest` Yes Request body req.CacheEnabled `bool` Yes Whether to enable caching for this query shape. req.CacheTTLSeconds `*int` No TTL override in seconds. Null to use project default. req.CacheSWRSeconds `*int` No SWR override in seconds. Null to use project default. ## Response `(*pgbeam.UpdateCacheRuleResponse, error)`: cache rule updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # UpdateProject URL: https://pgbeam.com/docs/go-sdk/projects/updateProject Description: Update a project Partially updates a project. Only provided fields are modified. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.UpdateProjectRequest` Yes Request body req.Name `*string` No Updated project name. req.Description `*string` No Updated project description. req.Tags `*[]string` No Replacement set of user-defined project labels. req.Status `*pgbeam.ProjectStatus` No Project lifecycle status. req.AllowedCidrs `*[]pgbeam.CidrEntry` No IP filtering rules as CIDR ranges with optional labels. Empty array means allow all. Both IPv4 and IPv6 CIDR notation are supported. req.DefaultPolicyProfileID `*string` No When set, passthrough/human connections are enforced against this policy profile. Send an empty string to clear. req.Residency `*pgbeam.DataResidency` No Data-residency requirement for the project. "any" (default) lets queries be served from the nearest data-plane metro. "us" or "eu" require the serving metro to be in that jurisdiction; the proxy fails a connection closed when it is served from a metro outside the required jurisdiction, so regulated workloads never process outside their permitted region. req.AgentsDisabled `*bool` No Project-level kill-switch. Set true to block ALL agent-credential connections to this project (live agent sessions are dropped within seconds); set false to re-enable them. Passthrough/human connections are unaffected. Engaging the kill-switch emits a kill\_switch webhook event. ## Response `(*pgbeam.Project, error)`: project updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # VerifyCustomDomain URL: https://pgbeam.com/docs/go-sdk/projects/verifyCustomDomain Description: Verify custom domain DNS Checks DNS TXT record to verify domain ownership. Updates domain status on success. Requires a Scale or Enterprise plan. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). domainID `string` Yes Unique custom domain identifier (prefixed, e.g. dom\_xxx). ## Response `(*pgbeam.VerifyCustomDomainResponse, error)`: verification result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Custom domains require a Scale or Enterprise plan. 404 Resource not found. 429 Rate limited. Try again later. --- # DeleteSchemaAnnotation URL: https://pgbeam.com/docs/go-sdk/schemaannotations/deleteSchemaAnnotation Description: Delete a schema annotation Removes a single annotation identified by its natural key. Omit column\_name to delete a table-level annotation, and omit schema\_name to match the unqualified form. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.DeleteSchemaAnnotationParams` Yes Query parameters params.TableName `string` Yes Relation (table or view) the annotation describes. params.SchemaName `string` No Optional schema. Omit to match the unqualified form. params.ColumnName `string` No Optional column. Omit to delete a table-level annotation. ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # ListSchemaAnnotations URL: https://pgbeam.com/docs/go-sdk/schemaannotations/listSchemaAnnotations Description: List schema annotations Lists the project's human-written table and column descriptions. These are surfaced to connected agents through the MCP schema catalog. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListSchemaAnnotationsParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListSchemaAnnotationsResponse, error)`: list of schema annotations. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # PutSchemaAnnotation URL: https://pgbeam.com/docs/go-sdk/schemaannotations/putSchemaAnnotation Description: Create or replace a schema annotation Attaches an operator-written description to a table (omit column\_name) or a column. Keyed by (schema\_name, table\_name, column\_name); an existing annotation with the same key is replaced. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.SchemaAnnotationInput` Yes Request body req.SchemaName `*string` No Optional schema. Null or empty matches the unqualified form. req.TableName `string` Yes Relation (table or view) the annotation describes. req.ColumnName `*string` No Optional column. Null describes the table itself. req.Description `string` Yes The operator-written description text. ## Response `(*pgbeam.SchemaAnnotation, error)`: the created or updated annotation. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # CreateSupportCase URL: https://pgbeam.com/docs/go-sdk/support/createSupportCase Description: Create a support case Creates a new support case with an initial message. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. req `pgbeam.CreateSupportCaseRequest` Yes Request body req.OrgID `string` Yes Organization ID. req.Title `string` Yes Brief summary of the issue. req.Severity `*int` No Severity level: 1=Critical, 2=High, 3=Normal, 4=Low. req.Body `string` Yes Initial message body. ## Response `(*pgbeam.SupportCase, error)`: support case created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. --- # CreateSupportMessage URL: https://pgbeam.com/docs/go-sdk/support/createSupportMessage Description: Add a message to a support case Adds a new message to an existing support case thread. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. caseID `string` Yes Unique support case identifier (prefixed, e.g. sc\_xxx). req `pgbeam.CreateSupportMessageRequest` Yes Request body req.Body `string` Yes Message content. ## Response `(*pgbeam.SupportMessage, error)`: message created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # GetSupportCase URL: https://pgbeam.com/docs/go-sdk/support/getSupportCase Description: Get a support case Returns a support case with all its messages. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. caseID `string` Yes Unique support case identifier (prefixed, e.g. sc\_xxx). ## Response `(*pgbeam.GetSupportCaseResponse, error)`: support case with messages. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # ListSupportCases URL: https://pgbeam.com/docs/go-sdk/support/listSupportCases Description: List support cases Lists support cases for the organization with optional status and search filters. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. params `*pgbeam.ListSupportCasesParams` No Query parameters params.Status `pgbeam.SupportCaseStatus` No Filter by case status. params.Search `string` No Search cases by title. params.PageSize `int` No Number of results per page (1-100, default 20). params.Page `int` No Page number (1-based, default 1). ## Response `(*pgbeam.ListSupportCasesResponse, error)`: list of support cases. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. --- # UpdateSupportCase URL: https://pgbeam.com/docs/go-sdk/support/updateSupportCase Description: Update a support case Updates the status of a support case (close or reopen). ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context orgID `string` Yes Unique organization identifier. caseID `string` Yes Unique support case identifier (prefixed, e.g. sc\_xxx). req `pgbeam.UpdateSupportCaseRequest` Yes Request body req.Status `*pgbeam.SupportCaseStatus` No Current status of the support case. ## Response `(*pgbeam.SupportCase, error)`: updated support case. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # CreateWebhookEndpoint URL: https://pgbeam.com/docs/go-sdk/webhooks/createWebhookEndpoint Description: Create a webhook endpoint Creates a webhook endpoint that receives project event deliveries. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). req `pgbeam.WebhookEndpointInput` Yes Request body req.URL `string` Yes HTTPS endpoint that receives event deliveries. req.Secret `*string` No Shared secret used to sign delivery payloads. Write-only. req.Format `*string` No Payload format for delivered events. req.EventTypes `*[]string` No Event types to deliver. Empty means all events. req.Enabled `*bool` No Whether deliveries are active for this endpoint. req.Description `*string` No Human-readable label for the endpoint. ## Response `(*pgbeam.WebhookEndpoint, error)`: webhook endpoint created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # DeleteWebhookEndpoint URL: https://pgbeam.com/docs/go-sdk/webhooks/deleteWebhookEndpoint Description: Delete a webhook endpoint Deletes a webhook endpoint and its pending deliveries. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). webhookID `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). ## Response `error`: returns nil on success. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # GetWebhookEndpoint URL: https://pgbeam.com/docs/go-sdk/webhooks/getWebhookEndpoint Description: Get a webhook endpoint Returns a single webhook endpoint by ID. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). webhookID `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). ## Response `(*pgbeam.WebhookEndpoint, error)`: the webhook endpoint. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # ListWebhookEndpoints URL: https://pgbeam.com/docs/go-sdk/webhooks/listWebhookEndpoints Description: List webhook endpoints Lists webhook endpoints for the project. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). params `*pgbeam.ListWebhookEndpointsParams` No Query parameters params.PageSize `int` No Maximum number of items to return (1-100, default 20). params.PageToken `string` No Opaque token for cursor-based pagination. ## Response `(*pgbeam.ListWebhookEndpointsResponse, error)`: list of webhook endpoints. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # TestWebhookEndpoint URL: https://pgbeam.com/docs/go-sdk/webhooks/testWebhookEndpoint Description: Send a test event Enqueues a test event delivery to the webhook endpoint. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). webhookID `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). ## Response `(*pgbeam.unknown, error)`: the result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # UpdateWebhookEndpoint URL: https://pgbeam.com/docs/go-sdk/webhooks/updateWebhookEndpoint Description: Update a webhook endpoint Updates a webhook endpoint. ## Usage ## Parameters Parameter Type Required Description ctx `context.Context` Yes Request context projectID `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). webhookID `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). req `pgbeam.WebhookEndpointInput` Yes Request body req.URL `string` Yes HTTPS endpoint that receives event deliveries. req.Secret `*string` No Shared secret used to sign delivery payloads. Write-only. req.Format `*string` No Payload format for delivered events. req.EventTypes `*[]string` No Event types to deliver. Empty means all events. req.Enabled `*bool` No Whether deliveries are active for this endpoint. req.Description `*string` No Human-readable label for the endpoint. ## Response `(*pgbeam.WebhookEndpoint, error)`: updated webhook endpoint. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # createAgentCredential URL: https://pgbeam.com/docs/ts-sdk/agents/createAgentCredential Description: Create an agent credential Issues a scoped Postgres login and hosted MCP token for an AI agent. The connection string and MCP token are returned once and cannot be retrieved again. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.name `string` Yes Human-readable label for the credential. body.policy\_profile\_id `string` Yes The policy profile to enforce for this credential. body.principal\_type `"agent" \| "human"` No Whether this credential represents an autonomous agent or a human operator. body.expires\_at `string` No Optional expiry. When set, the credential becomes unusable at this time (must be in the future). Omit or set null for a credential that never expires. ## Response `Promise`: agent credential created. secrets shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Agent credential quota reached for the organization plan. 404 Resource not found. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # exportAuditLogs URL: https://pgbeam.com/docs/ts-sdk/agents/exportAuditLogs Description: Export agent audit logs as CSV Streams the project's agent audit entries as a CSV file, newest first, honoring the same credential, event, decision, source and date-range filters as the list endpoint. The full filtered set is streamed (no pagination); the result is suitable for spreadsheets, SIEM ingestion, and compliance archives. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.credential\_id `string` No Filter to a single agent credential. queryParams.event `string` No Filter to a single event type (e.g. blocked, masked, query). queryParams.decision `AuditDecision` No Coarse outcome filter that groups events. `allow` = query; `block` = blocked, budget\_exhausted, auth\_failed, credential\_expired; `mask` = masked; `truncate` = truncated. queryParams.source `AuditSource` No Filter by statement origin (wire, mcp, rest, or control). queryParams.start `string` No Return entries at or after this timestamp (inclusive lower bound). queryParams.end `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `Promise`: the result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getAgentCredential URL: https://pgbeam.com/docs/ts-sdk/agents/getAgentCredential Description: Get an agent credential Returns a single agent credential. Secrets are never included. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.agent\_id `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). ## Response `Promise`: the agent credential (no secrets). ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # getAgentUsageBreakdown URL: https://pgbeam.com/docs/ts-sdk/agents/getAgentUsageBreakdown Description: Break down project usage by agent credential Aggregates the audit trail into per-agent usage for a window: statements by decision, rows and bytes returned, the cache outcome breakdown, and latency percentiles. Read-only, derived entirely from entries the gateway already records. Grouped by credential, not by session. `session_id` is 32 bits of randomness minted per connection, so it identifies a connection rather than an agent or a run, and at scale it collides; the credential is the only stable identity in the trail. This endpoint reports usage and deliberately attributes no dollar figure to an agent. Overage is computed on the organization's total against a plan limit, so no single agent causes it independently of the others, and any per-agent split of that bill is a policy choice rather than a measurement. The organization's limits and marginal rates are returned alongside the usage so a caller can apply its own policy, with both meanings of a zero limit already resolved. Three things are reported rather than assumed. Usage recorded against no credential is its own line, so agents plus unattributed equals totals exactly. Latency covers only entries that ran and carried a finite value: every refusal writes a literal zero because there was nothing to time, and counting those would drag an agent's percentiles toward zero in proportion to how often it was refused, so the heavily blocked agent would report the fastest queries. And gap markers left by undelivered entries set `complete` to false, since a total over a trail with holes in it is a floor, not a measurement. Both `start` and `end` are optional. Omitting `end` means now; omitting `start` means 30 days before the end. The window is half-open and is capped at 92 days, because this aggregate reads every row in the window on the request path and an unbounded one would sort a year of latencies per group. `requested_start` and `requested_end` echo the window that was actually used, so a caller that pinned neither still knows what the totals cover. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.start `string` No Return entries at or after this timestamp (inclusive lower bound). queryParams.end `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `Promise`: per-agent usage for the window. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getAuditSessionSummary URL: https://pgbeam.com/docs/ts-sdk/agents/getAuditSessionSummary Description: Summarize one agent session Groups a session's audit entries into one deterministic summary: the credentials and origins involved, the window it spans, how many statements were allowed, blocked, masked and truncated, the rows and bytes it moved, and the tables it read, wrote and was refused. No model is involved, so the same entries always summarize the same way. Returns metadata only (table names and counts), never row values, and requires the same audit:read permission the list and export endpoints do. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.session\_id `string` Yes Session identifier from an audit entry's session\_id field. Unique per connection within a proxy instance, not over time. queryParams.start `string` No Return entries at or after this timestamp (inclusive lower bound). queryParams.end `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `Promise`: session summary. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # listAgentCredentials URL: https://pgbeam.com/docs/ts-sdk/agents/listAgentCredentials Description: List agent credentials Lists agent credentials for the project. Secrets are never returned. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: list of agent credentials. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # listAuditLogs URL: https://pgbeam.com/docs/ts-sdk/agents/listAuditLogs Description: List agent audit logs Returns agent statement audit entries for the project, newest first, with optional credential, event, decision, source and date-range filters. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.credential\_id `string` No Filter to a single agent credential. queryParams.event `string` No Filter to a single event type (e.g. blocked, masked, query). queryParams.decision `AuditDecision` No Coarse outcome filter that groups events. `allow` = query; `block` = blocked, budget\_exhausted, auth\_failed, credential\_expired; `mask` = masked; `truncate` = truncated. queryParams.source `AuditSource` No Filter by statement origin (wire, mcp, rest, or control). queryParams.start `string` No Return entries at or after this timestamp (inclusive lower bound). queryParams.end `string` No Return entries strictly older than this timestamp (cursor / upper bound). queryParams.before `string` No Return entries strictly older than this timestamp (keyset pagination cursor). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). ## Response `Promise`: page of audit entries. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # revokeAgentCredential URL: https://pgbeam.com/docs/ts-sdk/agents/revokeAgentCredential Description: Revoke an agent credential Permanently revokes the credential and drops any live connections. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.agent\_id `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # rotateAgentCredential URL: https://pgbeam.com/docs/ts-sdk/agents/rotateAgentCredential Description: Rotate an agent credential's secrets Generates a new Postgres password and MCP token for the credential in place, keeping the same id, username, name, and policy. Live connections using the old password are dropped within seconds. The new secrets are returned once and cannot be retrieved again. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.agent\_id `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). ## Response `Promise`: secrets rotated. new secrets shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 The credential is revoked and cannot be rotated. --- # updateAgentCredentialStatus URL: https://pgbeam.com/docs/ts-sdk/agents/updateAgentCredentialStatus Description: Enable or disable an agent credential Toggles the kill-switch. Disabling drops live connections within seconds. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.agent\_id `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). body.status `"active" \| "disabled"` Yes Set active to re-enable or disabled to kill-switch. Use DELETE to revoke permanently. ## Response `Promise`: updated agent credential. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # verifyAuditChain URL: https://pgbeam.com/docs/ts-sdk/agents/verifyAuditChain Description: Verify the tamper-evident audit chain Recomputes the project's audit hash chain over an optional time range and reports whether it is intact. Each audit entry is linked to its predecessor with a SHA-256 hash, so editing or deleting any row breaks the chain. On a break, the response reports the first sequence number where a tampered or deleted entry was detected. Requires the same audit:read permission as the list and export endpoints. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.start `string` No Return entries at or after this timestamp (inclusive lower bound). queryParams.end `string` No Return entries strictly older than this timestamp (cursor / upper bound). ## Response `Promise`: chain verification result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # exportAccountData URL: https://pgbeam.com/docs/ts-sdk/account/exportAccountData Description: Export account data Returns all personal data associated with the authenticated user in a structured JSON format. Supports GDPR data portability and CCPA right to know. Audit logs are limited to the most recent 1000 entries. ## Usage ## Parameters None. ## Response `Promise`: account data export. ## Example ## Errors Status Description 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # getOnboardingProgress URL: https://pgbeam.com/docs/ts-sdk/account/getOnboardingProgress Description: Get onboarding progress Returns the onboarding checklist progress for an organization. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. ## Response `Promise`: onboarding progress. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # listOrganizations URL: https://pgbeam.com/docs/ts-sdk/account/listOrganizations Description: List organizations Lists the organizations visible to the caller's credential. An organization-scoped API key (pbo\_) returns exactly the organization it belongs to. A user credential (account-scoped API key or dashboard session token) returns the organizations the user is a member of, including the caller's role in each. ## Usage ## Parameters None. ## Response `Promise`: organizations visible to the caller. ## Example ## Errors Status Description 401 Missing or invalid authentication. 429 Rate limited. Try again later. --- # updateOnboardingProgress URL: https://pgbeam.com/docs/ts-sdk/account/updateOnboardingProgress Description: Update onboarding progress Mark an onboarding step as complete or dismiss the checklist. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. body.step `"project_created" \| "database_added" \| "connection_tested" \| "connection_string_copied" \| "first_query_run" \| "agent_credential_created"` No The onboarding step to mark as complete. body.dismiss `boolean` No Set to true to dismiss the onboarding checklist. ## Response `Promise`: updated onboarding progress. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getOrganizationPlan URL: https://pgbeam.com/docs/ts-sdk/analytics/getOrganizationPlan Description: Get organization plan Returns the current plan and limits for the organization. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. ## Response `Promise`: organization plan details. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # getOrganizationUsage URL: https://pgbeam.com/docs/ts-sdk/analytics/getOrganizationUsage Description: Get organization usage Returns daily usage data aggregated across all projects in the organization. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. queryParams.start\_date `string` Yes Start date (inclusive, YYYY-MM-DD). queryParams.end\_date `string` Yes End date (inclusive, YYYY-MM-DD). ## Response `Promise`: daily usage data. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # getProjectInsights URL: https://pgbeam.com/docs/ts-sdk/analytics/getProjectInsights Description: Get query insights for a project Returns aggregated query-level analytics for a project including top queries by count, cache hit/miss summary, and latency statistics. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.range `"1h" \| "6h" \| "24h" \| "7d"` No Time range to query. Defaults to 24h. queryParams.limit `number` No Maximum number of top queries to return (1-100). ## Response `Promise`: query insights for the project. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # getProjectUsage URL: https://pgbeam.com/docs/ts-sdk/analytics/getProjectUsage Description: Get project usage Returns daily usage data for a specific project, broken down by region. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.start\_date `string` Yes Start date (inclusive, YYYY-MM-DD). queryParams.end\_date `string` Yes End date (inclusive, YYYY-MM-DD). ## Response `Promise`: daily usage data by region. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # getVercelInstallation URL: https://pgbeam.com/docs/ts-sdk/analytics/getVercelInstallation Description: Get Vercel Marketplace installation status Returns the Vercel Marketplace installation for the organization, including its provisioned resources and their current-period usage. Returns 404 when the organization was not provisioned through the Vercel Marketplace. Powers the dashboard's Vercel integration page. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. ## Response `Promise`: vercel installation status. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # listPlans URL: https://pgbeam.com/docs/ts-sdk/analytics/listPlans Description: List available plans Returns all available plan tiers with their limits and pricing. ## Usage ## Parameters None. ## Response `Promise`: list of available plans. ## Example ## Errors Status Description 401 Missing or invalid authentication. 429 Rate limited. Try again later. --- # submitCancellationFeedback URL: https://pgbeam.com/docs/ts-sdk/analytics/submitCancellationFeedback Description: Submit cancellation feedback Records optional feedback when a user cancels their subscription. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. body.reason `string` No Predefined cancellation reason. body.feedback `string` No Free-text feedback from the user. ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # updateSpendLimit URL: https://pgbeam.com/docs/ts-sdk/analytics/updateSpendLimit Description: Update spend limit Sets the monthly spend limit for an organization. Null removes the limit. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. body.spend\_limit `number` No Monthly spend limit in dollars. Null to remove the limit. ## Response `Promise`: spend limit updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # listAnomalyAlerts URL: https://pgbeam.com/docs/ts-sdk/anomalies/listAnomalyAlerts Description: List anomaly alerts Lists anomaly alerts for the project, newest first, optionally filtered by status. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.status `"open" \| "acknowledged" \| "resolved"` No Filter to a single status. queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: page of anomaly alerts. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # updateAnomalyAlert URL: https://pgbeam.com/docs/ts-sdk/anomalies/updateAnomalyAlert Description: Triage an anomaly alert Updates the triage status of an anomaly alert (acknowledge or resolve). ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.anomaly\_id `string` Yes Unique anomaly alert identifier (prefixed, e.g. ano\_xxx). body.status `"acknowledged" \| "resolved"` Yes New triage state for the alert. ## Response `Promise`: the updated anomaly alert. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # approveApprovalRequest URL: https://pgbeam.com/docs/ts-sdk/approvals/approveApprovalRequest Description: Approve a held statement Approves a pending approval request, releasing the held statement. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.approval\_id `string` Yes Unique approval request identifier (prefixed, e.g. apr\_xxx). body.reason `string` No Human-readable note explaining the decision. ## Response `Promise`: the updated approval request. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Resource already exists or conflicts with current state. --- # listApprovalRequests URL: https://pgbeam.com/docs/ts-sdk/approvals/listApprovalRequests Description: List approval requests Lists approval requests for the project, newest first, optionally filtered by status. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.status `"pending" \| "approved" \| "rejected" \| "expired" \| "executed" \| "failed"` No Filter to a single status. queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: page of approval requests. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # rejectApprovalRequest URL: https://pgbeam.com/docs/ts-sdk/approvals/rejectApprovalRequest Description: Reject a held statement Rejects a pending approval request, denying the held statement. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.approval\_id `string` Yes Unique approval request identifier (prefixed, e.g. apr\_xxx). body.reason `string` No Human-readable note explaining the decision. ## Response `Promise`: the updated approval request. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Resource already exists or conflicts with current state. --- # discardDatabaseBranch URL: https://pgbeam.com/docs/ts-sdk/branches/discardDatabaseBranch Description: Discard a sandbox branch Marks an ephemeral sandbox branch as discarded for teardown. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.branch\_id `string` Yes Unique sandbox branch identifier (prefixed, e.g. brn\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # listDatabaseBranches URL: https://pgbeam.com/docs/ts-sdk/branches/listDatabaseBranches Description: List sandbox branches Lists ephemeral sandbox branches for the project's databases. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.status `"pending" \| "ready" \| "error" \| "discarded"` No Filter to a single status. queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: page of sandbox branches. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # createDatabase URL: https://pgbeam.com/docs/ts-sdk/databases/createDatabase Description: Add a database Registers a new upstream PostgreSQL database for the project. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.host `string` Yes PostgreSQL host. body.port `number` Yes PostgreSQL port. body.name `string` Yes PostgreSQL database name. body.username `string` Yes PostgreSQL username. body.password `string` Yes PostgreSQL password. Stored encrypted at rest. body.ssl\_mode `SSLMode` No PostgreSQL SSL connection mode. body.role `DatabaseRole` No Database role. Primary receives writes, replicas receive reads. body.pool\_region `string` No Region where the connection pool is maintained (near the database). When set and different from the client's edge region, queries are relayed through the pool region's data plane. Empty means direct connection. body.query\_timeout\_ms `number` No Query timeout in milliseconds. 0 means disabled (default). body.auto\_read\_routing `boolean` No Auto-route SELECT queries to read replicas. body.cache\_config `CacheConfig` No Query cache configuration. body.pool\_config `PoolConfig` No Connection pool configuration. ## Response `Promise`: database created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # deleteDatabase URL: https://pgbeam.com/docs/ts-sdk/databases/deleteDatabase Description: Delete a database Removes a database registration from the project. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getDatabase URL: https://pgbeam.com/docs/ts-sdk/databases/getDatabase Description: Get a database Returns a single database by ID. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `Promise`: database found. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getSchemaCatalog URL: https://pgbeam.com/docs/ts-sdk/databases/getSchemaCatalog Description: Read a database's schema catalog Connects to the upstream database read-only and returns its user relations (tables and views) and columns. Powers table/column autocomplete and view-aware warnings in the policy editor — relation kind distinguishes a view (whose masking/row-filters apply to the view itself, not its base tables) from a base table, and a per-column is\_binary flag flags columns that mask to NULL. System schemas are excluded; nothing is persisted. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `Promise`: schema catalog. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # listDatabases URL: https://pgbeam.com/docs/ts-sdk/databases/listDatabases Description: List databases Lists all databases registered for the project. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: list of databases. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # scanDatabaseForPii URL: https://pgbeam.com/docs/ts-sdk/databases/scanDatabaseForPii Description: Scan a database for likely-PII columns Connects to the upstream database read-only, inspects information\_schema and samples column values against PII heuristics, and returns ranked masking suggestions. Suggestions are advisory — the operator reviews them and applies the ones they want into a policy profile's masking rules. Nothing is auto-applied. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `Promise`: pii scan result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # testDatabaseConnection URL: https://pgbeam.com/docs/ts-sdk/databases/testDatabaseConnection Description: Test database connection Attempts to connect to the upstream database using the stored credentials and returns the result. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `Promise`: connection test result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # updateDatabase URL: https://pgbeam.com/docs/ts-sdk/databases/updateDatabase Description: Update a database Partially updates a database connection. Only provided fields are modified. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). body.host `string` No Updated PostgreSQL host. body.port `number` No Updated PostgreSQL port. body.name `string` No Updated PostgreSQL database name. body.username `string` No Updated PostgreSQL username. body.password `string` No Updated PostgreSQL password. body.ssl\_mode `SSLMode` No PostgreSQL SSL connection mode. body.role `DatabaseRole` No Database role. Primary receives writes, replicas receive reads. body.pool\_region `string` No Region where the connection pool is maintained (near the database). When set and different from the client's edge region, queries are relayed through the pool region's data plane. Empty means direct connection. body.query\_timeout\_ms `number` No Query timeout in milliseconds. 0 means disabled. body.auto\_read\_routing `boolean` No Auto-route SELECT queries to read replicas. body.cache\_config `CacheConfig` No Query cache configuration. body.pool\_config `PoolConfig` No Connection pool configuration. ## Response `Promise`: database updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # createHoneytoken URL: https://pgbeam.com/docs/ts-sdk/honeytokens/createHoneytoken Description: Register a honeytoken Registers a decoy (canary) relation for the project. Any agent statement that references it is blocked and recorded as a canary\_tripped audit event. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.schema\_name `string` No Optional schema. Null or empty matches the unqualified/public form. body.relation\_name `string` Yes Relation (table or view) name of the decoy. body.action `"audit_only" \| "kill"` Yes Response when the honeytoken is tripped. ## Response `Promise`: honeytoken registered. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # deleteHoneytoken URL: https://pgbeam.com/docs/ts-sdk/honeytokens/deleteHoneytoken Description: Delete a honeytoken Removes a honeytoken from the project. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.honeytoken\_id `string` Yes Unique honeytoken identifier (prefixed, e.g. hnt\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # getHoneytoken URL: https://pgbeam.com/docs/ts-sdk/honeytokens/getHoneytoken Description: Get a honeytoken Returns a single honeytoken by ID. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.honeytoken\_id `string` Yes Unique honeytoken identifier (prefixed, e.g. hnt\_xxx). ## Response `Promise`: the honeytoken. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # listHoneytokens URL: https://pgbeam.com/docs/ts-sdk/honeytokens/listHoneytokens Description: List honeytokens Lists the project's honeytokens. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: list of honeytokens. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # updateHoneytoken URL: https://pgbeam.com/docs/ts-sdk/honeytokens/updateHoneytoken Description: Update a honeytoken Updates a honeytoken's relation or action. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.honeytoken\_id `string` Yes Unique honeytoken identifier (prefixed, e.g. hnt\_xxx). body.schema\_name `string` No Optional schema. Null or empty matches the unqualified/public form. body.relation\_name `string` Yes Relation (table or view) name of the decoy. body.action `"audit_only" \| "kill"` Yes Response when the honeytoken is tripped. ## Response `Promise`: updated honeytoken. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # handleSlackSupportEvent URL: https://pgbeam.com/docs/ts-sdk/internal/handleSlackSupportEvent Description: Handle a Slack support event Receives a forwarded Slack event from the dashboard webhook handler and creates a support message. ## Usage ## Parameters Parameter Type Required Description body.channel\_id `string` Yes Slack channel ID where the message was posted. body.thread\_ts `string` Yes Slack thread timestamp identifying the support case thread. body.user\_id `string` Yes Slack user ID of the message author. body.text `string` Yes Message text from Slack. ## Response `Promise`: the result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. --- # lintMigration URL: https://pgbeam.com/docs/ts-sdk/migrations/lintMigration Description: Lint a migration Analyzes a migration script for unsafe schema changes and returns findings. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.sql `string` Yes The migration SQL to analyze. May contain multiple statements. body.database\_id `string` No Optional database to scope the lint to. ## Response `Promise`: lint results. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # createSelfHostEnrollment URL: https://pgbeam.com/docs/ts-sdk/platform/createSelfHostEnrollment Description: Issue a self-host enrollment token Issues an enrollment token a self-hosted (BYOC) proxy uses to authenticate to the control plane's config/audit gRPC stream. The token is returned once and cannot be retrieved again. Requires the Scale or enterprise plan. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. body.region\_label `string` No Operator-supplied label for where the proxy runs. body.description `string` No Optional human-readable note. body.expires\_at `string` No Optional expiry. When set, the enrollment token stops authenticating new proxy connections at this time (must be in the future). Omit or set null for a token that never expires. ## Response `Promise`: enrollment created. token shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 The organization's plan is not entitled to self-host. 429 Rate limited. Try again later. --- # getHealth URL: https://pgbeam.com/docs/ts-sdk/platform/getHealth Description: Health check Returns the health status of the API server. ## Usage ## Parameters None. ## Response `Promise`: service is healthy. ## Example ## Errors Status Description 429 Rate limited. Try again later. --- # listRegions URL: https://pgbeam.com/docs/ts-sdk/platform/listRegions Description: List available regions Returns all active data plane regions. ## Usage ## Parameters None. ## Response `Promise`: list of regions. ## Example ## Errors Status Description 401 Missing or invalid authentication. 429 Rate limited. Try again later. --- # listSelfHostEnrollments URL: https://pgbeam.com/docs/ts-sdk/platform/listSelfHostEnrollments Description: List self-host enrollments Lists an organization's self-host enrollments. Tokens are never returned. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. ## Response `Promise`: list of enrollments. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. --- # revokeSelfHostEnrollment URL: https://pgbeam.com/docs/ts-sdk/platform/revokeSelfHostEnrollment Description: Revoke a self-host enrollment Revokes an enrollment so its token can no longer authenticate a proxy. Connected proxies keep their last-known config until they reconnect. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. pathParams.enrollment\_id `string` Yes Unique enrollment identifier. ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # rotateSelfHostEnrollment URL: https://pgbeam.com/docs/ts-sdk/platform/rotateSelfHostEnrollment Description: Rotate a self-host enrollment token Mints a new enrollment token in place, keeping the same enrollment id, metadata, and expiry. The swap is atomic: the old token stops authenticating new proxy connections the moment this call returns. An already-connected proxy keeps its existing gRPC streams until it disconnects, then must present the new token to reconnect. The new token is returned once and cannot be retrieved again. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. pathParams.enrollment\_id `string` Yes Unique enrollment identifier. ## Response `Promise`: token rotated. new token shown once. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 The enrollment is revoked and cannot be rotated. --- # createPolicyProfile URL: https://pgbeam.com/docs/ts-sdk/policies/createPolicyProfile Description: Create a policy profile Creates a policy profile that can be attached to agent credentials. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.name `string` Yes Human-readable name for the policy profile. body.access\_mode `"read_only" \| "read_write"` No read\_only blocks all data and schema mutations. body.statement\_rules `StatementRules` No Per-statement-kind allow/deny lists. Empty allow means all kinds permitted by the access mode. body.table\_allowlist `string[]` No If non-empty, only these relations are reachable. A bare entry grants the public schema only; list another schema in full, as in billing.orders. body.table\_denylist `string[]` No Relations explicitly blocked. A bare entry blocks that relation in every schema. body.masking\_rules `MaskingRule[]` No Column masking rules applied to query results. body.budget\_queries\_per\_hour `number` No Max queries per rolling hour window. 0 means unlimited. body.budget\_queries\_per\_day `number` No Max queries per day window. 0 means unlimited. body.max\_rows `number` No Max rows returned per query. 0 means unlimited. body.statement\_timeout\_ms `number` No Upstream statement timeout for agent sessions. 0 uses the project default. body.row\_filters `RowFilter[]` No Per-relation row filters ANDed into agent reads. body.write\_mode `"normal" \| "rollback" \| "sandbox"` No How writes are handled. normal commits, rollback auto-rolls back, sandbox routes to an ephemeral branch. body.approval\_mode `"off" \| "writes" \| "ddl" \| "all"` No Which statement classes require human approval before execution. body.approval\_auto\_max\_rows `number` No Statements touching at most this many rows are auto-approved. 0 means none. body.approval\_timeout\_seconds `number` No How long a held statement waits for a decision before expiring. body.migration\_safety `"off" \| "warn" \| "block"` No Migration safety mode. warn surfaces findings, block refuses unsafe DDL. body.egress\_bytes\_per\_day `number` No Per-day egress budget in bytes. 0 means unlimited. body.max\_affected\_rows `number` No Hard cap on rows a single write (INSERT/UPDATE/DELETE) may affect. A write whose affected-row count would exceed this is executed inside a transaction, checked, and rolled back so nothing persists, then blocked. Enforced independently of human approval. 0 means unlimited. ## Response `Promise`: policy profile created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # deletePolicyProfile URL: https://pgbeam.com/docs/ts-sdk/policies/deletePolicyProfile Description: Delete a policy profile Deletes a policy profile. Fails if agent credentials still reference it. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.policy\_id `string` Yes Unique policy profile identifier (prefixed, e.g. pol\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 409 Policy profile is still referenced by agent credentials. --- # dryEvalPolicy URL: https://pgbeam.com/docs/ts-sdk/policies/dryEvalPolicy Description: Dry-eval a policy against a SQL statement Evaluates a single SQL statement against a policy (either a draft policy supplied inline or an existing policy referenced by id) and returns the decision the proxy would make: allow, block, mask, or row-filter. The evaluation reuses the data plane's own policy engine (the same parser, allow/block rules, row-filter rewriter, and masking analysis enforced on live agent sessions), so a what-if verdict matches real enforcement. Stateful checks a single-statement preview cannot model (per-region query and egress budgets, human approvals, and rollback/sandbox write routing) are reported as informational notes, not verdicts. This is a pure compute endpoint; it does not connect to the upstream database and persists nothing. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.sql `string` Yes The single SQL statement to evaluate. body.policy\_id `string` No ID of an existing saved policy profile to evaluate against. body.policy `PolicyProfileInput` No Mutable fields of a policy profile (used for create and update). ## Response `Promise`: the dry-eval decision. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getPolicyProfile URL: https://pgbeam.com/docs/ts-sdk/policies/getPolicyProfile Description: Get a policy profile Returns a single policy profile by ID. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.policy\_id `string` Yes Unique policy profile identifier (prefixed, e.g. pol\_xxx). ## Response `Promise`: the policy profile. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # listPolicyProfiles URL: https://pgbeam.com/docs/ts-sdk/policies/listPolicyProfiles Description: List policy profiles Lists all policy profiles for the project. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: list of policy profiles. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # recommendAgentPolicy URL: https://pgbeam.com/docs/ts-sdk/policies/recommendAgentPolicy Description: Recommend a least-privilege policy from recorded traffic Derives the tightest policy that would still pass every statement this agent credential has legitimately run, using its recorded audit history over a lookback window (default 30 days). The candidate's table allowlist is the union of relations actually referenced, its statement-kind allow set is the observed set, it downgrades to read-only when no writes were seen, and its max\_rows ceiling comes from an observed high-percentile row count. The candidate is proven safe by replaying it through the data plane's own policy engine against the same history: a good recommendation has replay.summary.newly\_blocked == 0. This endpoint is advisory only. It reads the audit log, never connects to the upstream database, and never creates, updates, or mutates any policy or credential; the operator loads the candidate into the editor and saves it themselves. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.agent\_id `string` Yes Unique agent credential identifier (prefixed, e.g. agt\_xxx). body.lookback\_days `number` No How many days of recorded audit history to analyze. body.limit `number` No Maximum number of distinct query shapes to analyze and replay, newest first. Traffic is deduplicated by normalized query hash. ## Response `Promise`: the recommended candidate policy and its replay proof. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # replayPolicy URL: https://pgbeam.com/docs/ts-sdk/policies/replayPolicy Description: Replay recorded agent traffic against a policy Replays the project's recorded agent audit traffic against a candidate policy (either a draft supplied inline or an existing policy referenced by id) and reports what would change: which queries that ran would now be blocked, which blocked queries would now be permitted, and which results would be masked or row-filtered. Traffic is deduplicated by normalized query shape, newest first, and every statement is evaluated through the data plane's own policy engine, so the verdicts match real enforcement. Stateful checks (budgets, approvals, write-mode routing) are reported as informational notes on each result, not verdicts. This endpoint reads only the audit log; it never connects to the upstream database and persists nothing. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.policy\_id `string` No ID of an existing saved policy profile to replay against. body.policy `PolicyProfileInput` No Mutable fields of a policy profile (used for create and update). body.credential\_id `string` No Restrict the replay to traffic recorded for one agent credential. body.bound\_policy\_id `string` No Restrict the replay to traffic recorded for the agent credentials currently bound to this policy profile. Use it to preview a change to a live policy against the traffic that policy actually governs: without it the replay covers every credential in the project, including credentials bound to other profiles, whose behaviour saving this candidate cannot change. Mutually exclusive with credential\_id. body.start\_ts `string` No Start of the traffic window (inclusive). Defaults to 7 days before end\_ts. body.end\_ts `string` No End of the traffic window (exclusive). Defaults to now. body.limit `number` No Maximum number of distinct queries to replay, newest first. Traffic is deduplicated by normalized query hash before evaluation. ## Response `Promise`: the replay summary and per-query decisions. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # updatePolicyProfile URL: https://pgbeam.com/docs/ts-sdk/policies/updatePolicyProfile Description: Update a policy profile Updates a policy profile. Changes hot-reload to active agent sessions. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.policy\_id `string` Yes Unique policy profile identifier (prefixed, e.g. pol\_xxx). body.name `string` Yes Human-readable name for the policy profile. body.access\_mode `"read_only" \| "read_write"` No read\_only blocks all data and schema mutations. body.statement\_rules `StatementRules` No Per-statement-kind allow/deny lists. Empty allow means all kinds permitted by the access mode. body.table\_allowlist `string[]` No If non-empty, only these relations are reachable. A bare entry grants the public schema only; list another schema in full, as in billing.orders. body.table\_denylist `string[]` No Relations explicitly blocked. A bare entry blocks that relation in every schema. body.masking\_rules `MaskingRule[]` No Column masking rules applied to query results. body.budget\_queries\_per\_hour `number` No Max queries per rolling hour window. 0 means unlimited. body.budget\_queries\_per\_day `number` No Max queries per day window. 0 means unlimited. body.max\_rows `number` No Max rows returned per query. 0 means unlimited. body.statement\_timeout\_ms `number` No Upstream statement timeout for agent sessions. 0 uses the project default. body.row\_filters `RowFilter[]` No Per-relation row filters ANDed into agent reads. body.write\_mode `"normal" \| "rollback" \| "sandbox"` No How writes are handled. normal commits, rollback auto-rolls back, sandbox routes to an ephemeral branch. body.approval\_mode `"off" \| "writes" \| "ddl" \| "all"` No Which statement classes require human approval before execution. body.approval\_auto\_max\_rows `number` No Statements touching at most this many rows are auto-approved. 0 means none. body.approval\_timeout\_seconds `number` No How long a held statement waits for a decision before expiring. body.migration\_safety `"off" \| "warn" \| "block"` No Migration safety mode. warn surfaces findings, block refuses unsafe DDL. body.egress\_bytes\_per\_day `number` No Per-day egress budget in bytes. 0 means unlimited. body.max\_affected\_rows `number` No Hard cap on rows a single write (INSERT/UPDATE/DELETE) may affect. A write whose affected-row count would exceed this is executed inside a transaction, checked, and rolled back so nothing persists, then blocked. Enforced independently of human approval. 0 means unlimited. ## Response `Promise`: updated policy profile. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # deleteSchemaAnnotation URL: https://pgbeam.com/docs/ts-sdk/schemaannotations/deleteSchemaAnnotation Description: Delete a schema annotation Removes a single annotation identified by its natural key. Omit column\_name to delete a table-level annotation, and omit schema\_name to match the unqualified form. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.table\_name `string` Yes Relation (table or view) the annotation describes. queryParams.schema\_name `string` No Optional schema. Omit to match the unqualified form. queryParams.column\_name `string` No Optional column. Omit to delete a table-level annotation. ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # listSchemaAnnotations URL: https://pgbeam.com/docs/ts-sdk/schemaannotations/listSchemaAnnotations Description: List schema annotations Lists the project's human-written table and column descriptions. These are surfaced to connected agents through the MCP schema catalog. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: list of schema annotations. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # putSchemaAnnotation URL: https://pgbeam.com/docs/ts-sdk/schemaannotations/putSchemaAnnotation Description: Create or replace a schema annotation Attaches an operator-written description to a table (omit column\_name) or a column. Keyed by (schema\_name, table\_name, column\_name); an existing annotation with the same key is replaced. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.schema\_name `string` No Optional schema. Null or empty matches the unqualified form. body.table\_name `string` Yes Relation (table or view) the annotation describes. body.column\_name `string` No Optional column. Null describes the table itself. body.description `string` Yes The operator-written description text. ## Response `Promise`: the created or updated annotation. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # createCustomDomain URL: https://pgbeam.com/docs/ts-sdk/projects/createCustomDomain Description: Add a custom domain Registers a new custom domain for the project. Returns DNS verification instructions. Requires a Scale or Enterprise plan. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.domain `string` Yes The custom domain name to add (e.g., db.example.com). ## Response `Promise`: custom domain created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Custom domains require a Scale or Enterprise plan. 404 Resource not found. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # createProject URL: https://pgbeam.com/docs/ts-sdk/projects/createProject Description: Create a project Creates a new project within the specified organization. ## Usage ## Parameters Parameter Type Required Description body.name `string` Yes Human-readable project name. body.org\_id `string` Yes Better Auth organization ID. body.description `string` No Optional project description. body.tags `string[]` No User-defined labels to attach to the project. body.cloud `"aws" \| "azure" \| "gcp"` No Cloud provider for the project. body.self\_hosted `boolean` No Mark this project as running on a self-hosted (BYOC) data plane in the customer's own VPC/cluster. Requires the Scale or enterprise plan. body.database `CreateDatabaseRequest` Yes Request body for registering an upstream database. ## Response `Promise`: project created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 409 Resource already exists or conflicts with current state. 429 Rate limited. Try again later. --- # createReplica URL: https://pgbeam.com/docs/ts-sdk/projects/createReplica Description: Add a replica Adds a read replica to a database. ## Usage ## Parameters Parameter Type Required Description pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). body.host `string` Yes PostgreSQL replica host. body.port `number` Yes PostgreSQL replica port. body.ssl\_mode `SSLMode` No PostgreSQL SSL connection mode. ## Response `Promise`: replica created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # deleteCustomDomain URL: https://pgbeam.com/docs/ts-sdk/projects/deleteCustomDomain Description: Delete a custom domain Removes a custom domain from the project and revokes its TLS certificate. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.domain\_id `string` Yes Unique custom domain identifier (prefixed, e.g. dom\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # deleteProject URL: https://pgbeam.com/docs/ts-sdk/projects/deleteProject Description: Delete a project Soft-deletes a project and all associated databases. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # deleteReplica URL: https://pgbeam.com/docs/ts-sdk/projects/deleteReplica Description: Delete a replica Removes a read replica from a database. ## Usage ## Parameters Parameter Type Required Description pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). pathParams.replica\_id `string` Yes Unique replica identifier (prefixed, e.g. rep\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getProject URL: https://pgbeam.com/docs/ts-sdk/projects/getProject Description: Get a project Returns a single project by ID. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). ## Response `Promise`: project found. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # getProjectMetrics URL: https://pgbeam.com/docs/ts-sdk/projects/getProjectMetrics Description: Get project metrics Returns recent project metrics snapshots, optionally filtered by region. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.limit `number` No Maximum number of recent snapshots to return. queryParams.region `string` No Filter metrics by region code. ## Response `Promise`: metrics snapshots ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 404 Resource not found. 429 Rate limited. Try again later. --- # listCacheRules URL: https://pgbeam.com/docs/ts-sdk/projects/listCacheRules Description: List cache rules Returns the cache rules for a database, showing all observed query shapes with their stats and cache recommendations. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: cache rule entries. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # listCustomDomains URL: https://pgbeam.com/docs/ts-sdk/projects/listCustomDomains Description: List custom domains Lists all custom domains registered for the project. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: list of custom domains. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # listProjects URL: https://pgbeam.com/docs/ts-sdk/projects/listProjects Description: List projects Lists projects filtered by organization. Requires org\_id query parameter. ## Usage ## Parameters Parameter Type Required Description queryParams.org\_id `string` Yes Organization ID to filter projects. queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. queryParams.sort\_by `"name" \| "created_at" \| "active_connections"` No Sort field for projects list. ## Response `Promise`: list of projects. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 429 Rate limited. Try again later. --- # listReplicas URL: https://pgbeam.com/docs/ts-sdk/projects/listReplicas Description: List replicas Lists all read replicas for a database. ## Usage ## Parameters Parameter Type Required Description pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). ## Response `Promise`: list of replicas. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # updateCacheRule URL: https://pgbeam.com/docs/ts-sdk/projects/updateCacheRule Description: Update cache rule Enable or disable caching for a specific query shape, with optional TTL and SWR overrides. Requires the query to exist in the cache rules. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.database\_id `string` Yes Unique database identifier (prefixed, e.g. db\_xxx). pathParams.query\_hash `string` Yes xxhash64 hex of the normalized SQL. body.cache\_enabled `boolean` Yes Whether to enable caching for this query shape. body.cache\_ttl\_seconds `number` No TTL override in seconds. Null to use project default. body.cache\_swr\_seconds `number` No SWR override in seconds. Null to use project default. ## Response `Promise`: cache rule updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # updateProject URL: https://pgbeam.com/docs/ts-sdk/projects/updateProject Description: Update a project Partially updates a project. Only provided fields are modified. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.name `string` No Updated project name. body.description `string` No Updated project description. body.tags `string[]` No Replacement set of user-defined project labels. body.status `ProjectStatus` No Project lifecycle status. body.allowed\_cidrs `CidrEntry[]` No IP filtering rules as CIDR ranges with optional labels. Empty array means allow all. Both IPv4 and IPv6 CIDR notation are supported. body.default\_policy\_profile\_id `string` No When set, passthrough/human connections are enforced against this policy profile. Send an empty string to clear. body.residency `DataResidency` No Data-residency requirement for the project. "any" (default) lets queries be served from the nearest data-plane metro. "us" or "eu" require the serving metro to be in that jurisdiction; the proxy fails a connection closed when it is served from a metro outside the required jurisdiction, so regulated workloads never process outside their permitted region. body.agents\_disabled `boolean` No Project-level kill-switch. Set true to block ALL agent-credential connections to this project (live agent sessions are dropped within seconds); set false to re-enable them. Passthrough/human connections are unaffected. Engaging the kill-switch emits a kill\_switch webhook event. ## Response `Promise`: project updated. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # verifyCustomDomain URL: https://pgbeam.com/docs/ts-sdk/projects/verifyCustomDomain Description: Verify custom domain DNS Checks DNS TXT record to verify domain ownership. Updates domain status on success. Requires a Scale or Enterprise plan. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.domain\_id `string` Yes Unique custom domain identifier (prefixed, e.g. dom\_xxx). ## Response `Promise`: verification result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Custom domains require a Scale or Enterprise plan. 404 Resource not found. 429 Rate limited. Try again later. --- # createSupportCase URL: https://pgbeam.com/docs/ts-sdk/support/createSupportCase Description: Create a support case Creates a new support case with an initial message. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. body.org\_id `string` Yes Organization ID. body.title `string` Yes Brief summary of the issue. body.severity `number` No Severity level: 1=Critical, 2=High, 3=Normal, 4=Low. body.body `string` Yes Initial message body. ## Response `Promise`: support case created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. --- # createSupportMessage URL: https://pgbeam.com/docs/ts-sdk/support/createSupportMessage Description: Add a message to a support case Adds a new message to an existing support case thread. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. pathParams.case\_id `string` Yes Unique support case identifier (prefixed, e.g. sc\_xxx). body.body `string` Yes Message content. ## Response `Promise`: message created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # getSupportCase URL: https://pgbeam.com/docs/ts-sdk/support/getSupportCase Description: Get a support case Returns a support case with all its messages. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. pathParams.case\_id `string` Yes Unique support case identifier (prefixed, e.g. sc\_xxx). ## Response `Promise`: support case with messages. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # listSupportCases URL: https://pgbeam.com/docs/ts-sdk/support/listSupportCases Description: List support cases Lists support cases for the organization with optional status and search filters. ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. queryParams.status `SupportCaseStatus` No Filter by case status. queryParams.search `string` No Search cases by title. queryParams.page\_size `number` No Number of results per page (1-100, default 20). queryParams.page `number` No Page number (1-based, default 1). ## Response `Promise`: list of support cases. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. --- # updateSupportCase URL: https://pgbeam.com/docs/ts-sdk/support/updateSupportCase Description: Update a support case Updates the status of a support case (close or reopen). ## Usage ## Parameters Parameter Type Required Description pathParams.org\_id `string` Yes Unique organization identifier. pathParams.case\_id `string` Yes Unique support case identifier (prefixed, e.g. sc\_xxx). body.status `SupportCaseStatus` No Current status of the support case. ## Response `Promise`: updated support case. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # createWebhookEndpoint URL: https://pgbeam.com/docs/ts-sdk/webhooks/createWebhookEndpoint Description: Create a webhook endpoint Creates a webhook endpoint that receives project event deliveries. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). body.url `string` Yes HTTPS endpoint that receives event deliveries. body.secret `string` No Shared secret used to sign delivery payloads. Write-only. body.format `"json" \| "splunk_hec" \| "datadog" \| "elastic"` No Payload format for delivered events. body.event\_types `string[]` No Event types to deliver. Empty means all events. body.enabled `boolean` No Whether deliveries are active for this endpoint. body.description `string` No Human-readable label for the endpoint. ## Response `Promise`: webhook endpoint created. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # deleteWebhookEndpoint URL: https://pgbeam.com/docs/ts-sdk/webhooks/deleteWebhookEndpoint Description: Delete a webhook endpoint Deletes a webhook endpoint and its pending deliveries. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.webhook\_id `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). ## Response `Promise`: no content. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # getWebhookEndpoint URL: https://pgbeam.com/docs/ts-sdk/webhooks/getWebhookEndpoint Description: Get a webhook endpoint Returns a single webhook endpoint by ID. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.webhook\_id `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). ## Response `Promise`: the webhook endpoint. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # listWebhookEndpoints URL: https://pgbeam.com/docs/ts-sdk/webhooks/listWebhookEndpoints Description: List webhook endpoints Lists webhook endpoints for the project. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). queryParams.page\_size `number` No Maximum number of items to return (1-100, default 20). queryParams.page\_token `string` No Opaque token for cursor-based pagination. ## Response `Promise`: list of webhook endpoints. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. 429 Rate limited. Try again later. --- # testWebhookEndpoint URL: https://pgbeam.com/docs/ts-sdk/webhooks/testWebhookEndpoint Description: Send a test event Enqueues a test event delivery to the webhook endpoint. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.webhook\_id `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). ## Response `Promise`: the result. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # updateWebhookEndpoint URL: https://pgbeam.com/docs/ts-sdk/webhooks/updateWebhookEndpoint Description: Update a webhook endpoint Updates a webhook endpoint. ## Usage ## Parameters Parameter Type Required Description pathParams.project\_id `string` Yes Unique project identifier (prefixed, e.g. prj\_xxx). pathParams.webhook\_id `string` Yes Unique webhook endpoint identifier (prefixed, e.g. whk\_xxx). body.url `string` Yes HTTPS endpoint that receives event deliveries. body.secret `string` No Shared secret used to sign delivery payloads. Write-only. body.format `"json" \| "splunk_hec" \| "datadog" \| "elastic"` No Payload format for delivered events. body.event\_types `string[]` No Event types to deliver. Empty means all events. body.enabled `boolean` No Whether deliveries are active for this endpoint. body.description `string` No Human-readable label for the endpoint. ## Response `Promise`: updated webhook endpoint. ## Example ## Errors Status Description 400 Invalid request parameters. 401 Missing or invalid authentication. 403 Operation not allowed by current plan limits. 404 Resource not found. --- # cache-rules list URL: https://pgbeam.com/docs/cli/projects/cache-rules/list Description: List cache rules for a database List all tracked query shapes and their caching status for a database. Shows the query hash, a truncated SQL pattern, query type, whether caching is enabled, call count, average latency, and PgBeam's caching recommendation. Results are paginated — use `--page-size` and `--page-token` to navigate pages. ## Usage ## Options Option Description Required Default `--database-id ` ID of the database whose cache rules to list Yes - `--page-size ` Number of entries per page (1-100). Defaults to the API default. No - `--page-token ` Pagination token returned from a previous list call to fetch the next page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: Hash, Query, Type, Cached, Calls, Avg (ms), and Recommendation. If more pages are available, prints the `--page-token` value for the next page. With `--json`, returns the full paginated response. --- # cache-rules set URL: https://pgbeam.com/docs/cli/projects/cache-rules/set Description: Update cache rule for a query Enable or disable caching for a specific query shape, identified by its xxhash64 hash. You can optionally override the TTL (time-to-live) and SWR (stale-while-revalidate) durations. Omitting `--ttl` or `--swr` uses the project-level defaults. Use `pgbeam cache-rules list` to find query hashes. ## Usage ## Options Option Description Required Default `` Query hash (xxhash64 hex) identifying the query shape. Find this via `pgbeam cache-rules list`. Yes - `--database-id ` ID of the database that owns the query Yes - `--enabled ` Whether to enable caching for this query: "true" or "false" Yes - `--ttl ` TTL (time-to-live) override in seconds. Omit to use the project default. No - `--swr ` SWR (stale-while-revalidate) override in seconds. Omit to use the project default. No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the updated cache rule showing whether caching is enabled, the TTL, and the SWR duration. With `--json`, returns the full cache rule entry. --- # env pull URL: https://pgbeam.com/docs/cli/projects/env/pull Description: Write DATABASE_URL template to .env Write a `DATABASE_URL` connection string template to a `.env` file (or a custom file via `--file`). The URL points to the project's PgBeam proxy host. You'll need to replace `USER`, `PASS`, and `YOUR_DB` with your actual upstream database credentials. If the file already contains a `DATABASE_URL`, you'll be prompted before overwriting unless `--yes` is passed. ## Usage ## Options Option Description Required Default `--file ` Path to the output file No `.env` `--yes`, `-y` Skip the confirmation prompt if the file already contains DATABASE\_URL No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming the file was written and reminds you to replace the placeholder credentials (USER, PASS, YOUR\_DB). --- # domains add URL: https://pgbeam.com/docs/cli/projects/domains/add Description: Add a custom domain Registers a new custom domain for the project. Returns DNS verification instructions. Requires a Scale or Enterprise plan. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # domains delete URL: https://pgbeam.com/docs/cli/projects/domains/delete Description: Delete a custom domain Removes a custom domain from the project and revokes its TLS certificate. ## Usage ## Options Option Description Required Default `` Yes - `--yes`, `-y` Skip the confirmation prompt (useful for scripts and CI/CD) No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # domains list URL: https://pgbeam.com/docs/cli/projects/domains/list Description: List custom domains Lists all custom domains registered for the project. ## Usage ## Options Option Description Required Default `--limit ` Maximum number of items (1-100) No - `--all` Fetch every page No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # domains verify URL: https://pgbeam.com/docs/cli/projects/domains/verify Description: Verify custom domain DNS Checks DNS TXT record to verify domain ownership. Updates domain status on success. Requires a Scale or Enterprise plan. ## Usage ## Options Option Description Required Default `` Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Renders a human-readable table or detail view by default; pass `--json` for the raw API response. --- # replicas add URL: https://pgbeam.com/docs/cli/projects/replicas/add Description: Add a read replica Add a read replica to a database connection. PgBeam can route read-only queries to replicas for improved performance and load distribution. Without the `--host` flag, the command prompts for the replica hostname interactively. ## Usage ## Options Option Description Required Default `--database-id ` ID of the database to add the replica to Yes - `--host ` Hostname or IP address of the replica server No - `--port ` Port number of the replica server No `5432` `--ssl-mode ` SSL connection mode: disable, require, verify-ca, or verify-full No - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints the new replica ID. With `--json`, returns the full replica object. --- # replicas delete URL: https://pgbeam.com/docs/cli/projects/replicas/delete Description: Remove a read replica Remove a read replica from a database. PgBeam will stop routing queries to this replica. The upstream replica server is not affected. A confirmation prompt is shown unless `--yes` is passed. ## Usage ## Options Option Description Required Default `` ID of the replica to remove Yes - `--database-id ` ID of the database that owns the replica Yes - `--yes`, `-y` Skip the confirmation prompt No `false` All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Prints a success message confirming the replica was deleted. --- # replicas list URL: https://pgbeam.com/docs/cli/projects/replicas/list Description: List read replicas List all read replicas configured for a database. Shows each replica's ID, host, port, and SSL mode. ## Usage ## Options Option Description Required Default `--database-id ` ID of the database whose replicas to list Yes - All global options (`--token`, `--profile`, `--project`, `--org`, `--json`, `--no-color`, `--no-trunc`, `--debug`) are also available on this command. ## Examples ## Output Displays a table with columns: ID, Host, Port, and SSL. With `--json`, returns the full replica list from the API.