Setting up a data warehouse source

From PostHog/skills · View interactive version

Setting up a data warehouse source is an AI agent skill from the GitHub repository PostHog/skills. Guide the user through connecting a new data warehouse source, including databases, SaaS tools, and bucket files. Use when the user wants to "connect Stripe", "import data from Postgres", "import files from a bucket", "upload a file", "add a new data source", or pick sync methods for each table. Thi

How to use this skill

Skill file

Setting up a data warehouse source

Use this skill when the user wants to connect an external data source to PostHog's data warehouse for the first time.

Use AmazonS3 for Amazon S3, GoogleCloudStorage for Google Cloud Storage, AzureBlob for Azure Blob, and

CloudflareR2 for Cloudflare R2. For a local file, direct the user to upload it in the PostHog app. That flow

creates a FileUpload source. No MCP tool uploads files.

Bucket sources use full_refresh by default.

Default to the one-step flow: data-warehouse-source-setup validates credentials, discovers every table, enables

them with sensible sync defaults (incremental where possible), and creates the source in a single call — no

schemas array to assemble. For credentials, hand the user a secure browser link with data-warehouse-source-connect-link

instead of collecting secrets in chat. Only drop to the manual wizard → db-schema → create flow when the user wants to

hand-pick which tables sync or set non-default sync types per table.

When to use this skill

Available tools

| Tool | Purpose |

| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |

| data-warehouse-source-connect-link | Preferred for credentials — get a secure browser/OAuth link so the user authenticates without pasting secrets in chat |

| data-warehouse-source-setup | Preferred to create — one call: validate creds, discover tables, apply sync defaults, create the source |

| external-data-sources-wizard | Discover which source types exist and what fields each needs (advanced flow) |

| external-data-sources-db-schema | Validate credentials and list tables with available sync methods per table (advanced flow) |

| external-data-sources-create | Advanced create — requires a schemas array built from the db-schema response |

| external-data-sources-check-cdc-prerequisites-create | Postgres CDC pre-flight check (optional, only for Postgres CDC) |

| external-data-sources-webhook-info-retrieve | Check if a source supports webhooks and whether one has been registered |

| external-data-sources-create-webhook-create | Register a webhook with the external service after source creation |

| external-data-sources-update-webhook-inputs-create | Supply the signing secret manually when auto-registration failed |

| external-data-sources-list | After creation, confirm the source is listed and see its initial status |

| external-data-schemas-list | See per-table sync status once the source is created |

| external-data-destinations-list | See existing destinations, including the PostHog warehouse |

| external-data-destinations-connect-link | Secure browser link where the user enters a destination's credentials; returns nothing secret |

| external-data-destinations-connect-link-status | Poll with the link's connect_token to get the integration the user saved |

| external-data-destinations-create | Create a destination from the integration the connect page saved |

| external-data-destinations-add-sources | Attach existing sources to a destination |

| external-data-sources-destinations-update | Set a source's full destination list, for example to keep the PostHog warehouse before attaching |

| external-data-destinations-test-connection | Diagnose a destination that is failing or paused (does not resume it) |

Pre-flight: credential gotchas that cause most failures

Surface these before collecting credentials — they're the top reasons setup fails on the first try. Validating

against them up front avoids burning credential prompts on retries.

(10.x, 192.168.x, 172.16–31.x) are rejected — PostHog runs the connection from its own infrastructure, not the

user's machine. Serverless/managed Postgres (Neon, Supabase, RDS behind strict rules) often also needs PostHog's

egress IPs allowlisted first. If the DB isn't publicly reachable, route to the browser deep-link

(data-warehouse-source-connect-link) or an SSH tunnel rather than collecting credentials that can't validate.

direct host is IPv6-only). The pooler host looks like aws-0-<region>.pooler.supabase.com, the username must be

postgres.<project-ref>, and the port is 6543 (not 5432). The password is the database password (Settings →

Database), which is distinct from the anon/service_role JWT keys and from the Supabase account password. If

SUPABASE_URL is in the project env, derive the project ref from db.<ref>.supabase.co to pre-fill these instead of

asking the user to guess.

import needs a full/read-access key.

can't resolve it — the create/db-schema/setup calls reject it with a clear error. Resolve it to the real value

first, or collect credentials via data-warehouse-source-connect-link and pass the resulting credential_id.

Recommended: one-step setup

Most setups should use this path — it avoids the most common failures (skipping db-schema, malformed schemas,

missing required fields).

  1. Discover the source type and its fields (optional): external-data-sources-wizard lists every source type and

the credential fields each needs. Use it to know what to ask the user for; skip it if the source type is obvious.

  1. Collect credentials securely: call data-warehouse-source-connect-link({source_type}). It returns a

