AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

building-workflows

Build, edit, test, enable, and monitor PostHog workflows over MCP. Author the action/edge graph so it runs and opens cleanly in the visual editor, then change drafts surgically with patch operations. Use when asked to build, set up, automate, change, fix, or debug a workflow, campaign, broadcast, drip sequence, or event-triggered automation in the workflows product, including first-time messaging setup (email channel, sending domain, frequency cap) before the first workflow.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--building-workflows at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 4

references/graph-schema.md · 24000

dius preview.

  • internal-event (flag-gated) — { "type": "internal-event", "filters": { "source": "internal-events", "events": [{ "id": "<event>", "type": "events" }], "properties": [<cond>] } }. Fires once for each matching event on the internal-events stream; filters.events must name at least one allowed event id. Runs have no associated person, so person-dependent steps are unavailable. Test-run with an event named in filters.events and no person; any other event name is skipped at the trigger. The Slack trigger is this with $slack_message_received in filters.events: the run's event carries properties integration_id, channel, channel_type, slack_team_id, user, bot_id, app_id, subtype, text, ts, thread_ts, is_thread_reply, is_ext_shared_channel, and slack_event (the raw Slack payload). A workflow leaving draft must include one exact channel property filter whose value contains one or more channel IDs; several IDs match any listed channel. The GitHub trigger uses $github_event_received and requires exact repository and event_type filters.

Trigger masking (throttling an event trigger)

trigger_masking is a top-level workflow field (not an action) that throttles an already-matching event trigger — it dedups/samples firings, it does not decide who enters.

"trigger_masking": { "hash": "{person.id}", "ttl": 3600, "threshold": null }
  • hash — HogQL template defining the dedup key. "{person.id}" = once per person.
  • ttl — seconds to suppress repeats of the same hash (60–94608000).
  • threshold? — fire once per N matches of the same hash (a sampler: N=3 fires on the 1st, 4th, 7th…). Omit to fire once then suppress within ttl.
  • Don't send bytecode — compiled server-side from hash.

Condition shape (<cond>)

Property conditions used in trigger/action filters, branch conditions, and conversion:

{ "key": "plan", "value": ["pro"], "operator": "exact", "type": "person" }

type is event | person | group. Never include bytecode — the server compiles it.

Edges

{ "from": "source_id", "to": "target_id", "type": "continue", "index": 0 }
  • type: "continue" — fall-through: the sequential next step, or the no-match path out of a conditional_branch. For a wait_until_condition it is the max_wait_duration timeout path.
  • type: "branch" — requires index, matching config.conditions[index] on a conditional_branch. A wait_until_condition resolves (its condition matches or an events entry fires) out the branch edge at index: 0.
  • Every non-exit node needs a reachable next action via an outgoing edge, or execution fails with "No next action found".
  • A conditional_branch with N conditions typically has N branch edges (index: 0..N-1) plus one continue edge for the no-match path.
  • A wait_until_condition needs a branch edge at index: 0 (resolution) and a continue edge (timeout). Without the index: 0 branch it only ever advances on timeout, never on the event/condition firing.

function* inputs

Inputs are keyed by the template's input schema, each wrapped in {value: ...}:

