: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
feat(workflows): link broadcasts to the broadcast scene and suggest broadcasts over mcp (#120581)
Daniel Marchuk23798942d2d5
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex b4fd969b4f5a..fd3e4763869a 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -43,6 +43,7 @@ tools:readOnly: falsedestructive: falseidempotent: false+ enrich_url: '{id}'title: Create broadcastdescription: >Create a broadcast: a one-time or scheduled email to an audience, which the user reviews and launches from@@ -58,6 +59,27 @@ tools:workflows-patch-action-email.inject_body:origin_product: broadcasts+ url_prefix: /broadcasts+ workflows-convert-to-broadcast:+ operation: hog_flows_convert_to_broadcast+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ enrich_url: '{id}'+ title: Convert workflow to broadcast+ description: >+ Move a workflow that sends one email to a batch audience over to broadcasts. It keeps its id, runs and+ metrics, leaves the workflows list and opens in the broadcast editor, which shows delivery, open and click+ numbers per send. It can no longer take more steps, and this cannot be undone, so ask the user first. The+ workflow must be exactly a batch trigger, one email and an exit, joined in that order, with exit_condition+ 'exit_only_at_end' (set it with workflows-update first). It fails with a validation error for any other+ shape, an archived workflow, a workflow with a staged draft, or one that is already a broadcast. Returns the+ id and origin_product, plus _posthogUrl, the broadcast link.+ url_prefix: /broadcastsworkflows-create:operation: hog_flows_createenabled: true@@ -70,7 +92,9 @@ tools:enrich_url: '{id}/workflow'title: Create workflowdescription: >- Create a workflow. Before a project's first email, SMS or push workflow, call workflows-setup-status when it+ Create a workflow. For one email sent once or on a schedule to an audience (a batch trigger, one email step+ and an exit), use broadcasts-create instead: the user gets the broadcast editor and per-send delivery, open+ and click numbers. Before a project's first email, SMS or push workflow, call workflows-setup-status when itis available, so the user knows what blocks sending. It is created as a draft and does NOT run untilenabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicitapproval — from then on it runs on real people, and further content edits stage as a draft you must publish@@ -95,6 +119,7 @@ tools:cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X atleast N times over the last M days') is unsupported; reject it and explain why.ui_app: workflow+ hooks: workflows/broadcastLinkHooksworkflows-data-suggestions-create:operation: workflow_data_suggestions_buildenabled: true@@ -216,6 +241,7 @@ tools:awaiting workflows-publish (null when nothing is staged) — the live config in actions/edges is what'srunning.ui_app: workflow+ hooks: workflows/broadcastLinkHooksworkflows-get-invocation:operation: hog_flows_invocation_result_retrieveenabled: true@@ -591,6 +617,7 @@ tools:- actions- edgesui_app: workflow+ hooks: workflows/broadcastLinkHooksworkflows-update-schedule:operation: hog_flows_schedules_partial_updateenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex e7d03d67528f..55475f6a3927 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -15015,8 +15015,22 @@},"feature_flag": "engineering-analytics"},+ "workflows-convert-to-broadcast": {+ "description": "Move a workflow that sends one email to a batch audience over to broadcasts. It keeps its id, runs and metrics, leaves the workflows list and opens in the broadcast editor, which shows delivery, open and click numbers per send. It can no longer take more steps, and this cannot be undone, so ask the user first. The workflow must be exactly a batch trigger, one email and an exit, joined in that order, with exit_condition 'exit_only_at_end' (set it with workflows-update first). It fails with a validation error for any other shape, an archived workflow, a workflow with a staged draft, or one that is already a broadcast. Returns the id and origin_product, plus _posthogUrl, the broadcast link.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Convert workflow to broadcast",+ "title": "Convert workflow to broadcast",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-create": {- "description": "Create a workflow. Before a project's first email, SMS or push workflow, call workflows-setup-status when it is available, so the user knows what blocks sending. 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 — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. 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. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. 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. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",+ "description": "Create a workflow. For one email sent once or on a schedule to an audience (a batch trigger, one email step and an exit), use broadcasts-create instead: the user gets the broadcast editor and per-send delivery, open and click numbers. Before a project's first email, SMS or push workflow, call workflows-setup-status when it is available, so the user knows what blocks sending. 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 — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. 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. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. 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. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its cadence with workflows-schedule-create and skip the audience preview. 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",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 3b2fc0ff6769..51ee00368976 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -15737,8 +15737,22 @@"readOnlyHint": true}},+ "workflows-convert-to-broadcast": {+ "description": "Move a workflow that sends one email to a batch audience over to broadcasts. It keeps its id, runs and metrics, leaves the workflows list and opens in the broadcast editor, which shows delivery, open and click numbers per send. It can no longer take more steps, and this cannot be undone, so ask the user first. The workflow must be exactly a batch trigger, one email and an exit, joined in that order, with exit_condition 'exit_only_at_end' (set it with workflows-update first). It fails with a validation error for any other shape, an archived workflow, a workflow with a staged draft, or one that is already a broadcast. Returns the id and origin_product, plus _posthogUrl, the broadcast link.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Convert workflow to broadcast",+ "title": "Convert workflow to broadcast",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-create": {- "description": "Create a workflow. Before a project's first email, SMS or push workflow, call workflows-setup-status when it is available, so the user knows what blocks sending. 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 — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. 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. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. 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. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its cadence with workflows-schedule-create and skip the audience preview. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",+ "description": "Create a workflow. For one email sent once or on a schedule to an audience (a batch trigger, one email step and an exit), use broadcasts-create instead: the user gets the broadcast editor and per-send delivery, open and click numbers. Before a project's first email, SMS or push workflow, call workflows-setup-status when it is available, so the user knows what blocks sending. 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 — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|schedule|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. 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. For '$account_custom_property_changed', current_value is polymorphic. To target multiple property types, repeat that event in filters.events: nested properties in each event entry are ANDed, while event entries are ORed. For example, one entry can pair property_name=Plan with current_value=enterprise and another can pair property_name=Seats with current_value greater than 5; do not put one shared current_value condition in top-level properties. 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. A 'schedule' trigger has no audience: it runs once per occurrence, so attach its cadence with workflows-schedule-create and skip the audience preview. 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",diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex e4797771a5a1..ce55d01940de 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 28 enabled ops+ * PostHog API - MCP 29 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -749,6 +749,19 @@ export const HogFlowsBatchJobsListParams = () => zod.object({),})+/**+ * Move a workflow to broadcasts. It keeps its id, runs and metrics, leaves the workflows list and opens+ * in the broadcast editor. This cannot be undone.+ */+export const HogFlowsConvertToBroadcastParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this hog flow.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})+export const HogFlowsDiscardDraftCreateParams = () => zod.object({id: zod.string().describe('A UUID string identifying this hog flow.'),project_id: zoddiff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex bc840ab6ba28..d1885b236176 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -8,6 +8,9 @@ import { WorkflowActionEmailPatchSchema, WorkflowGraphPatchSchema } from '@/scheimport { withToolHooks } from '@/tools/tool-hooks'import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+import hooks_workflowsCreate from '@/tools/workflows/broadcastLinkHooks'+import hooks_workflowsGet from '@/tools/workflows/broadcastLinkHooks'+import hooks_workflowsUpdate from '@/tools/workflows/broadcastLinkHooks'import hooks_workflowsDataSuggestionsCreate from '@/tools/workflows/dataSuggestionCreateHooks'const BroadcastsCreateSchema = () => {@@ -15,7 +18,7 @@ const BroadcastsCreateSchema = () => {return HogFlowsCreateBody}-const broadcastsCreate = (): ToolBase<ReturnType<typeof BroadcastsCreateSchema>, Schemas.HogFlow> => ({+const broadcastsCreate = (): ToolBase<ReturnType<typeof BroadcastsCreateSchema>, WithPostHogUrl<Schemas.HogFlow>> => ({name: 'broadcasts-create',schema: BroadcastsCreateSchema(),handler: async (context: Context, params: z.infer<ReturnType<typeof BroadcastsCreateSchema>>) => {@@ -60,7 +63,28 @@ const broadcastsCreate = (): ToolBase<ReturnType<typeof BroadcastsCreateSchema>,path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/`,body,})- return result+ return await withPostHogUrl(context, result, `/broadcasts/${result.id}`)+ },+})++const WorkflowsConvertToBroadcastSchema = () => {+ const HogFlowsConvertToBroadcastParams = orvalSchemas.HogFlowsConvertToBroadcastParams()+ return HogFlowsConvertToBroadcastParams.omit({ project_id: true })+}++const workflowsConvertToBroadcast = (): ToolBase<+ ReturnType<typeof WorkflowsConvertToBroadcastSchema>,+ WithPostHogUrl<Schemas.HogFlowConvertedToBroadcast>+> => ({+ name: 'workflows-convert-to-broadcast',+ schema: WorkflowsConvertToBroadcastSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsConvertToBroadcastSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.HogFlowConvertedToBroadcast>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/convert_to_broadcast/`,+ })+ return await withPostHogUrl(context, result, `/broadcasts/${result.id}`)},})@@ -73,49 +97,52 @@ const workflowsCreate = (): ToolBase<ReturnType<typeof WorkflowsCreateSchema>, WwithUiApp('workflow', {name: 'workflows-create',schema: WorkflowsCreateSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsCreateSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.name !== undefined) {- body['name'] = params.name- }- if (params.description !== undefined) {- body['description'] = params.description- }- if (params.status !== undefined) {- body['status'] = params.status- }- if (params.origin_product !== undefined) {- body['origin_product'] = params.origin_product- }- if (params.trigger_masking !== undefined) {- body['trigger_masking'] = params.trigger_masking- }- if (params.conversion !== undefined) {- body['conversion'] = params.conversion- }- if (params.exit_condition !== undefined) {- body['exit_condition'] = params.exit_condition- }- if (params.email_sending_rate_limit !== undefined) {- body['email_sending_rate_limit'] = params.email_sending_rate_limit- }- if (params.edges !== undefined) {- body['edges'] = params.edges- }- if (params.actions !== undefined) {- body['actions'] = params.actions- }- if (params.variables !== undefined) {- body['variables'] = params.variables+ handler: withToolHooks(+ hooks_workflowsCreate,+ async (context: Context, params: z.infer<ReturnType<typeof WorkflowsCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.status !== undefined) {+ body['status'] = params.status+ }+ if (params.origin_product !== undefined) {+ body['origin_product'] = params.origin_product+ }+ if (params.trigger_masking !== undefined) {+ body['trigger_masking'] = params.trigger_masking+ }+ if (params.conversion !== undefined) {+ body['conversion'] = params.conversion+ }+ if (params.exit_condition !== undefined) {+ body['exit_condition'] = params.exit_condition+ }+ if (params.email_sending_rate_limit !== undefined) {+ body['email_sending_rate_limit'] = params.email_sending_rate_limit+ }+ if (params.edges !== undefined) {+ body['edges'] = params.edges+ }+ if (params.actions !== undefined) {+ body['actions'] = params.actions+ }+ if (params.variables !== undefined) {+ body['variables'] = params.variables+ }+ const result = await context.api.request<Schemas.HogFlow>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/`,+ body,+ })+ return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)}- const result = await context.api.request<Schemas.HogFlow>({- method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/`,- body,- })- return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)- },+ ),})const WorkflowsDataSuggestionsCreateSchema = () => {@@ -252,14 +279,17 @@ const workflowsGet = (): ToolBase<ReturnType<typeof WorkflowsGetSchema>, WithPoswithUiApp('workflow', {name: 'workflows-get',schema: WorkflowsGetSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsGetSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.HogFlow>({- method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/`,- })- return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)- },+ handler: withToolHooks(+ hooks_workflowsGet,+ async (context: Context, params: z.infer<ReturnType<typeof WorkflowsGetSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.HogFlow>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/`,+ })+ return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)+ }+ ),})const WorkflowsGetInvocationSchema = () => {@@ -805,37 +835,40 @@ const workflowsUpdate = (): ToolBase<ReturnType<typeof WorkflowsUpdateSchema>, WwithUiApp('workflow', {name: 'workflows-update',schema: WorkflowsUpdateSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsUpdateSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.name !== undefined) {- body['name'] = params.name- }- if (params.description !== undefined) {- body['description'] = params.description- }- if (params.trigger_masking !== undefined) {- body['trigger_masking'] = params.trigger_masking- }- if (params.conversion !== undefined) {- body['conversion'] = params.conversion- }- if (params.exit_condition !== undefined) {- body['exit_condition'] = params.exit_condition- }- if (params.email_sending_rate_limit !== undefined) {- body['email_sending_rate_limit'] = params.email_sending_rate_limit- }- if (params.variables !== undefined) {- body['variables'] = params.variables+ handler: withToolHooks(+ hooks_workflowsUpdate,+ async (context: Context, params: z.infer<ReturnType<typeof WorkflowsUpdateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.trigger_masking !== undefined) {+ body['trigger_masking'] = params.trigger_masking+ }+ if (params.conversion !== undefined) {+ body['conversion'] = params.conversion+ }+ if (params.exit_condition !== undefined) {+ body['exit_condition'] = params.exit_condition+ }+ if (params.email_sending_rate_limit !== undefined) {+ body['email_sending_rate_limit'] = params.email_sending_rate_limit+ }+ if (params.variables !== undefined) {+ body['variables'] = params.variables+ }+ const result = await context.api.request<Schemas.HogFlowUpdate>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/`,+ body,+ })+ return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)}- const result = await context.api.request<Schemas.HogFlowUpdate>({- method: 'PATCH',- path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/`,- body,- })- return await withPostHogUrl(context, result, `/workflows/${result.id}/workflow`)- },+ ),})const WorkflowsUpdateScheduleSchema = () => {@@ -912,6 +945,7 @@ const workflowsVersionStats = (): ToolBase<export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'broadcasts-create': broadcastsCreate,+ 'workflows-convert-to-broadcast': workflowsConvertToBroadcast,'workflows-create': workflowsCreate,'workflows-data-suggestions-create': workflowsDataSuggestionsCreate,'workflows-data-suggestions-get': workflowsDataSuggestionsGet,diff --git a/services/mcp/src/tools/workflows/broadcastLinkHooks.ts b/services/mcp/src/tools/workflows/broadcastLinkHooks.tsnew file mode 100644index 000000000000..229e706456b7--- /dev/null+++ b/services/mcp/src/tools/workflows/broadcastLinkHooks.ts@@ -0,0 +1,16 @@+import type { ToolHooks } from '@/tools/tool-hooks'+import { withAgentNote, withPostHogUrl } from '@/tools/tool-utils'+import type { Context } from '@/tools/types'+import { broadcastConversionNote, type HogFlowLike, hogFlowPath } from '@/tools/workflows/hogFlowLink'++async function afterResponse(context: Context, _params: unknown, result: unknown): Promise<unknown> {+ const flow = result as HogFlowLike | null+ if (!flow?.id) {+ return result+ }+ const linked = await withPostHogUrl(context, result, hogFlowPath({ ...flow, id: flow.id }))+ const note = broadcastConversionNote(flow)+ return note ? withAgentNote(linked, note) : linked+}++export default { afterResponse } satisfies ToolHooks<unknown>diff --git a/services/mcp/src/tools/workflows/hogFlowLink.ts b/services/mcp/src/tools/workflows/hogFlowLink.tsnew file mode 100644index 000000000000..9a72e17bbc4a--- /dev/null+++ b/services/mcp/src/tools/workflows/hogFlowLink.ts@@ -0,0 +1,57 @@+type FlowStep = {+ id?: string+ type?: string+ config?: { type?: string; filters?: { audience_type?: string } | null } | null+}+type FlowEdge = { from?: string; to?: string }++export type HogFlowLike = {+ id?: string+ status?: string | null+ origin_product?: string | null+ exit_condition?: string | null+ draft?: unknown+ actions?: FlowStep[] | null+ edges?: FlowEdge[] | null+}++/** The app path a hog flow opens at: broadcasts have their own scene, everything else is the workflow editor. */+export function hogFlowPath(flow: { id: string; origin_product?: string | null }): string {+ return flow.origin_product === 'broadcasts' ? `/broadcasts/${flow.id}` : `/workflows/${flow.id}/workflow`+}++// Mirrors is_convertible_to_broadcast in the backend, except the exit condition, which the note asks the agent to fix+// first. A flow the endpoint would refuse for any other reason gets no note.+function isConvertibleShape(flow: HogFlowLike): boolean {+ if (flow.origin_product || flow.status === 'archived' || flow.draft) {+ return false+ }+ const steps = flow.actions ?? []+ const trigger = steps.find((step) => step.type === 'trigger')+ const email = steps.find((step) => step.type === 'function_email')+ const exit = steps.find((step) => step.type === 'exit')+ if (steps.length !== 3 || !trigger || !email || !exit) {+ return false+ }+ if (trigger.config?.type !== 'batch' || trigger.config?.filters?.audience_type === 'accounts') {+ return false+ }+ const paths = new Set((flow.edges ?? []).map((edge) => `${edge.from}->${edge.to}`))+ return paths.size === 2 && paths.has(`${trigger.id}->${email.id}`) && paths.has(`${email.id}->${exit.id}`)+}++/** Guidance for an agent that made or fetched a workflow which could be a broadcast, or null when it can't be one. */+export function broadcastConversionNote(flow: HogFlowLike): string | null {+ if (!isConvertibleShape(flow)) {+ return null+ }+ const exitStep =+ flow.exit_condition === 'exit_only_at_end'+ ? ''+ : " Converting needs exit_condition 'exit_only_at_end', so set that with workflows-update first."+ return (+ 'This workflow is one email to a batch audience, which is a broadcast. Ask the user whether to move it to ' ++ 'broadcasts with workflows-convert-to-broadcast: it then opens in the broadcast editor with per-send ' ++ `delivery, open and click numbers, and can no longer take more steps.${exitStep}`+ )+}diff --git a/services/mcp/src/tools/workflows/lifecycle.ts b/services/mcp/src/tools/workflows/lifecycle.tsindex fba6342a36a9..abd516486e0e 100644--- a/services/mcp/src/tools/workflows/lifecycle.ts+++ b/services/mcp/src/tools/workflows/lifecycle.ts@@ -5,6 +5,7 @@ import { HogFlowsPartialUpdateParams } from '@/generated/workflows/api'import { withUiApp } from '@/resources/ui-apps'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase } from '@/tools/types'+import { hogFlowPath } from '@/tools/workflows/hogFlowLink'const LifecycleSchema = HogFlowsPartialUpdateParams().omit({ project_id: true })@@ -22,7 +23,7 @@ const patchStatus = async (path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/`,body: { status },})- return await withPostHogUrl(context, result, `/pipeline/destinations/hog-${result.id}`)+ return await withPostHogUrl(context, result, hogFlowPath(result))}export const workflowsEnable = (): ToolBase<typeof LifecycleSchema, LifecycleResult> =>diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-convert-to-broadcast.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-convert-to-broadcast.jsonnew file mode 100644index 000000000000..6c38f5b9f257--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-convert-to-broadcast.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this hog flow.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/workflows-broadcast-link-hooks.test.ts b/services/mcp/tests/unit/workflows-broadcast-link-hooks.test.tsnew file mode 100644index 000000000000..fe87a5eef963--- /dev/null+++ b/services/mcp/tests/unit/workflows-broadcast-link-hooks.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest'++import type { Context } from '@/tools/types'+import hooks from '@/tools/workflows/broadcastLinkHooks'++const context = {+ stateManager: { getProjectId: async () => '7' },+ api: { getProjectBaseUrl: (projectId: string) => `https://app.example.com/project/${projectId}` },+} as unknown as Context++const WORKFLOW_URL = 'https://app.example.com/project/7/workflows/abc/workflow'+const BROADCAST_URL = 'https://app.example.com/project/7/broadcasts/abc'+const oneEmailBatch = {+ id: 'abc',+ status: 'draft',+ origin_product: null,+ exit_condition: 'exit_only_at_end',+ draft: null,+ actions: [+ { id: 't', type: 'trigger', config: { type: 'batch', filters: {} } },+ { id: 'e', type: 'function_email', config: {} },+ { id: 'x', type: 'exit', config: {} },+ ],+ edges: [+ { from: 't', to: 'e' },+ { from: 'e', to: 'x' },+ ],+}++describe('broadcastLinkHooks', () => {+ it.each([+ {+ name: 'a broadcast links to the broadcast scene',+ flow: { origin_product: 'broadcasts' },+ url: BROADCAST_URL,+ },+ {+ name: 'an archived broadcast still links to the broadcast scene',+ flow: { origin_product: 'broadcasts', status: 'archived' },+ url: BROADCAST_URL,+ },+ { name: 'a one-email batch workflow suggests a broadcast', flow: {}, note: 'workflows-convert-to-broadcast' },+ {+ name: 'the default exit condition asks for exit_only_at_end first',+ flow: { exit_condition: 'exit_on_conversion' },+ note: 'exit_only_at_end',+ },+ {+ name: 'a workflow with more steps is left alone',+ flow: { actions: [...oneEmailBatch.actions, { id: 'd', type: 'delay', config: {} }] },+ },+ {+ name: 'an event trigger is left alone',+ flow: {+ actions: [{ id: 't', type: 'trigger', config: { type: 'event' } }, ...oneEmailBatch.actions.slice(1)],+ },+ },+ { name: 'an email that skips to the exit is left alone', flow: { edges: [{ from: 't', to: 'x' }] } },+ { name: 'a staged draft is left alone', flow: { draft: { actions: [] } } },+ { name: 'an archived workflow is left alone', flow: { status: 'archived' } },+ { name: 'a workflow another product owns is left alone', flow: { origin_product: 'surveys' } },+ ])('$name', async ({ flow, url, note }) => {+ const result = (await hooks.afterResponse(context, {}, { ...oneEmailBatch, ...flow })) as {+ _posthogUrl: string+ _agentNote?: string+ }++ expect(result._posthogUrl).toBe(url ?? WORKFLOW_URL)+ if (note) {+ expect(result._agentNote).toContain(note)+ } else {+ expect(result._agentNote).toBeUndefined()+ }+ })+})