connect_url to a minimal connect page rendering the source's full connection form — the user authorizes via

OAuth or enters credentials there, whichever the source offers (the response's auth_method tells you which to

expect). The page validates the details against a live connection and stashes them encrypted in a temporary

store — it does NOT create the source. After the user confirms they're done, find the stored credential id via

data-warehouse-stored-credentials-list (filter by source_type, newest first; the page also shows the id to

the user) and pass {"credential_id": <id>} to setup. Stored credentials are single-use — deleted as soon as

setup consumes them — and expire after 24 hours.

Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.

  1. Create in one call: data-warehouse-source-setup({source_type, payload, prefix}). The server validates

credentials, discovers all tables, enables them with sync defaults (incremental where a tracking column exists,

else append, else full_refresh — never CDC), sets created_via=mcp, and creates the source. The payload carries

a credential reference ({"credential_id": ...} or the OAuth integration id key) — or inline credentials for

headless automation; no schemas array is needed. On success you get the new source id; call

external-data-schemas-list to show the user what was enabled and how each table will sync.

The OAuth integration id key is different for every source.

Do not guess it: call external-data-sources-wizard with the source_type and use the name of the field whose type is oauth

(for example google_ads_integration_id for GoogleAds).

A failed call returns a 400 with a message that says how to fix it and, for most causes, a stable code

such as credential_expired, credential_not_found, credential_source_type_mismatch, invalid_config,

credential_validation_failed, duplicate_source or no_tables_found.

A failed call does not use up a stored credential, so after fixing a cause that is not in the stored details you can retry with the same credential_id.

Stored values always win over inline values, so inline corrections to them have no effect.

Ask the user for a new connect link when the code is credential_expired or credential_not_found.

Do the same when the code is credential_validation_failed and the stored password, key or token has changed or is wrong.

Notes specific to this path:

counts for very large tables and offer the advanced flow if the user wants to sync only a subset.

setup response: on success, webhook-capable tables sync in real time and webhook-only tables (e.g. Stripe Discount)

are enabled too; on failure (e.g. the API key can't create webhooks), tables keep the polling defaults and

webhook-only tables stay disabled — relay the webhook.error to the user and offer Step 6 to register manually.

If webhook.pending_inputs is non-empty, collect those values and submit via

external-data-sources-update-webhook-inputs-create. CDC is never chosen automatically; use the advanced flow +

CDC steps for near-real-time Postgres.

Advanced: hand-pick tables (three-step flow)

Use this when the user wants to choose exactly which tables sync or set non-default sync types. Don't try to shortcut

to external-data-sources-create — you need the db-schema response to build a valid schemas payload.

         ┌────────────────────┐
         │ 1. wizard          │  What source types exist? What fields does each need?
         └────────┬───────────┘
                  ▼
         ┌────────────────────┐
         │ 2. db-schema       │  Validate creds. List tables + available sync methods per table.
         └────────┬───────────┘
                  ▼
         ┌────────────────────┐
         │ 3. create          │  Send source_type + credentials + schemas[] to actually create.
         └────────────────────┘

Workflow

Step 1 — Discover the source type

Call external-data-sources-wizard with source_type set to the kind(s) you need (comma-separated, e.g.

Postgres,Stripe). The unfiltered response describes every supported source and is hundreds of KB — large enough to

blow your context budget. Only omit source_type when you genuinely need to enumerate every available type, and when

you do, pass fields: ['*.name', '*.caption'] so the response carries just the names instead of every source's config

field definitions. The response is a dict keyed by source type. Each entry describes:

type (input, password, switch, select, file-upload), and required.

user explicitly asked for a preview.

Match the user's request to a source. If they said "Postgres", look up Postgres. If they said something ambiguous

like "database", present the top relevant matches (Postgres, MySQL, MongoDB, BigQuery, Snowflake, Redshift) and let

them pick.

For bucket files, use the canonical source_type: AmazonS3, GoogleCloudStorage, AzureBlob, or CloudflareR2.

For a local file, use the app's upload flow. It creates a FileUpload source after the user uploads the file.

For OAuth-based sources (Hubspot, Salesforce, Google Ads), the wizard entry hints at an OAuth flow. These typically

need the user to authorize in the PostHog UI rather than pasting credentials — explain this and direct them to the

source setup page rather than trying to collect tokens in chat. OAuth is about _authentication_, not about how data

flows; OAuth sources still use polling bulk sync, not webhooks.

Gather the required credentials from the user. Never ask for more fields than the wizard entry says are required —

asking for an unnecessary port when the source doesn't need one confuses users.

Step 2 — Validate credentials and discover tables

Call external-data-sources-db-schema with source_type plus all credential fields. This does two things at once:

  1. Validates the credentials against the live source. Returns 400 with a message if anything is wrong (bad host,

wrong password, permission denied). Show the error verbatim — it's often actionable ("password authentication

failed for user 'x'").

  1. If valid, returns an array of table entries. Each entry:
{
  "table": "orders",
  "should_sync": false,
  "rows": 1_250_000,
  "incremental_available": true,   # can do sync_type=incremental
  "append_available": true,        # can do sync_type=append
  "cdc_available": true,           # can do sync_type=cdc  (null = not enabled for team)
  "supports_webhooks": false,      # can do sync_type=webhook for real-time push
  "incremental_fields": [          # candidates: usually updated_at, created_at, id
    {"field": "updated_at", "type": "datetime", "label": "updated_at", ...},
    {"field": "created_at", "type": "datetime", ...},
    {"field": "id", "type": "integer", ...}
  ],
  "detected_primary_keys": ["id"],
  "available_columns": [{"field": "id", "type": "integer", "nullable": false}, ...],
  "description": "..."
}

Present this to the user. Don't dump the raw JSON — summarize: which tables were found, row counts, and the default

sync method recommendation per table (see sync-type decision guide).

Step 3 — Confirm per-table sync configuration

For each table the user wants to sync, pick a sync_type. See the

sync-type decision guide for detailed rules, but the short version is:

the tables where supports_webhooks: true, then register the webhook as a post-create step (see step 6 below).

Tables that don't support webhooks on the same source still need a bulk sync_type.

For each schema that will use incremental/append/cdc, you also need:

returned by db-schema. Prefer updated_at over created_at (updated_at catches late-arriving updates;

created_at misses them). For integer-only tables, use the monotonically increasing primary key.

numeric, objectid).