"inputs": { "url": { "value": "https://example.com/hook" } }
  • Wrap values in {value: ...}. A flat string won't enable templating.
  • Templating uses single-curly {person.x} / {event.x} inside the value string. Liquid-style {{ ... }} is rejected on hog-templated fields ("Placeholders are not allowed in this context") — the only fields that accept Liquid are ones whose input schema declares templating: liquid (the email input on function_email does; most others don't).
  • Dictionary input values are template strings too — write booleans/numbers as single-expression templates: "{true}", "{42}", which evaluate to the typed value.
  • Required inputs must be present, or create fails with "This field is required".

Discovering function templates (do this, don't guess)

The set of available function templates and their required inputs is live data, not something to hardcode — it changes as integrations are added. For a function node:

  1. cdp-function-templates-list (filter type=destination) to find the right template and its id.
  2. cdp-function-templates-retrieve with that id to read its inputs_schema — the exact keys, types, and which are required.
  3. Build inputs from that schema. A template_id not in the live list fails with "Template not found".

function_email, function_sms, and function_push are the exception — their template_id is the fixed literal template-email / template-twilio / template-native-push, so you don't look the template_id up, and you can omit it entirely: the server infers the literal from the step type. A saved email template's UUID goes in template_uuid alongside the literal, never in template_id (a UUID sent as template_id is moved into template_uuid automatically). For function_email, referencing a template means you only author from/to: the server materializes the template's body at save (see the action-types table). function_push still has variable inputs (notably channels), so retrieve its inputs_schema even though the id is fixed.

function_push worked example

Retrieve template-native-push with cdp-function-templates-retrieve for the full inputs_schema (it has many optional Android/iOS keys), but the core shape is:

{
  "id": "push_1",
  "name": "Re-engagement push",
  "type": "function_push",
  "config": {
    "template_id": "template-native-push",
    "inputs": {
      "distinctId": { "value": "{event.distinct_id}" },
      "channels": { "value": [6, 7] },
      "title": { "value": "Notification from {event.event}" },
      "body": { "value": "Hi {{ person.properties.first_name }}, come finish setting up.", "templating": "liquid" }
    }
  }
}
  • channels is an integration_multi input: its value is an array of integration id numbers (e.g. [6, 7]), not objects. Find the FCM/APNs integration ids with integrations-list (look for kind firebase / apns); at least one is required or the send throws "No push channel configured".
  • Templating differs per input. body is liquid — interpolate with {{ person.x }} / {{ event.x }} (double braces) and set "templating": "liquid". title and the other string inputs are hog — use {event.x} / {person.x} (single braces). The wrong brace style leaves the expression as a literal.
  • Required: distinctId, channels, title. Optional: body, image, data, ttlSeconds, android_*, ios_* (retrieve the inputs_schema for the full set).
  • Never hand-author bytecode — the server compiles it from value. Omit order too: the editor lays fields out in the template's inputs_schema order (fixed and consistent), not by the order on your inputs, so leaving it off doesn't change the form. Push has no delivered/opened/clicked signal (FCM/APNs respond synchronously), so a successful send means "accepted for delivery", nothing more.

Replay Vision step

Replay Vision is PostHog's AI that watches session recordings. It replays a session as video, together with its events, and answers a question about it. Each scan uses credits from the project's Replay Vision quota.

A function node with template_id: "template-posthog-replay-vision" scans the trigger event's session and waits for the answer. Use it when the next step depends on what happened in the session, which event properties alone can't tell, for example to add session context to a Slack alert or to branch on whether the user struggled. The project must record sessions, and the trigger event must carry a $session_id.

{
  "id": "vision_1",
  "name": "Did checkout fail?",
  "type": "function",
  "config": {
    "template_id": "template-posthog-replay-vision",
    "inputs": {
      "analysis": { "value": { "type": "monitor", "prompt": "Did the user hit an error during checkout?" } }
    }
  },
  "output_variable": { "key": "replay_vision" }
}
  • analysis is a literal object, not a template. Never set "templating" on it, and never put {...} expressions in it. Its value takes one of these shapes:

    | type | Required keys | What the step answers | | ------------ | ----------------------------------------------- | --------------------------------------------------------- | | monitor | prompt | A yes/no verdict on the question in prompt. | | classifier | prompt, tags (1 to 100 category strings) | Which of the categories in tags fit the session. | | scorer | prompt, scale: {"min": <num>, "max": <num>} | A score on the scale. max must be greater than min. | | summarizer | prompt | A title, a summary, and chapters. | | scanner | scanner_id (a saved scanner's UUID) | The saved scanner's answer, with its own type and prompt. |

  • The inline types take the same optional settings as a saved scanner of that type. See the creating-replay-vision-scanners skill. Find saved scanners with the vision-scanners tools. The step refuses an experiment scanner, because it samples the experiment's variants evenly, which one triggered session can't do.

  • session_id defaults to {event.properties.$session_id}. Leave it unset unless the session ID is in another property.

  • wait_for_session_end defaults to true, which scans the recording after the session has been quiet for 35 minutes. Set it to false only when the trigger event comes after the session ended.

  • The step result is {"state", "output", "warnings"}. state is succeeded, failed, skipped, ineligible or lost. output is the scanner's answer: verdict, tags or score with reasoning for a monitor, classifier or scorer, and title, summary and chapters for a summarizer. Every type also returns confidence. Use output_variable to keep the result, then branch on it. When output is null, warnings says why: used-up credits, a session too short or too long to scan, or a failed scan.

  • Main environment only. The server refuses the step in a child environment of a project.

  • Daily caps. Each workflow can start 100 scans a day, and the project 500, unless the project settings change replay_vision_scan_rate_limit_per_day and replay_vision_scan_team_rate_limit_per_day. Past a cap the step returns state: "skipped" and the workflow continues.

  • Access. The token needs session_recording:read (or :write) and replay_scanner:write, and the user needs access to recordings and to the saved scanner. Without them, the save fails with a message that names what is missing.

Opt out of messages step

A function node with template_id: "template-posthog-opt-out-of-messages" adds the run's recipient to the opt-out list for one message category, or for all marketing messages. Later email, SMS and push steps for that category skip the recipient. Use it whenever a workflow has to opt someone out. Don't build this with a webhook step that calls messaging_preferences/add_opt_out/ with an API key: that call breaks when the key's owner leaves or the key rotates, and its failures only show as webhook errors.

{
  "id": "opt_out_1",
  "name": "Opt out of product updates",
  "type": "function",
  "on_error": "abort",
  "config": {
    "template_id": "template-posthog-opt-out-of-messages",
    "inputs": {
      "category_id": { "value": "<message category id>" },
      "identifier": { "value": "{person.properties.email}" }
    }
  }
}
  • category_id is a literal, not a template. Use a marketing message category's id (UUID), listed by message-categories-list, or "$all" for all marketing messages. If the category doesn't exist yet and the user's request covers creating it, for example an import that brings its own categories, create it with message-categories-create. Otherwise ask the user for it rather than guess. Never put {...} expressions in it. A save with a category the project doesn't have fails.
  • identifier is who to opt out. It defaults to {person.properties.email}. Use the same value as the recipient of the email step it should suppress, because opt-outs match the recipient exactly.
  • Only marketing categories work, because transactional messages ignore opt-outs. A save with a transactional category fails.
  • The step fails, and the workflow log says why, when identifier is empty or the category was deleted. It never passes silently.
  • Set "on_error": "abort" on the node. Without it, a failed opt-out continues to the next step, which may send the message the person asked to stop.
  • Running it again for someone who is already opted out succeeds and logs "Already opted out".
  • The step is behind the workflow-opt-out-of-messages-action feature flag. Without the flag, the save fails with "Template not found".

Duration strings (delay_duration, max_wait_duration)

Must match ^\d*\.?\d+[dhms]$ — a number plus unit s | m | h | d. Examples: 30s, 30m, 2h, 1d, 1.5d (=36h).

  • No ISO-8601. Fractions are allowed in every unit.
  • Per-unit caps: s≤60, m≤60, h≤24, and d≤365 for delay_duration and max_delay_duration but d≤30 for a wait's max_wait_duration. A save over a cap is rejected, so use the larger unit (90m → 1.5h). Workflows saved before the check may still store an over-cap value, which runs at the cap.

Waiting until a date (delay_until)

A delay waits either a fixed span or until a date carried by the person or the event. Use delay_until when the date differs per person, which a duration cannot express (a trial expiry, a renewal date, a booked appointment).

{
  "id": "delay_1",
  "type": "delay",
  "config": {
    "delay_until": { "expression": "person.properties.trial_expiration_at", "offset": "-1d" },
    "max_delay_duration": "30d"
  }
}
  • Exactly one of delay_duration and delay_until. Both together are rejected; so is neither.
  • expression is HogQL resolving to a datetime. An ISO string, a HogDateTime, and unix seconds all resolve to the same instant, so a stored date works whichever shape the customer set it in. A bare number is read as seconds: a millisecond timestamp (what Date.now() and most SDKs produce) is rejected rather than read as a date tens of thousands of years out. Divide it by 1000 in the expression, or store the date as an ISO string.
  • offset shifts that instant and is signed: ^-?\d*\.?\d+[dhms]$. -1d is a day before the date, 2h is two hours after. Omit it to wait for the date itself. Keep the arithmetic here rather than in the expression, so the builder can still read the step back as a property plus an offset.
  • Unlike delay_duration, an offset is not clamped per unit: -48h means 48 hours, not 24. max_delay_duration bounds the wait instead.
  • timezone, use_person_timezone and fallback_timezone work as they do on wait_until_time_window, and decide which zone a date with no offset of its own is read in (a bare 2026-03-01, or 2026-03-01T09:00:00). A date that states an offset, a HogDateTime, and unix seconds are absolute and ignore them. Default UTC, so a date-only value means midnight UTC unless you set a zone.
  • max_delay_duration caps how far past the step's start the wait may run (default 30d, same duration rules as above). It exists so a far-future date cannot park a run indefinitely.
  • Never send bytecode. The server compiles the expression at save time and discards anything the client sent. A broken expression fails the save with the parse error.
  • The expression is re-read on every wake, not only on entry, and the only wake a parked delay schedules is the instant it computed. So a date that moves further out is honored: the run wakes at the old instant and parks again to the new one. A date that moves closer is not: nothing wakes the run early, so it waits for the original instant and then continues at once, later than the new date asked for.
  • A date that cannot be resolved aborts the run whatever on_error says, because a wait that cannot work out when to act has nothing safe to fall through to.
  • A person property is person.properties.<key>; an event property is properties.<key>, with no event. prefix. The expression runs against the same globals as a filter, where event is the event's name, so event.properties.<key> resolves to nothing and aborts the run.
  • The builder writes those two shapes (bracketed when the key is not a bare identifier). Any other expression saves fine but shows in the editor as a read-only custom expression instead of a property pick.

Conversion & exit condition

  • exit_condition: exit_only_at_end (default), exit_on_conversion, exit_on_trigger_not_matched, exit_on_trigger_not_matched_or_conversion.
  • The …conversion variants require a conversion goal with two slots plus a window:
    • filters — property conditions only, an array [{key, value, operator, type}, ...] (empty array = any event in the window converts).
    • events — event-based goals, [{ "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events" }] } }].
    • window — how long after entry a conversion still counts, as a duration string ("7d", "12h", "30m", "45s"), max "365d". Omit it (or null) for the default 90-day window.
    • There is no minutes form. The server drops a window_minutes key without an error, so a window sent that way silently becomes the 90-day default.
  • An event goal goes in events, never in filters. An event object stuffed into filters is invisible to the conversion matcher and breaks the conversion picker. Without a goal the …conversion exit is a silent no-op. Server compiles the bytecode.

