Skip to content

: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.

12.1 KB
Raw Blame
import { z } from 'zod'

import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'
import { isFeatureFlagEnabled } from '@/lib/posthog/flags'
import type { Context, ToolBase } from '@/tools/types'

type BlastRadius = { affected: number; total: number; limit: number; confirm_token: string }

type WorkflowTrigger = { type?: string; filters?: unknown }

type WorkflowAction = { type?: string; config?: { template_id?: string } }

const SENDING_TIER_REQUESTS_FLAG = 'workflows-sending-tier-requests'

async function fetchWorkflow(
    context: Context,
    projectId: string,
    workflowId: string
): Promise<{ status: string | undefined; trigger: WorkflowTrigger; sendsEmail: boolean }> {
    const workflow = await context.api.request<{ status?: string; trigger?: unknown; actions?: WorkflowAction[] }>({
        method: 'GET',
        path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(workflowId))}/`,
    })
    return {
        status: workflow.status,
        trigger: (workflow.trigger ?? {}) as WorkflowTrigger,
        sendsEmail: workflowSendsEmail(workflow.actions),
    }
}

// Kept in sync with hog_flow_sends_email on the backend, which applies the email tier cap only to workflows with an email step.
function workflowSendsEmail(actions: WorkflowAction[] | undefined): boolean {
    return (actions ?? []).some(
        (action) => action?.type === 'function_email' || action?.config?.template_id === 'template-email'
    )
}

function triggerFilters(trigger: WorkflowTrigger): unknown {
    return trigger.filters ?? { properties: [] }
}

async function sizeAudience(
    context: Context,
    projectId: string,
    filters: unknown,
    sendsEmail: boolean
): Promise<BlastRadius> {
    return await context.api.request<BlastRadius>({
        method: 'POST',
        path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/user_blast_radius/`,
        body: { filters, sends_email: sendsEmail },
    })
}

// Evaluate with the same workspace groups tool discovery uses, so a flag that targets projects or
// organizations agrees with whether workflows-reputation-get is listed.
async function sendingTierRequestsEnabled(context: Context): Promise<boolean> {
    const analyticsContext = await context.stateManager.getAnalyticsContext().catch(() => undefined)
    return await isFeatureFlagEnabled(
        SENDING_TIER_REQUESTS_FLAG,
        await context.getDistinctId(),
        analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : undefined
    )
}

/**
 * Echo-back guard: the caller must have sized the audience with workflows-blast-radius and surfaced the
 * number to the user. We recompute it here and reject on drift or over-cap before any fan-out. The cap is
 * the per-team `limit` the blast-radius endpoint returns (HOGFLOW_BATCH_TRIGGER_LIMIT), which the batch
 * consumer also enforces — so the run is rejected here rather than silently truncated downstream.
 */
async function assertAcknowledged(
    context: Context,
    affected: number,
    acknowledged: number,
    limit: number,
    sendsEmail: boolean
): Promise<void> {
    if (affected !== acknowledged) {
        throw new Error(
            `Audience size is now ${affected} users (you acknowledged ${acknowledged}). Re-check with ` +
                `workflows-blast-radius and confirm the new count with the user before running.`
        )
    }
    if (affected > limit) {
        // The flag is read only here, so runs within the cap never wait on flag evaluation.
        const pointAtTier = sendsEmail && (await sendingTierRequestsEnabled(context))
        throw new Error(
            `Audience of ${affected} users exceeds the ${limit}-user cap for this project. Narrow the ` +
                `workflow's batch trigger filters to reduce the audience, then try again.` +
                (pointAtTier
                    ? ` If workflows-reputation-get shows sending_allowance.enforced with this max_batch_audience, ` +
                      `the cap comes from the project's email sending tier, which grows with a clean sending ` +
                      `record. If the user needs a higher cap, tell them they can request one from Workflows > ` +
                      `Messaging > Reputation with "Request a higher allowance".`
                    : '')
        )
    }
}

const BlastRadiusSchema = z.object({
    workflow_id: z.string().describe('ID of the workflow whose batch-trigger audience to size.'),
})

export const workflowsBlastRadius = (): ToolBase<typeof BlastRadiusSchema, BlastRadius> => ({
    name: 'workflows-blast-radius',
    schema: BlastRadiusSchema,
    handler: async (context, params) => {
        const projectId = await context.stateManager.getProjectId()
        const { trigger, sendsEmail } = await fetchWorkflow(context, projectId, params.workflow_id)
        return await sizeAudience(context, projectId, triggerFilters(trigger), sendsEmail)
    },
})

const RunBatchSchema = z.object({
    workflow_id: z.string().describe('ID of the batch workflow to run now.'),
    acknowledged_affected_count: z
        .number()
        .int()
        .describe(
            'The affected-user count from workflows-blast-radius that you showed the user AND they explicitly ' +
                'confirmed before you called this — never size and fire in one step. Rejected if it no longer ' +
                'matches the current audience, forcing a re-check.'
        ),
    confirm_token: z
        .string()
        .describe(
            'The confirm_token from the same workflows-blast-radius preview whose count the user confirmed. ' +
                'The API rejects dispatch without it, and it goes stale when the audience filters change or ' +
                'after 15 minutes — re-preview to refresh.'
        ),
    variables: z
        .record(z.string(), z.unknown())
        .optional()
        .describe('Optional {key: value} variable overrides for this run; defaults to the workflow definition.'),
})

