:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(workflows): building-workflows skill, steer agents to patch + test (#63545)
Harley Alexandere13ddb0edd21
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex 74c8a6ed3dee..d4d40fbeb5bf 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -93,19 +93,20 @@ tools:enrich_url: '{id}/workflow'title: Create workflowdescription: >- Create a workflow. Needs an actions array with exactly one type='trigger' (config.type:- event|webhook|manual|batch|tracking_pixel) plus action nodes — function/function_email/function_sms, delay- (e.g. '30m'), conditional_branch, wait_until_condition — connected by edges. Created as a draft; activate- with workflows-enable. 'batch' = broadcast to an audience, one run per matching person (emails/messages).- The audience is config.filters.properties: person-property conditions ({type:'person',key,value,operator})- and/or cohort references ({type:'cohort',key:'id',value:<id>,operator:'in'}). Prefer inline person-property- conditions or a dynamic (filter-based) cohort via cohorts-create — these re-evaluate as people qualify; a- static cohort is a frozen list, use only when given an explicit set. An event trigger fires on every- occurrence matching the event and the trigger's filters; throttle repeat firings with trigger_masking- (dedup/sampling — not behavioral filtering). Behavioral cohorts/targeting ('did event X at least N times- over the last M days') are unsupported — if the user requests one, reject it and explain why. A batch- workflow doesn't fire on enable alone: dispatch it with workflows-run-batch (one-off) or attach a recurring- schedule with workflows-schedule-create.+ Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run+ first, then enable (workflows-enable) only with the user's explicit approval — enabling is a one-way door,+ since live workflows can't be edited over MCP. Provide an actions array with exactly one type='trigger'+ (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes+ (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by+ edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the+ per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch+ condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition;+ omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never+ hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts+ to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per+ matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with+ workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is+ unsupported; reject it and explain why.ui_app: workflowworkflows-get:operation: hog_flows_retrieve@@ -236,7 +237,9 @@ tools:nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the resultfully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwisenothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned,- so you don't need to re-fetch before the next edit.+ so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each+ condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition.+ Re-test the changed path with workflows-test-run after patching.workflows-stats:operation: hog_flows_metrics_retrieveenabled: true@@ -264,9 +267,13 @@ tools:idempotent: falsetitle: Test-run workflowdescription: >- Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async- actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects.- Optional current_action_id starts from a specific node. Returns the execution trace.+ Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result+ includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit+ current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat.+ To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action+ after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}).+ Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side+ effects. Returns the step's execution trace.exclude_params:- configurationworkflows-update:@@ -281,14 +288,12 @@ tools:enrich_url: '{id}/workflow'title: Update workflowdescription: >- Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking- already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable- / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or- cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a- static frozen-list cohort. An event trigger fires on every occurrence matching the event and the trigger's- filters; throttle repeat firings with trigger_masking (dedup/sampling — not behavioral filtering).- Behavioral cohorts/targeting ('did event X at least N times over the last M days') are unsupported — if the- user requests one, reject it and explain why.+ Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurally+ validated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patch+ can't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when+ you can't get workflows-patch-graph to land a change. Draft only: active workflows are read-only via MCP+ (editing risks breaking already-scheduled runs), so create a new draft to change a live one. Status changes+ go through workflows-enable / workflows-archive.exclude_params:- statusui_app: workflowdiff --git a/products/workflows/skills/building-workflows/SKILL.md b/products/workflows/skills/building-workflows/SKILL.mdnew file mode 100644index 000000000000..8a489068f21e--- /dev/null+++ b/products/workflows/skills/building-workflows/SKILL.md@@ -0,0 +1,114 @@+---+name: building-workflows+description: '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.'+---++# Building workflows++A PostHog **workflow** is a directed graph: a list of **action nodes** (`actions`) wired by **edges** (`edges`), with exactly one `trigger` node that starts every run. You author that graph as JSON and ship it over MCP. Always call it a "workflow" to the user. "Hog flow" is the internal code name (`HogFlow`), not a user-facing term.++The single biggest failure mode is **getting the graph JSON structurally wrong**. The backend stores `actions`/`config` as loose JSON, but the visual editor parses every node against a strict schema, so a malformed node saves but then **breaks the editor view** for the whole workflow. Before composing or editing any graph, read [references/graph-schema.md](references/graph-schema.md). It is the contract; do not improvise node shapes from these examples alone.++## The lifecycle++Work the workflow through these stages. Don't jump straight to enabling it.++1. **Compose the graph.** Build `actions` + `edges` per [references/graph-schema.md](references/graph-schema.md). For any `function` node, don't guess the template: list the live catalog with `cdp-function-templates-list` and read its required inputs with `cdp-function-templates-retrieve`.+2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.+3. **Test-run it.** `workflows-test-run` runs **one step at a time**. Start at the first step (omit `current_action_id`, or point it at the trigger) with sample `globals` (`{event, person, groups}`); the result includes the next step's id (`nextActionId`). Feed that back as `current_action_id` and run again, walking step by step to the end. Skip `delay` nodes by jumping to the action after them (delays aren't simulated). Async side effects (HTTP/email/SMS) are mocked unless you set `mock_async_functions=false`. Read each step's trace to confirm the path taken.+4. **Read logs while iterating.** `workflows-logs` shows the per-step execution trace (levels DEBUG to ERROR). This is how you see _why_ a step skipped, branched, or errored.+5. **Edit the draft, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. Drafts only; active workflows are read-only over MCP.+6. **Enable (one-way door, needs the user's explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. You can't edit a live workflow over MCP (to change it you recreate it as a new draft), so treat enabling as effectively irreversible: finish testing, then get the user's explicit go before enabling. Don't enable on your own initiative.+7. **Dispatch (batch/schedule only).** A `batch` workflow does **not** fire on enable alone. Send a one-off broadcast with `workflows-run-batch`, or attach a recurring schedule with `workflows-schedule-create`. Confirm with `workflows-get` that `status=='active'` _and_ its read-only `schedules` field has an active entry.+8. **Monitor.** Drill down: `workflows-global-stats` (which workflows are failing) to `workflows-stats` (one workflow's trend) to `workflows-list-invocations` (who it failed for) to `workflows-get-invocation` (the triggering payload) to `workflows-logs` (the failing step).++Full tool catalog, grouped by job: [references/lifecycle-and-debugging.md](references/lifecycle-and-debugging.md).++## Editing a draft++**Patch, don't replace.** Edit a draft with `workflows-patch-graph`: a small, ordered list of id-addressed operations (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`). `update_action` deep-merges its patch, so changing one email subject is a few lines, not the whole graph. The ops apply atomically server-side (read, apply in order, validate, save only if valid), and the response echoes the **full updated graph**, so you never re-fetch before the next edit. This keeps each round-trip tiny instead of re-transmitting every action and edge.++`workflows-update` is the fallback, for two cases: top-level metadata a graph patch can't express (for example renaming the workflow), or as an escape hatch when you genuinely can't get `workflows-patch-graph` to land a change (send the whole corrected workflow rather than keep fighting the op list). For everything else, patch.++After **any** patch, re-test the path you changed (step 3). A patch that validates structurally can still route the wrong way.++Email templates follow the same rule: edit a template's design with **`workflows-patch-email-template`** (surgical, id-addressed ops over the Unlayer blocks), not `workflows-update-email-template`, which resends the entire design JSON. Compose and edit templates with the **`designing-email-templates`** skill.++## Changing a live workflow++Active workflows cannot be edited over MCP. **To change a live workflow, create a new draft** (`workflows-create`) with the updated graph, test it, and enable it. If the user wants to edit a live workflow in place, tell them that isn't supported yet and offer the new-draft path.++## What the server owns, never send it++The server compiles and manages these. Authoring them by hand is the fastest way to a broken workflow:++- **`bytecode`** on any filter, trigger, condition, conversion, or masking. Compiled server-side from the human-readable `properties`/`hash`. Omit it; send `filters: {...}`, not bytecode.+- **`trigger`** (top-level). _Derived_ from the `trigger` action in `actions`. Read-only. Set the trigger by adding the trigger node, not by setting this field.+- **`billable_action_types`**, `version`, `id`, `created_*`. Computed/managed.++## Minimal worked example++Event trigger, wait 1 day, send email, exit. Note: exactly one `trigger`, every non-exit node has an outgoing edge, ids are referenced consistently by `edges`, and no `bytecode` is sent.++```json+{+ "name": "Nudge after signup",+ "description": "One day after signup, send a reminder.",+ "exit_condition": "exit_only_at_end",+ "actions": [+ {+ "id": "trigger_node",+ "name": "Signed up",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": { "events": [{ "id": "user signed up", "name": "user signed up", "type": "events", "order": 0 }] }+ }+ },+ {+ "id": "delay_1",+ "name": "Wait 1 day",+ "type": "delay",+ "config": { "delay_duration": "1d" }+ },+ {+ "id": "email_1",+ "name": "Reminder email",+ "type": "function_email",+ "config": {+ "template_id": "template-email",+ "message_category_type": "marketing",+ "inputs": {+ "email": {+ "value": {+ "to": { "email": "{person.properties.email}", "name": "" },+ "from": { "email": "[email protected]", "name": "Example" },+ "subject": "Don't forget to finish setting up",+ "html": "<p>Hi {person.properties.first_name}, …</p>"+ }+ }+ }+ }+ },+ {+ "id": "exit_node",+ "name": "Exit",+ "type": "exit",+ "config": { "reason": "Done" }+ }+ ],+ "edges": [+ { "from": "trigger_node", "to": "delay_1", "type": "continue" },+ { "from": "delay_1", "to": "email_1", "type": "continue" },+ { "from": "email_1", "to": "exit_node", "type": "continue" }+ ]+}+```++For anything beyond a placeholder email body, author the design with the **`designing-email-templates`** skill and reference the template. Don't hand-write production email HTML here.++## Hard rules to surface to the user, not work around++- **Behavioral targeting is unsupported.** "Did event X at least N times over the last M days" can't be expressed as a trigger or a batch/schedule audience. If asked, reject it and explain; don't approximate it with a broken filter. (The backend rejects behavioral cohorts in batch audiences outright.)+- **Batch audiences target _who a person is_, not what they did.** Person properties and/or static/property-based cohorts only. Event/action filters in a batch audience are silently dropped, so they're rejected.+- **Prefer re-evaluating audiences.** For batch, inline person-property conditions or a dynamic (filter-based) cohort re-evaluate as people qualify; a static cohort is a frozen list, use only for an explicit given set.diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdnew file mode 100644index 000000000000..112516d13dfe--- /dev/null+++ b/products/workflows/skills/building-workflows/references/graph-schema.md@@ -0,0 +1,144 @@+# Workflow graph schema++The contract for `actions` and `edges`. The stored workflow is loose JSON, but **the visual editor validates every node against a strict schema keyed on `type`**. A node that saves successfully but doesn't match this contract will **break the editor view for the whole workflow** when someone opens it. Treat the shapes below as required, not advisory.++## Node (action) shape++Every action object has these common fields plus a type-specific `config`:++```json+{+ "id": "unique_within_workflow",+ "name": "Human label",+ "description": "",+ "type": "<see action types>",+ "config": {},+ "on_error": "continue",+ "filters": null,+ "output_variable": null+}+```++- `id` — unique within the workflow; edges reference it by `from`/`to`.+- `on_error` — optional; **only `continue` or `abort`.** Omit to use the default.+- `filters` — optional property filters gating the action: `{properties: [<cond>]}`. Send `properties`, not `bytecode`.+- `output_variable` — optional; store a step result into a workflow variable. `{key, result_path?, spread?}`.++## Action types and their `config`++Use **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor's parse for the entire graph.++| `type` | `config` |+| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |+| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |+| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |+| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages should sum to 100 — a shortfall leaves an unrouted remainder, an excess makes later cohorts unreachable. |+| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |+| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |+| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don't guess the id or its inputs — discover them live (see below). |+| `function_email` | `{ "template_id": "template-email", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-email`. |+| `function_sms` | `{ "template_id": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`. |+| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |++### Branch and wait condition filters (the `filters` wrapper is mandatory)++`conditional_branch` and `wait_until_condition` gate on a **`filters` object**, the action-filter shape (`{properties?, events?, actions?, source?, filter_test_accounts?}`). The wrapper is not optional:++- Write `{ "filters": { "properties": [<cond>] } }` on each condition, **never** `{ "properties": [<cond>] }` directly on the condition object. The bare form saves but the visual editor flags it and the branch compiles to a constant, so it never evaluates your condition.+- `conditional_branch` conditions are **property-only** (person/group `<cond>`s). Event/action filters are rejected here ("Event filters are not allowed in conditionals").+- `wait_until_condition` is event-aware: its `condition.filters` and each `events?[].filters` may also carry `events`/`actions`. An entry naming neither an event nor an action is dropped (it would match everything).+- `source` is optional (defaults to `events`). Never send `bytecode`; the server compiles it from `properties`.++### Trigger `config` (the `trigger` node)++Discriminated on `config.type`:++- `event` — `{ "type": "event", "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events", "order": 0, "properties": [<cond>] }], "properties": [<cond>], "filter_test_accounts": false } }`. Fires on **every** matching occurrence. Throttle repeats with `trigger_masking` (dedup/sampling — not behavioral filtering).+- `webhook` / `manual` / `tracking_pixel` — `{ "type": "webhook", "template_id": "<id>", "inputs": { ... } }`. Function-style triggers; discover the `template_id` and its inputs the same way as `function` nodes (see "Discovering function templates").+- `batch` — `{ "type": "batch", "filters": { "properties": [<cond>] } }`. The audience: person-property conditions and/or cohort references. **No event/action filters** (silently dropped, so rejected). Does not fire on enable — dispatch a one-off broadcast with `workflows-run-batch`, or make it **recurring** with `workflows-schedule-create` (attaches an RRULE schedule; each firing re-broadcasts to this same `config.filters.properties` audience). A recurring workflow is a `batch` trigger plus a schedule — there is no separate "schedule" trigger type to author.++### 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.++```json+"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:++```json+{ "key": "plan", "value": ["pro"], "operator": "exact", "type": "person" }+```++`type` is `event` | `person` | `group`. Never include `bytecode` — the server compiles it.++## Edges++```json+{ "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: ...}`:++```json+"inputs": { "url": { "value": "https://example.com/hook" } }+```++- **Wrap values in `{value: ...}`.** A flat string won't enable templating.+- Templating uses `{person.x}` / `{event.x}` inside the value string.+- **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` and `function_sms` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` (required by the editor), so you don't look those up.++## Duration strings (`delay_duration`, `max_wait_duration`)++Must match `^\d*\.?\d+[dhm]$` — a number plus unit `m` | `h` | `d`. Examples: `30m`, `2h`, `1d`, `0.5m` (=30s).++- **No seconds, no ISO-8601.** For sub-minute, use a fraction of a minute.+- Per-unit caps are **silently clamped**: `m`≤60, `h`≤24, `d`≤30. Max total 30d. Use the larger unit (`90m` → use `1.5h`) to avoid surprise clamping.++## 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_minutes` — minutes after entry (`null` = no window).+- **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"`.+- [ ] 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+[dhm]$` and dodge the silent per-unit clamp.+- [ ] Function inputs are `{key: {value: ...}}`; no hand-written `bytecode` anywhere; no top-level `trigger` field set.diff --git a/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.mdnew file mode 100644index 000000000000..3c0878fa395e--- /dev/null+++ b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md@@ -0,0 +1,47 @@+# Workflow tool reference++The MCP tools for the workflows product, grouped by job. The lifecycle that strings them together (build → test → edit → enable → monitor) lives in [SKILL.md](../SKILL.md); this is the catalog of which tool does what.++## Tool inventory++**Author & lifecycle**++- `workflows-create` — create a workflow. Always created as a `draft`.+- `workflows-patch-graph` — **the way to edit a draft's graph.** An ordered, id-addressed op list (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`) applied atomically; `update_action` deep-merges (a `null` leaf deletes a key). Returns the full updated graph, so no re-fetch. **Drafts only.**+- `workflows-update` — **fallback editor.** Top-level metadata a graph patch can't express (renaming), or an escape hatch to replace the whole workflow when `workflows-patch-graph` won't land a change. **Drafts only**; active workflows are read-only over MCP, so to change a live one create a new draft.+- `workflows-enable` — draft → `active`. **One-way door:** you can't edit a live workflow (only recreate it as a draft), so test first and get the user's explicit approval before enabling.+- `workflows-archive` — retire a workflow.+- `workflows-get` — full definition: trigger, edges, actions, exit condition, variables, and read-only `schedules` (any recurring schedules attached to the workflow; there's no separate list-schedules tool).+- `workflows-list` — all workflows with name, status, version, trigger, timestamps.++**Test & inspect**++- `workflows-test-run` — runs **one step at a time**, it does not traverse the whole graph in one call. Omit `current_action_id` (or set it to the trigger) to run the first step; the result gives you `nextActionId`, which you pass as `current_action_id` on the next call. Walk the workflow step by step this way; to test a specific branch, set `current_action_id` to that node. Skip `delay` nodes by jumping to the action after them (delays aren't simulated). Pass test data via `globals` (`{event, person, groups}`). Async actions (HTTP/email/SMS) mocked by default; `mock_async_functions=false` fires real side effects. Returns the step's execution trace.+- `workflows-logs` — execution log entries (timestamp, level DEBUG/LOG/INFO/WARN/ERROR, message). Filter by level, text, time range, limit.++**Batch & schedules**++- `workflows-run-batch` — one-off broadcast to the batch audience (one run per matching person).+- `workflows-schedule-create` — attach a recurring schedule (RRULE) to a batch/schedule workflow.+- `workflows-update-schedule` — change a schedule's RRULE, start time, timezone, or variable overrides.+- `workflows-list-batch-jobs` — past batch runs (one-off + schedule-triggered), with the audience filters and variable overrides each used. No per-run status here — use logs/stats for outcomes.+- `workflows-blast-radius` — preview how many people a set of audience filters matches before dispatching.++**Monitor & debug**++- `workflows-global-stats` — at-a-glance health across ALL workflows: per-workflow succeeded/failed over a window, most-failing first.+- `workflows-stats` — one workflow's success/failure time-series (hour/day/week), with breakdown by kind/name.+- `workflows-list-invocations` — per-recipient outcomes (one per person/event): status, error_kind/error_message, distinct_id, person_id, timings. Filter `status=failed`.+- `workflows-get-invocation` — a single invocation incl. `invocation_globals` (the raw triggering payload that ran). The broad→narrow drill-down (global-stats → stats → invocations → get-invocation → logs) is in [SKILL.md](../SKILL.md).++**Discover function templates** (for `function` nodes and webhook/manual/tracking_pixel triggers)++- `cdp-function-templates-list` — the live catalog of function templates (filter `type=destination`). Source of truth for which integrations exist; don't hardcode template ids.+- `cdp-function-templates-retrieve` — one template's full detail including its `inputs_schema`. Read this before building a `function` node's `inputs`.++**Email templates** (compose and edit with the `designing-email-templates` skill)++- `workflows-create-email-template` — create a new template.+- `workflows-patch-email-template` — **the way to edit an existing template's design.** Id-addressed ops over the Unlayer blocks, applied atomically; same shape as `workflows-patch-graph`. Use for any change to an existing design.+- `workflows-update-email-template` — full-replace, last resort (see `workflows-update` vs `workflows-patch-graph`).+- `workflows-list-email-templates`, `workflows-get-email-template` / `workflows-show-email-template` — list and read.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex affb471d6017..6e62f6e3a755 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7580,7 +7580,7 @@}},"workflows-create": {- "description": "Create a workflow. Needs an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes — function/function_email/function_sms, delay (e.g. '30m'), conditional_branch, wait_until_condition — connected by edges. Created as a draft; activate with workflows-enable. 'batch' = broadcast to an audience, one run per matching person (emails/messages). The audience is config.filters.properties: person-property conditions ({type:'person',key,value,operator}) and/or cohort references ({type:'cohort',key:'id',value:<id>,operator:'in'}). Prefer inline person-property conditions or a dynamic (filter-based) cohort via cohorts-create — these re-evaluate as people qualify; a static cohort is a frozen list, use only when given an explicit set. An event trigger fires on every occurrence matching the event and the trigger's filters; throttle repeat firings with trigger_masking (dedup/sampling — not behavioral filtering). Behavioral cohorts/targeting ('did event X at least N times over the last M days') are unsupported — if the user requests one, reject it and explain why. A batch workflow doesn't fire on enable alone: dispatch it with workflows-run-batch (one-off) or attach a recurring schedule with workflows-schedule-create.",+ "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — enabling is a one-way door, since live workflows can't be edited over MCP. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.","category": "Workflows","feature": "workflows","summary": "Create workflow",@@ -7748,7 +7748,7 @@}},"workflows-patch-graph": {- "description": "Surgically edit a draft workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any change to an existing draft — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned, so you don't need to re-fetch before the next edit.",+ "description": "Surgically edit a draft workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any change to an existing draft — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.","category": "Workflows","feature": "workflows","summary": "Patch workflow graph",@@ -7790,7 +7790,7 @@}},"workflows-test-run": {- "description": "Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Optional current_action_id starts from a specific node. Returns the execution trace.",+ "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Returns the step's execution trace.","category": "Workflows","feature": "workflows","summary": "Test-run workflow",@@ -7804,7 +7804,7 @@}},"workflows-update": {- "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort. An event trigger fires on every occurrence matching the event and the trigger's filters; throttle repeat firings with trigger_masking (dedup/sampling — not behavioral filtering). Behavioral cohorts/targeting ('did event X at least N times over the last M days') are unsupported — if the user requests one, reject it and explain why.",+ "description": "Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurally validated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patch can't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when you can't get workflows-patch-graph to land a change. Draft only: active workflows are read-only via MCP (editing risks breaking already-scheduled runs), so create a new draft to change a live one. Status changes go through workflows-enable / workflows-archive.","category": "Workflows","feature": "workflows","summary": "Update workflow",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex bb935cce691a..9aa810c5b7bd 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8117,7 +8117,7 @@}},"workflows-create": {- "description": "Create a workflow. Needs an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes — function/function_email/function_sms, delay (e.g. '30m'), conditional_branch, wait_until_condition — connected by edges. Created as a draft; activate with workflows-enable. 'batch' = broadcast to an audience, one run per matching person (emails/messages). The audience is config.filters.properties: person-property conditions ({type:'person',key,value,operator}) and/or cohort references ({type:'cohort',key:'id',value:<id>,operator:'in'}). Prefer inline person-property conditions or a dynamic (filter-based) cohort via cohorts-create — these re-evaluate as people qualify; a static cohort is a frozen list, use only when given an explicit set. An event trigger fires on every occurrence matching the event and the trigger's filters; throttle repeat firings with trigger_masking (dedup/sampling — not behavioral filtering). Behavioral cohorts/targeting ('did event X at least N times over the last M days') are unsupported — if the user requests one, reject it and explain why. A batch workflow doesn't fire on enable alone: dispatch it with workflows-run-batch (one-off) or attach a recurring schedule with workflows-schedule-create.",+ "description": "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — enabling is a one-way door, since live workflows can't be edited over MCP. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms, delay, conditional_branch, wait_until_condition, ...) connected by edges. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.","category": "Workflows","feature": "workflows","summary": "Create workflow",@@ -8145,7 +8145,7 @@}},"workflows-enable": {- "description": "Enable / activate a draft workflow and start processing events. Confirm with the user before invoking.",+ "description": "Enable / activate a draft workflow and start processing events. One-way door: a live workflow can't be edited over MCP (to change it you recreate it as a new draft), so test it first and get the user's explicit approval before invoking. Don't enable on your own initiative.","category": "Workflows","feature": "workflows","summary": "Enable workflow",@@ -8299,7 +8299,7 @@}},"workflows-patch-graph": {- "description": "Surgically edit a draft workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any change to an existing draft — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned, so you don't need to re-fetch before the next edit.",+ "description": "Surgically edit a draft workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any change to an existing draft — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. Draft only — active workflows are read-only via MCP. The full updated workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.","category": "Workflows","feature": "workflows","summary": "Patch workflow graph",@@ -8369,7 +8369,7 @@}},"workflows-test-run": {- "description": "Test-invoke a saved workflow. Pass test event data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Optional current_action_id starts from a specific node. Returns the execution trace.",+ "description": "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS) are mocked by default; set mock_async_functions=false to fire real side effects. Returns the step's execution trace.","category": "Workflows","feature": "workflows","summary": "Test-run workflow",@@ -8383,7 +8383,7 @@}},"workflows-update": {- "description": "Update a workflow by ID. Draft only — active workflows are read-only via MCP for now (editing risks breaking already-scheduled runs); create a new draft for changes instead. Status changes go through workflows-enable / workflows-archive. A batch audience is config.filters.properties — person-property conditions and/or cohort references. Prefer person properties or a dynamic (filter-based) cohort, which re-evaluate, over a static frozen-list cohort. An event trigger fires on every occurrence matching the event and the trigger's filters; throttle repeat firings with trigger_masking (dedup/sampling — not behavioral filtering). Behavioral cohorts/targeting ('did event X at least N times over the last M days') are unsupported — if the user requests one, reject it and explain why.",+ "description": "Fallback editor. Prefer workflows-patch-graph for graph changes: it sends only the delta, is structurally validated, and returns the full updated graph. Reach for workflows-update for top-level metadata a patch can't express (name, description, exit_condition), or as an escape hatch to replace the whole workflow when you can't get workflows-patch-graph to land a change. Draft only: active workflows are read-only via MCP (editing risks breaking already-scheduled runs), so create a new draft to change a live one. Status changes go through workflows-enable / workflows-archive.","category": "Workflows","feature": "workflows","summary": "Update workflow",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 97e2a2297e5f..fefa326cfa27 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -607,7 +607,7 @@}},"workflows-enable": {- "description": "Enable / activate a draft workflow and start processing events. Confirm with the user before invoking.",+ "description": "Enable / activate a draft workflow and start processing events. One-way door: a live workflow can't be edited over MCP (to change it you recreate it as a new draft), so test it first and get the user's explicit approval before invoking. Don't enable on your own initiative.","category": "Workflows","feature": "workflows","summary": "Enable workflow",