Pre-submit checklist

  • [ ] Exactly one type: "trigger" action; usually exactly one exit.
  • [ ] Every action type and config matches a row above (no types outside the supported set).
  • [ ] on_error is only continue or abort.
  • [ ] function_email.template_id == "template-email", function_sms.template_id == "template-twilio", function_push.template_id == "template-native-push".
  • [ ] A webhook / manual trigger sets template_id == "template-source-webhook" (a tracking_pixel uses "template-source-webhook-pixel") — these are built-in source templates, not catalog lookups.
  • [ ] That trigger's inputs.event / inputs.distinct_id match its own type: {request.body.*} for webhook, $workflow_triggered + {request.body.user_id} for manual, {request.query.ph_*} for tracking_pixel. The wrong pair saves fine and then fails at trigger time.
  • [ ] Every non-exit node has an outgoing edge; branch edges have an index matching a condition.
  • [ ] Every conditional_branch / wait_until_condition condition is wrapped: {filters: {properties: [...]}}, not {properties: [...]}.
  • [ ] All durations match ^\d*\.?\d+[dhms]$ and stay within the per-unit caps.
  • [ ] Every delay sets exactly one of delay_duration and delay_until, and no delay_until carries hand-written bytecode.
  • [ ] Function inputs are {key: {value: ...}}; no hand-written bytecode anywhere; no top-level trigger field set.
  • [ ] A Replay Vision step's analysis value is a literal object of one of the five shapes, with no templating.