export const workflowsRunBatch = (): ToolBase<typeof RunBatchSchema, unknown> => ({
    name: 'workflows-run-batch',
    schema: RunBatchSchema,
    handler: async (context, params) => {
        const projectId = await context.stateManager.getProjectId()
        const { status, trigger, sendsEmail } = await fetchWorkflow(context, projectId, params.workflow_id)

        if (trigger.type !== 'batch') {
            throw new Error(
                `workflows-run-batch only applies to workflows with a 'batch' trigger (this one is ` +
                    `'${trigger.type ?? 'unknown'}'). Use workflows-test-run to test-invoke, or a schedule for recurring runs.`
            )
        }

        if (status !== 'active') {
            throw new Error(
                `Workflow is not active (status '${status ?? 'unknown'}') — a batch run sends real messages, so the ` +
                    `workflow must be enabled first with workflows-enable.`
            )
        }

        const filters = triggerFilters(trigger)
        const { affected, limit } = await sizeAudience(context, projectId, filters, sendsEmail)
        await assertAcknowledged(context, affected, params.acknowledged_affected_count, limit, sendsEmail)

        return await context.api.request({
            method: 'POST',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.workflow_id))}/batch_jobs/`,
            body: {
                filters,
                confirm_token: params.confirm_token,
                ...(params.variables !== undefined ? { variables: params.variables } : {}),
            },
        })
    },
})

const ScheduleCreateSchema = z.object({
    workflow_id: z
        .string()
        .describe('ID of the workflow to attach the recurring schedule to. Its trigger must be batch or schedule.'),
    rrule: z
        .string()
        .describe("iCalendar RRULE (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."),
    starts_at: z.string().describe('ISO 8601 datetime the schedule starts from.'),
    timezone: z.string().optional().describe("IANA timezone for the RRULE (default 'UTC')."),
    acknowledged_affected_count: z
        .number()
        .int()
        .optional()
        .describe(
            'Batch triggers only: the affected-user count from workflows-blast-radius that you showed the user ' +
                'AND they explicitly confirmed before scheduling. Each firing re-broadcasts to the audience at that ' +
                'time; rejected if it no longer matches. Omit for a schedule trigger, which has no audience.'
        ),
    confirm_token: z
        .string()
        .optional()
        .describe(
            'Batch triggers only: the confirm_token from the same workflows-blast-radius preview whose count the ' +
                'user confirmed. The API rejects a batch schedule without it, and it goes stale when the audience ' +
                'filters change or after 15 minutes - re-preview to refresh. Omit for a schedule trigger.'
        ),
    variables: z
        .record(z.string(), z.unknown())
        .optional()
        .describe('Optional {key: value} variable overrides merged with the workflow defaults on each run.'),
})

export const workflowsScheduleCreate = (): ToolBase<typeof ScheduleCreateSchema, unknown> => ({
    name: 'workflows-schedule-create',
    schema: ScheduleCreateSchema,
    handler: async (context, params) => {
        const projectId = await context.stateManager.getProjectId()
        const { status, trigger, sendsEmail } = await fetchWorkflow(context, projectId, params.workflow_id)

        if (trigger.type !== 'batch' && trigger.type !== 'schedule') {
            throw new Error(
                `workflows-schedule-create only applies to workflows with a 'batch' or 'schedule' trigger (this ` +
                    `one is '${trigger.type ?? 'unknown'}').`
            )
        }

        // A schedule trigger fires one person-less run per occurrence, so there is no audience to
        // size or confirm. Only a batch trigger fans out to persons and needs the blast-radius step.
        let confirmToken: string | undefined
        if (trigger.type === 'batch') {
            // Require the workflow to be active before scheduling. A draft's trigger can still be edited in
            // place, so scheduling a draft would let the audience be broadened after you acknowledged it (the
            // scheduler uses the trigger's filters at fire time). On an active workflow an MCP trigger edit only
            // stages a draft, so the acknowledged audience can't change without an explicit publish.
            if (status !== 'active') {
                throw new Error(
                    `Workflow is not active (status '${status ?? 'unknown'}') — enable it with workflows-enable before ` +
                        `scheduling. Scheduling a draft would let the audience change after you sized it.`
                )
            }
            if (params.acknowledged_affected_count === undefined || params.confirm_token === undefined) {
                throw new Error(
                    'A batch trigger schedules a recurring broadcast: preview the audience with workflows-blast-radius, ' +
                        'confirm the count with the user, then pass acknowledged_affected_count and confirm_token.'
                )
            }
            const { affected, limit } = await sizeAudience(context, projectId, triggerFilters(trigger), sendsEmail)
            await assertAcknowledged(context, affected, params.acknowledged_affected_count, limit, sendsEmail)
            confirmToken = params.confirm_token
        }

        return await context.api.request({
            method: 'POST',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.workflow_id))}/schedules/`,
            body: {
                rrule: params.rrule,
                starts_at: params.starts_at,
                ...(confirmToken !== undefined ? { confirm_token: confirmToken } : {}),
                ...(params.timezone !== undefined ? { timezone: params.timezone } : {}),
                ...(params.variables !== undefined ? { variables: params.variables } : {}),
            },
        })
    },
})