Step 4 — Pick a good prefix

The source's prefix is prepended to table names in HogQL. Tables end up as {prefix}_{table_name}.

Confirm the prefix with the user before creating — changing it later is possible but renames every table.

Step 5 — Create the source

Call external-data-sources-create with:

{
  "source_type": "Postgres",
  "prefix": "postgres_prod",
  "payload": {
    "host": "...",
    "port": "5432",
    "dbname": "...",
    "user": "...",
    "password": "...",
    "schema": "public",
    "schemas": [
      {
        "name": "orders",
        "should_sync": true,
        "sync_type": "incremental",
        "incremental_field": "updated_at",
        "incremental_field_type": "datetime",
        "primary_key_columns": ["id"]
      },
      {
        "name": "users",
        "should_sync": true,
        "sync_type": "full_refresh"
      },
      {
        "name": "audit_log",
        "should_sync": false
      }
    ]
  }
}

Rules for the schemas array:

Tables the user didn't mention default to should_sync: false.

On success you'll get back a source with a new id. The first sync is triggered automatically.

Step 6 — Register a webhook (only when any schema is `sync_type: "webhook"`)

Webhook-type schemas don't start receiving data just by existing — the external service needs to know where to POST

events, and PostHog needs to know how to verify them. This is a second call after source creation, not part of the

external-data-sources-create payload. Do this before telling the user the setup is complete, otherwise they

hear "syncs are running" while the push channel is still unregistered.

Only needed when at least one schema on the source has sync_type: "webhook" and should_sync: true. Currently only

Stripe implements this flow; for everything else skip this step.

Before calling create-webhook, check external-data-sources-webhook-info-retrieve({id}). If it already returns

exists: true, do NOT call create-webhook again — each successful call registers a new external endpoint and would

result in duplicate deliveries.

  1. Call external-data-sources-create-webhook-create({id}). PostHog:

Returns {success, webhook_url, error}. On success report the webhook_url to the user for their records — but

they don't need to paste it anywhere; registration is already done.

  1. If success: false with a permissions error like "API key doesn't have permission to create webhooks":

store it. The HogFunction picks it up and verifies incoming payloads.

  1. Verify with external-data-sources-webhook-info-retrieve({id}). A healthy webhook has exists: true,

external_status.status: "enabled", and no error.

Webhooks are supplementary to bulk sync. The first load of a webhook-enabled schema is still done via polling

(initial_sync_complete flips to true when done); after that, the webhook becomes the primary ingestion path. A

webhook schema will still have a sync_frequency that schedules a periodic bulk refresh as a safety net. This is

expected — not something to "fix".

Step 7 — Confirm and explain what happens next

After creation (and, for webhook schemas, after Step 6):

syncs can take anywhere from seconds to hours depending on row count — a multi-million-row table is fine, just

slow.

CDC setup for Postgres (optional, when requested)

If the user wants near-real-time replication from Postgres:

  1. Before calling db-schema, run external-data-sources-check-cdc-prerequisites-create with their Postgres creds.

It returns {valid, errors[]} listing anything missing (wal_level, replication slot, publication, permissions).

  1. If valid: false, present the errors and ask the user to fix on the Postgres side. Don't try to create a CDC

source that will immediately fail.

  1. Once prerequisites pass, proceed to db-schema and create. Set sync_type: "cdc" on the tables that need it, and

include primary_key_columns for each (CDC requires them).

To add CDC to a Postgres source that already exists, use external-data-sources-enable-cdc-create (it re-checks the

prerequisites), then set sync_type: "cdc" on the tables. external-data-sources-update-cdc-settings-create tunes the

lag thresholds. external-data-sources-disable-cdc-create turns CDC off and resets every CDC table, so ask first.

Sending a source to the user's own warehouse (optional, when requested)

Only do this when the user asks for their data in their own Snowflake, BigQuery, Postgres, Redshift, Databricks, S3,

Azure Blob storage or MotherDuck. These tools exist only when the feature is on for the project. MotherDuck also needs its

own feature flag, so creating one can fail with a 400 on type while that flag is off.

  1. Call external-data-destinations-list first. If a destination for that target already exists, reuse it, but only

when its status is healthy. A failing or paused one needs fixing first (see the end of this section).

  1. Call external-data-destinations-connect-link with the destination_type (for S3-compatible storage such as R2 or

MinIO, also pass integration_kind: "s3-compatible"). Share connect_url. The user must open it while logged in

to PostHog as the same user this session acts as. The page saves an integration.

  1. Call external-data-destinations-connect-link-status with the returned connect_token every few seconds until

status is connected or expired. When it is connected, confirm display_name with the user and use

integration_id. When it is expired, get a new link. If the user saved the connection as another PostHog user,

the page shows the integration id instead: ask the user for it.

  1. Ask the user for the target (database and schema, dataset, bucket and prefix, and so on), then call

external-data-destinations-create with type, name, integration and config. Creation tests the

connection for every type except Redshift, and a 400 names the field to fix. A wrong Redshift target only shows up

when the first sync fails. The target cannot change later, so confirm it before creating.

  1. Before you attach a source, check two things and tell the user what you find:

destination (is_posthog_warehouse in external-data-destinations-list), the source may write there by

default, and attaching would stop its PostHog tables updating. If the user wants to keep them, call

external-data-sources-destinations-update with that same list before step 6: it makes the warehouse an

explicit link. Skip that call while any destination in external-data-destinations-list is paused, because it

would delete a hidden link to that destination. Tell the user instead. When destination_ids is empty, tell

the user the PostHog tables stop updating.

external-data-schemas-destinations-retrieve for the source's tables. Those with inherits_from_source: false

will not reach the new destination.

  1. Call external-data-destinations-add-sources with the source ids. A source that has already synced sends only

new rows to the destination. Offer resync: true to copy the history, and say that a resync re-reads every row

(including overridden tables that do not reach the new destination) and bills every destination the source

writes to.

If a destination shows status: "failing" or "paused", run external-data-destinations-test-connection and relay

the message of the first failed step. Redshift has no test: relay latest_error from

external-data-destinations-retrieve instead. The test only reports. A paused destination stays paused until the user

fixes the problem and saves it on the warehouse destinations page.

Important notes

asynchronously — the source appears in the list with status Error and no tables. Skipping the validation step

just pushes the failure into the background.

— row counts and relevance matter for billing. Let the user opt in explicitly.

response. You can't "also add an orders table" unless db-schema found one.

configured destinations for writes here and nowhere else. Some projects can also send a source's tables to their

own database (external-data-sources-destinations-retrieve shows where a source writes, when the feature is on for

the project). Setting that up is a separate step (see "Sending a source to the user's own warehouse") and never something to do as part of creating a source — adding a

destination to a source that has already synced leaves it holding none of the history until the tables are resynced,

and a resync bills every destination the source writes to.

something short, descriptive, and not already taken.

authenticates in their browser — the connect page renders the source's full connection form (OAuth and credential

options alike) and stores the result without creating the source. Don't collect OAuth tokens or database passwords

in chat; pass the credential_id reference to setup — source creation always happens through setup, not the UI.

(An already-connected OAuth integration can also be passed directly via its id key, e.g.

{"hubspot_integration_id": 123}.)

webhook — the create-webhook call does. Always follow create → create-webhook → webhook-info for webhook-type

schemas, and never leave a webhook schema dangling without registration (it just won't receive events).

webhooks for Hubspot, Salesforce, or Postgres — they'll use polling sync.

hourly is very different from a 10k-row dimension table synced daily. Flag large tables and offer longer sync

frequencies (sync_frequency: "24hour") as the default.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.