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.

feat(workflows): read and update sending rules over MCP (#118494)

Meikel Ratz1ca1472fff02
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4f086d17fe39..fad723b041db 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6406,6 +6406,10 @@ snapshots:
hash: v1.k794b7964.4cbfe20c626f0f7912dbd47b41a152c9c30f92d12a3f599476fb10043d7f7e70.9NI9FaMch59lt8xO3Xhp9ruHKLyDcvupNp20dZrR8_Y
mcp-apps-workflows--list--light:
hash: v1.k794b7964.05ea602d6d9345842a6335a7a5dfd2708b35e7e84582dedab2d4f75daab793c5.R8GtNbF9pB7JrXdEIBpk8XsgLhKJuKMA1UB9qr0Tzbs
+ mcp-apps-workflows--sending-rules-no-cap--light:
+ hash: v1.k794b7964.867f1b4e3d741066f04905b02b7fac75d46359ea5ad0edeaa90f9d628d9d77c3.PT8sl8on2CltpY-AcuDeqrMESYi9vEU9WtCxx0qb3sk
+ mcp-apps-workflows--sending-rules-with-cap--light:
+ hash: v1.k794b7964.1fdf067e0e75418820aadb9c30f5db135a6505da2a04ed16b79fcc8c1c8b42ab.mRdiS_UV-b32KVoSSAeIllMAJvEEbA1HGqeZQDvtoIU
mcp-apps-workflows--setup-status-done--light:
hash: v1.k794b7964.2ecc52194af0bc94be9841afc57128da763075064497948ecd81e2114695bc81.9CDthZ77iyEZATCkKdP_y8cU2nOu9KDWR_uKm-sBvBk
mcp-apps-workflows--setup-status-in-progress--light:
diff --git a/products/workflows/backend/presentation/views/workflow_sending_rules.py b/products/workflows/backend/presentation/views/workflow_sending_rules.py
new file mode 100644
index 000000000000..2178e252a160
--- /dev/null
+++ b/products/workflows/backend/presentation/views/workflow_sending_rules.py
@@ -0,0 +1,102 @@
+from typing import Any
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.project import update_team_workflows_config
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.organization import OrganizationMembership
+
+from products.workflows.backend.facade.enums import EMAIL_TRACKING_CONSENT_MODE_CHOICES
+from products.workflows.backend.facade.team_extension import TeamWorkflowsConfig
+
+
+class WorkflowSendingRulesSerializer(serializers.Serializer):
+ project_id = serializers.IntegerField(
+ source="team_id", read_only=True, help_text="The project these sending rules belong to."
+ )
+ expected_project_id = serializers.IntegerField(
+ write_only=True,
+ required=False,
+ help_text="Optional. The project_id from the rules being changed. The update is rejected when it does not "
+ "match the current project, so a change never lands in a project the user did not look at.",
+ )
+ marketing_frequency_cap_max_messages = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ max_value=1000,
+ help_text="The most marketing messages one person gets in the window, across all workflows and broadcasts. "
+ "Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. "
+ "Transactional messages are never capped. The recommended cap is 1 message every 2 days.",
+ )
+ marketing_frequency_cap_window_days = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ max_value=30,
+ help_text="The length of the rolling frequency cap window, in days. Set it together with "
+ "marketing_frequency_cap_max_messages, or set both to null to turn the cap off.",
+ )
+ email_tracking_consent_mode = serializers.ChoiceField(
+ choices=EMAIL_TRACKING_CONSENT_MODE_CHOICES,
+ required=False,
+ help_text="Whether tracking opens and clicks on marketing email needs the recipient's consent. "
+ "'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' "
+ "tracks only recipients who consented. Transactional email is never affected.",
+ )
+ capture_workflows_engagement_events = serializers.BooleanField(
+ required=False,
+ help_text="Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights "
+ "and funnels. These events count toward the project's event usage.",
+ )
+
+
+class WorkflowSendingRulesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """The project-wide rules every workflow and broadcast follows when it sends a message."""
+
+ scope_object = "project"
+ scope_object_read_actions = ["current"]
+ scope_object_write_actions = ["update_current"]
+
+ @extend_schema(operation_id="workflow_sending_rules_retrieve", responses={200: WorkflowSendingRulesSerializer})
+ @action(detail=False, methods=["get"])
+ def current(self, request: Request, **kwargs: Any) -> Response:
+ return Response(self._rules())
+
+ @extend_schema(
+ operation_id="workflow_sending_rules_partial_update",
+ request=WorkflowSendingRulesSerializer,
+ responses={200: WorkflowSendingRulesSerializer},
+ )
+ @current.mapping.patch
+ def update_current(self, request: Request, **kwargs: Any) -> Response:
+ # Matches the admin-only rule on workflows_config in project settings.
+ level = self.user_permissions.team(self.team).effective_membership_level
+ if level is None or level < OrganizationMembership.Level.ADMIN:
+ raise PermissionDenied("Only project admins can change sending rules.")
+ payload = WorkflowSendingRulesSerializer(data=request.data, partial=True)
+ payload.is_valid(raise_exception=True)
+ changes = dict(payload.validated_data)
+ expected_project_id = changes.pop("expected_project_id", None)
+ if expected_project_id is not None and expected_project_id != self.team.id:
+ raise ValidationError(
+ {"expected_project_id": "These sending rules belong to another project. Switch back to it first."}
+ )
+ update_team_workflows_config(
+ self.team,
+ changes,
+ context={"request": request, "user_access_control": self.user_access_control},
+ )
+ return Response(self._rules())
+
+ def _rules(self) -> dict[str, Any]:
+ # Read the row fresh: `Team.workflows_config` is a cached_property and can hold values from before an update.
+ config = TeamWorkflowsConfig.objects.filter(team_id=self.team.id).first() or TeamWorkflowsConfig(
+ team_id=self.team.id
+ )
+ return WorkflowSendingRulesSerializer(config).data
diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.py
index 1de904dd6439..583d61001597 100644
--- a/products/workflows/backend/routes.py
+++ b/products/workflows/backend/routes.py
@@ -13,6 +13,7 @@ from products.workflows.backend.presentation.views import (
workflow_classifications,
workflow_data_suggestions,
workflow_scout_runs,
+ workflow_sending_rules,
workflow_setup,
workflow_tasks,
workflow_vision_requests,
@@ -39,6 +40,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_workflow_data_suggestions",
["team_id"],
)
+ routers.projects.register(
+ r"workflow_sending_rules",
+ workflow_sending_rules.WorkflowSendingRulesViewSet,
+ "project_workflow_sending_rules",
+ ["team_id"],
+ )
routers.projects.register(
r"workflow_setup", workflow_setup.WorkflowSetupViewSet, "project_workflow_setup", ["team_id"]
)
diff --git a/products/workflows/backend/test/test_workflow_sending_rules.py b/products/workflows/backend/test/test_workflow_sending_rules.py
new file mode 100644
index 000000000000..b5459cc957f9
--- /dev/null
+++ b/products/workflows/backend/test/test_workflow_sending_rules.py
@@ -0,0 +1,53 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.organization import OrganizationMembership
+
+
+class TestWorkflowSendingRulesAPI(APIBaseTest):
+ def _url(self) -> str:
+ return f"/api/projects/{self.team.id}/workflow_sending_rules/current/"
+
+ def _set_level(self, level: OrganizationMembership.Level) -> None:
+ self.organization_membership.level = level
+ self.organization_membership.save()
+
+ def test_an_admin_sets_the_cap_and_reads_it_back(self) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+
+ response = self.client.patch(
+ self._url(),
+ {"marketing_frequency_cap_max_messages": 1, "marketing_frequency_cap_window_days": 2},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = self.client.get(self._url()).json()
+ assert body["marketing_frequency_cap_max_messages"] == 1
+ assert body["marketing_frequency_cap_window_days"] == 2
+
+ @parameterized.expand(
+ [
+ ("a member", OrganizationMembership.Level.MEMBER, {"capture_workflows_engagement_events": True}, 403),
+ ("half a cap", OrganizationMembership.Level.ADMIN, {"marketing_frequency_cap_max_messages": 3}, 400),
+ (
+ "another project",
+ OrganizationMembership.Level.ADMIN,
+ {
+ "expected_project_id": 999999,
+ "marketing_frequency_cap_max_messages": 1,
+ "marketing_frequency_cap_window_days": 2,
+ },
+ 400,
+ ),
+ ]
+ )
+ def test_an_update_is_rejected_for(self, _name, level, payload, expected_status) -> None:
+ self._set_level(level)
+
+ response = self.client.patch(self._url(), payload, format="json")
+
+ assert response.status_code == expected_status, response.json()
+ assert self.client.get(self._url()).json()["marketing_frequency_cap_max_messages"] is None
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index f979f7868a12..9d9762c86cab 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -2533,6 +2533,78 @@ export interface PeopleImportApi {
dropped_too_large: number
}
+/**
+ * * `off` - Off
+ * * `opt_out` - Opt Out
+ * * `opt_in` - Opt In
+ */
+export type EmailTrackingConsentModeEnumApi =
+ (typeof EmailTrackingConsentModeEnumApi)[keyof typeof EmailTrackingConsentModeEnumApi]
+
+export const EmailTrackingConsentModeEnumApi = {
+ Off: 'off',
+ OptOut: 'opt_out',
+ OptIn: 'opt_in',
+} as const
+
+export interface WorkflowSendingRulesApi {
+ /** The project these sending rules belong to. */
+ readonly project_id: number
+ /** Optional. The project_id from the rules being changed. The update is rejected when it does not match the current project, so a change never lands in a project the user did not look at. */
+ expected_project_id?: number
+ /**
+ * The most marketing messages one person gets in the window, across all workflows and broadcasts. Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. Transactional messages are never capped. The recommended cap is 1 message every 2 days.
+ * @minimum 1
+ * @maximum 1000
+ * @nullable
+ */
+ marketing_frequency_cap_max_messages?: number | null
+ /**
+ * The length of the rolling frequency cap window, in days. Set it together with marketing_frequency_cap_max_messages, or set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 30
+ * @nullable
+ */
+ marketing_frequency_cap_window_days?: number | null
+ /** Whether tracking opens and clicks on marketing email needs the recipient's consent. 'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' tracks only recipients who consented. Transactional email is never affected.
+ *
+ * * `off` - Off
+ * * `opt_out` - Opt Out
+ * * `opt_in` - Opt In */
+ email_tracking_consent_mode?: EmailTrackingConsentModeEnumApi
+ /** Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights and funnels. These events count toward the project's event usage. */
+ capture_workflows_engagement_events?: boolean
+}
+
+export interface PatchedWorkflowSendingRulesApi {
+ /** The project these sending rules belong to. */
+ readonly project_id?: number
+ /** Optional. The project_id from the rules being changed. The update is rejected when it does not match the current project, so a change never lands in a project the user did not look at. */
+ expected_project_id?: number
+ /**
+ * The most marketing messages one person gets in the window, across all workflows and broadcasts. Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. Transactional messages are never capped. The recommended cap is 1 message every 2 days.
+ * @minimum 1
+ * @maximum 1000
+ * @nullable
+ */
+ marketing_frequency_cap_max_messages?: number | null
+ /**
+ * The length of the rolling frequency cap window, in days. Set it together with marketing_frequency_cap_max_messages, or set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 30
+ * @nullable
+ */
+ marketing_frequency_cap_window_days?: number | null
+ /** Whether tracking opens and clicks on marketing email needs the recipient's consent. 'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' tracks only recipients who consented. Transactional email is never affected.
+ *
+ * * `off` - Off
+ * * `opt_out` - Opt Out
+ * * `opt_in` - Opt In */
+ email_tracking_consent_mode?: EmailTrackingConsentModeEnumApi
+ /** Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights and funnels. These events count toward the project's event usage. */
+ capture_workflows_engagement_events?: boolean
+}
+
/**
* * `channel` - Channel
* * `domain` - Domain
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 310ea8aec0ed..f00e99143535 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -70,6 +70,7 @@ import type {
PatchedHogFlowScheduleApi,
PatchedHogFlowTemplateApi,
PatchedHogFlowUpdateApi,
+ PatchedWorkflowSendingRulesApi,
PeopleImportApi,
PeopleImportCreateApi,
SendCalendarFlowApi,
@@ -80,6 +81,7 @@ import type {
WorkflowProposalCreateApi,
WorkflowProposalOutcomeApi,
WorkflowProposalRejectRequestApi,
+ WorkflowSendingRulesApi,
WorkflowSetupStatusApi,
WorkflowStatsRowApi,
} from './api.schemas'
@@ -1511,6 +1513,43 @@ export const workflowPeopleImportsCreate = async (
})
}
+export const getWorkflowSendingRulesRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/workflow_sending_rules/current/`
+}
+
+/**
+ * The project-wide rules every workflow and broadcast follows when it sends a message.
+ */
+export const workflowSendingRulesRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<WorkflowSendingRulesApi> => {
+ return apiMutator<WorkflowSendingRulesApi>(getWorkflowSendingRulesRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWorkflowSendingRulesPartialUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/workflow_sending_rules/current/`
+}
+
+/**
+ * The project-wide rules every workflow and broadcast follows when it sends a message.
+ */
+export const workflowSendingRulesPartialUpdate = async (
+ projectId: string,
+ patchedWorkflowSendingRulesApi?: NonReadonly<PatchedWorkflowSendingRulesApi>,
+ options?: RequestInit
+): Promise<WorkflowSendingRulesApi> => {
+ return apiMutator<WorkflowSendingRulesApi>(getWorkflowSendingRulesPartialUpdateUrl(projectId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedWorkflowSendingRulesApi),
+ })
+}
+
export const getWorkflowSetupStatusUrl = (projectId: string) => {
return `/api/projects/${projectId}/workflow_setup/status/`
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index f8907c2ebf73..c4566eff14b5 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -3307,3 +3307,48 @@ export const WorkflowPeopleImportsCreateBody = /* @__PURE__ */ zod.object({
'One object per person. Each needs \"email\". An optional \"distinct_id\" picks the person to update or create, and an \"id\" column counts as the distinct_id when there is no \"distinct_id\" column. Without either, the row updates the person with that email, or creates one keyed by the email. Every other key is set as a person property.'
),
})
+
+/**
+ * The project-wide rules every workflow and broadcast follows when it sends a message.
+ */
+export const workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapMaxMessagesMax = 1000
+
+export const workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapWindowDaysMax = 30
+
+export const WorkflowSendingRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ expected_project_id: zod
+ .number()
+ .optional()
+ .describe(
+ 'Optional. The project_id from the rules being changed. The update is rejected when it does not match the current project, so a change never lands in a project the user did not look at.'
+ ),
+ marketing_frequency_cap_max_messages: zod
+ .number()
+ .min(1)
+ .max(workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapMaxMessagesMax)
+ .nullish()
+ .describe(
+ 'The most marketing messages one person gets in the window, across all workflows and broadcasts. Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. Transactional messages are never capped. The recommended cap is 1 message every 2 days.'
+ ),
+ marketing_frequency_cap_window_days: zod
+ .number()
+ .min(1)
+ .max(workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapWindowDaysMax)
+ .nullish()
+ .describe(
+ 'The length of the rolling frequency cap window, in days. Set it together with marketing_frequency_cap_max_messages, or set both to null to turn the cap off.'
+ ),
+ email_tracking_consent_mode: zod
+ .enum(['off', 'opt_out', 'opt_in'])
+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')
+ .optional()
+ .describe(
+ "Whether tracking opens and clicks on marketing email needs the recipient's consent. 'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' tracks only recipients who consented. Transactional email is never affected.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"
+ ),
+ capture_workflows_engagement_events: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights and funnels. These events count toward the project's event usage."
+ ),
+})
diff --git a/products/workflows/mcp/apps/WorkflowSendingRulesView.tsx b/products/workflows/mcp/apps/WorkflowSendingRulesView.tsx
new file mode 100644
index 000000000000..e0e0a12a753f
--- /dev/null
+++ b/products/workflows/mcp/apps/WorkflowSendingRulesView.tsx
@@ -0,0 +1,104 @@
+import { type ReactElement, type ReactNode } from 'react'
+
+import { Button, Card, CardContent, Switch } from '@posthog/quill'
+
+export interface WorkflowSendingRulesData {
+ project_id: number
+ marketing_frequency_cap_max_messages: number | null
+ marketing_frequency_cap_window_days: number | null
+ email_tracking_consent_mode: 'off' | 'opt_out' | 'opt_in'
+ capture_workflows_engagement_events: boolean
+}
+
+export interface WorkflowSendingRulesViewProps {
+ data: WorkflowSendingRulesData
+ saving?: boolean
+ error?: string | null
+ onApplyRecommendedCap?: () => void
+ onEngagementEventsChange?: (enabled: boolean) => void
+}
+
+const CONSENT_LABELS: Record<WorkflowSendingRulesData['email_tracking_consent_mode'], string> = {
+ off: 'No consent enforcement',
+ opt_out: 'Track unless the recipient objected',
+ opt_in: 'Track only recipients who consented',
+}
+
+function plural(count: number, noun: string): string {
+ return `${count} ${noun}${count === 1 ? '' : 's'}`
+}
+
+function Rule({
+ title,
+ description,
+ children,
+}: {
+ title: string
+ description: string
+ children: ReactNode
+}): ReactElement {
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="font-medium">{title}</span>
+ <span className="text-sm text-muted-foreground">{description}</span>
+ </div>
+ {children}
+ </div>
+ )
+}
+
+export function WorkflowSendingRulesView({
+ data,
+ saving = false,
+ error,
+ onApplyRecommendedCap,
+ onEngagementEventsChange,
+}: WorkflowSendingRulesViewProps): ReactElement {
+ const maxMessages = data.marketing_frequency_cap_max_messages
+ const windowDays = data.marketing_frequency_cap_window_days
+ const capDescription =
+ maxMessages !== null && windowDays !== null
+ ? `At most ${plural(maxMessages, 'marketing email')} every ${plural(windowDays, 'day')} per person.`
+ : null
+
+ return (
+ <div className="p-4">
+ <Card>
+ <CardContent className="flex flex-col gap-4">
+ <div className="flex flex-col">
+ <span className="font-semibold">Sending rules</span>
+ <span className="text-sm text-muted-foreground">
+ Every workflow and broadcast in this project follows these rules.
+ </span>
+ </div>
+ <Rule
+ title="Frequency cap"
+ description={capDescription ?? 'No cap. The recommended cap is 1 marketing email every 2 days.'}
+ >
+ {capDescription === null && onApplyRecommendedCap ? (
+ <Button size="sm" variant="primary" disabled={saving} onClick={onApplyRecommendedCap}>
+ Apply recommended cap
+ </Button>
+ ) : null}
+ </Rule>
+ <Rule title="Email tracking consent" description={CONSENT_LABELS[data.email_tracking_consent_mode]}>
+ {null}
+ </Rule>
+ <Rule
+ title="Engagement events"
+ description="Sends, opens, clicks and bounces as PostHog events. They count toward event usage."
+ >
+ <Switch
+ checked={data.capture_workflows_engagement_events}
+ disabled={saving || !onEngagementEventsChange}
+ onCheckedChange={(checked) => onEngagementEventsChange?.(checked)}
+ aria-label="Capture email engagement events"
+ />
+ </Rule>
+ {error ? <p className="m-0 text-sm text-danger">{error}</p> : null}
+ </CardContent>
+ </Card>
+ </div>
+ )
+}
diff --git a/products/workflows/mcp/apps/Workflows.stories.tsx b/products/workflows/mcp/apps/Workflows.stories.tsx
index 4198e0146a51..6ca1428f2382 100644
--- a/products/workflows/mcp/apps/Workflows.stories.tsx
+++ b/products/workflows/mcp/apps/Workflows.stories.tsx
@@ -6,6 +6,7 @@ import {
WorkflowDataSuggestionsView,
type WorkflowDataSuggestionsData,
WorkflowListView,
+ WorkflowSendingRulesView,
WorkflowSetupStatusView,
type WorkflowSetupStatusData,
type WorkflowSetupStep,
@@ -148,6 +149,38 @@ export const DataSuggestionsBuilt: Story = {
name: 'Data suggestions after a build',
}
+export const SendingRulesNoCap: Story = {
+ render: () => (
+ <WorkflowSendingRulesView
+ data={{
+ project_id: 1,
+ marketing_frequency_cap_max_messages: null,
+ marketing_frequency_cap_window_days: null,
+ email_tracking_consent_mode: 'off',
+ capture_workflows_engagement_events: false,
+ }}
+ onApplyRecommendedCap={() => {}}
+ onEngagementEventsChange={() => {}}
+ />
+ ),
+}
+
+export const SendingRulesWithCap: Story = {
+ render: () => (
+ <WorkflowSendingRulesView
+ data={{
+ project_id: 1,
+ marketing_frequency_cap_max_messages: 1,
+ marketing_frequency_cap_window_days: 2,
+ email_tracking_consent_mode: 'opt_out',
+ capture_workflows_engagement_events: true,
+ }}
+ onApplyRecommendedCap={() => {}}
+ onEngagementEventsChange={() => {}}
+ />
+ ),
+}
+
const setupStep = (key: string, done: boolean, title: string, nextStep: string, path: string): WorkflowSetupStep => ({
key,
done,
diff --git a/products/workflows/mcp/apps/index.ts b/products/workflows/mcp/apps/index.ts
index b2442e114149..de54eff308ca 100644
--- a/products/workflows/mcp/apps/index.ts
+++ b/products/workflows/mcp/apps/index.ts
@@ -10,6 +10,11 @@ export {
type WorkflowDataSuggestionsViewProps,
} from './WorkflowDataSuggestionsView'
export { WorkflowDataSuggestionBuildView } from './WorkflowDataSuggestionBuildView'
+export {
+ WorkflowSendingRulesView,
+ type WorkflowSendingRulesData,
+ type WorkflowSendingRulesViewProps,
+} from './WorkflowSendingRulesView'
export {
WorkflowSetupStatusView,
type WorkflowSetupStatusData,
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 299e2eeaac80..b4fd969b4f5a 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -12,6 +12,17 @@ ui_apps:
workflow-list:
type: list
detail_tool: workflows-get
+ workflow-sending-rules:
+ type: custom
+ app_name: PostHog Sending Rules
+ description:
+ Sending rules for the project, with a button to apply the recommended frequency cap and a switch for
+ engagement events.
+ render_ui:
+ component_import: products/workflows/mcp/apps
+ view_component: WorkflowSendingRulesView
+ view_prop: data
+ data_type: WorkflowSendingRulesData
workflow-setup-status:
type: detail
view_prop: data
@@ -450,6 +461,30 @@ tools:
in-flight. A 409 means a draft is already open — publish or discard it, or pass overwrite=true to replace
it. Note what a rollback can't undo: runs that already moved on while the newer version was live keep their
positions.
+ workflows-sending-rules-get:
+ operation: workflow_sending_rules_retrieve
+ enabled: true
+ title: Get sending rules
+ description: >
+ The project-wide rules every workflow and broadcast follows when it sends: the marketing frequency cap,
+ email tracking consent, and whether email engagement events are captured. Null cap fields mean no cap.
+ ui_app: workflow-sending-rules
+ feature_flag: workflows-mcp-onboarding
+ workflows-sending-rules-update:
+ operation: workflow_sending_rules_partial_update
+ enabled: true
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update sending rules
+ description: >
+ Change the project-wide sending rules. Only the fields you send change. When a project has no frequency cap
+ yet, recommend 1 marketing message every 2 days (max_messages 1, window_days 2) and turning on engagement
+ events; leave tracking consent as it is unless the user asks. Confirm the values with the user before
+ calling. Needs a project admin. Set both cap fields together, or both to null to turn the cap off.
+ ui_app: workflow-sending-rules
+ feature_flag: workflows-mcp-onboarding
workflows-setup-status:
operation: workflow_setup_status
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 211fcde8732d..042a3bf1e7b3 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -15270,6 +15270,36 @@
"readOnlyHint": false
}
},
+ "workflows-sending-rules-get": {
+ "description": "The project-wide rules every workflow and broadcast follows when it sends: the marketing frequency cap, email tracking consent, and whether email engagement events are captured. Null cap fields mean no cap.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get sending rules",
+ "title": "Get sending rules",
+ "required_scopes": ["project:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "workflows-mcp-onboarding"
+ },
+ "workflows-sending-rules-update": {
+ "description": "Change the project-wide sending rules. Only the fields you send change. When a project has no frequency cap yet, recommend 1 marketing message every 2 days (max_messages 1, window_days 2) and turning on engagement events; leave tracking consent as it is unless the user asks. Confirm the values with the user before calling. Needs a project admin. Set both cap fields together, or both to null to turn the cap off.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Update sending rules",
+ "title": "Update sending rules",
+ "required_scopes": ["project:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "workflows-mcp-onboarding"
+ },
"workflows-setup-status": {
"description": "Which messaging setup steps the project has done: email channel, verified sending domain, opt-out categories, frequency cap, email template and first workflow. Call it first when a user asks to set up workflows or messaging, or asks to build an email, SMS or push workflow in a project that may not send yet. For each open step, tell the user what it needs and share its app_url, since channel and domain setup happen in the app. An email workflow can be drafted before ready_to_send_email is true, but it cannot send until it is. Automations that only post to Slack or call webhooks need none of these steps. When data_suggestions_available is true, offer workflows-data-suggestions-list once setup is done.",
"category": "Workflows",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index bf7caae5dfa4..344d39a03826 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -16030,6 +16030,36 @@
"readOnlyHint": false
}
},
+ "workflows-sending-rules-get": {
+ "description": "The project-wide rules every workflow and broadcast follows when it sends: the marketing frequency cap, email tracking consent, and whether email engagement events are captured. Null cap fields mean no cap.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get sending rules",
+ "title": "Get sending rules",
+ "required_scopes": ["project:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "workflows-mcp-onboarding"
+ },
+ "workflows-sending-rules-update": {
+ "description": "Change the project-wide sending rules. Only the fields you send change. When a project has no frequency cap yet, recommend 1 marketing message every 2 days (max_messages 1, window_days 2) and turning on engagement events; leave tracking consent as it is unless the user asks. Confirm the values with the user before calling. Needs a project admin. Set both cap fields together, or both to null to turn the cap off.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Update sending rules",
+ "title": "Update sending rules",
+ "required_scopes": ["project:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "workflows-mcp-onboarding"
+ },
"workflows-setup-status": {
"description": "Which messaging setup steps the project has done: email channel, verified sending domain, opt-out categories, frequency cap, email template and first workflow. Call it first when a user asks to set up workflows or messaging, or asks to build an email, SMS or push workflow in a project that may not send yet. For each open step, tell the user what it needs and share its app_url, since channel and domain setup happen in the app. An email workflow can be drafted before ready_to_send_email is true, but it cannot send until it is. Automations that only post to Slack or call webhooks need none of these steps. When data_suggestions_available is true, offer workflows-data-suggestions-list once setup is done.",
"category": "Workflows",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 67977571ab6e..d8514a7b2c44 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -89078,6 +89078,35 @@ export namespace Schemas {
error_code?: string | null;
}
+ export interface PatchedWorkflowSendingRules {
+ /** The project these sending rules belong to. */
+ readonly project_id?: number;
+ /** Optional. The project_id from the rules being changed. The update is rejected when it does not match the current project, so a change never lands in a project the user did not look at. */
+ expected_project_id?: number;
+ /**
+ * The most marketing messages one person gets in the window, across all workflows and broadcasts. Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. Transactional messages are never capped. The recommended cap is 1 message every 2 days.
+ * @minimum 1
+ * @maximum 1000
+ * @nullable
+ */
+ marketing_frequency_cap_max_messages?: number | null;
+ /**
+ * The length of the rolling frequency cap window, in days. Set it together with marketing_frequency_cap_max_messages, or set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 30
+ * @nullable
+ */
+ marketing_frequency_cap_window_days?: number | null;
+ /** Whether tracking opens and clicks on marketing email needs the recipient's consent. 'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' tracks only recipients who consented. Transactional email is never affected.
+ *
+ * * `off` - Off
+ * * `opt_out` - Opt Out
+ * * `opt_in` - Opt In */
+ email_tracking_consent_mode?: EmailTrackingConsentModeEnum;
+ /** Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights and funnels. These events count toward the project's event usage. */
+ capture_workflows_engagement_events?: boolean;
+ }
+
export interface PathCleaningPreviewExample {
/** A real sampled path before the suggested rules are applied. */
before: string;
@@ -117246,6 +117275,35 @@ export namespace Schemas {
estimated_cost_usd: number | null;
}
+ export interface WorkflowSendingRules {
+ /** The project these sending rules belong to. */
+ readonly project_id: number;
+ /** Optional. The project_id from the rules being changed. The update is rejected when it does not match the current project, so a change never lands in a project the user did not look at. */
+ expected_project_id?: number;
+ /**
+ * The most marketing messages one person gets in the window, across all workflows and broadcasts. Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. Transactional messages are never capped. The recommended cap is 1 message every 2 days.
+ * @minimum 1
+ * @maximum 1000
+ * @nullable
+ */
+ marketing_frequency_cap_max_messages?: number | null;
+ /**
+ * The length of the rolling frequency cap window, in days. Set it together with marketing_frequency_cap_max_messages, or set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 30
+ * @nullable
+ */
+ marketing_frequency_cap_window_days?: number | null;
+ /** Whether tracking opens and clicks on marketing email needs the recipient's consent. 'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' tracks only recipients who consented. Transactional email is never affected.
+ *
+ * * `off` - Off
+ * * `opt_out` - Opt Out
+ * * `opt_in` - Opt In */
+ email_tracking_consent_mode?: EmailTrackingConsentModeEnum;
+ /** Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights and funnels. These events count toward the project's event usage. */
+ capture_workflows_engagement_events?: boolean;
+ }
+
export interface WorkflowSetupStep {
/** Which setup step this is. The steps come in the order the setup wizard asks for them.
*
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 96c210293a85..e4797771a5a1 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 26 enabled ops
+ * PostHog API - MCP 28 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1353,6 +1353,70 @@ export const WorkflowDataSuggestionsGenerateBody = () => zod.object({
.describe('Make new suggestions even when the cached ones are still valid.'),
})
+/**
+ * The project-wide rules every workflow and broadcast follows when it sends a message.
+ */
+export const WorkflowSendingRulesRetrieveParams = () => zod.object({
+ 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\/."
+ ),
+})
+
+/**
+ * The project-wide rules every workflow and broadcast follows when it sends a message.
+ */
+export const WorkflowSendingRulesPartialUpdateParams = () => zod.object({
+ 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 workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapMaxMessagesMax = 1000
+
+export const workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapWindowDaysMax = 30
+
+export const WorkflowSendingRulesPartialUpdateBody = () => zod.object({
+ expected_project_id: zod
+ .number()
+ .optional()
+ .describe(
+ 'Optional. The project_id from the rules being changed. The update is rejected when it does not match the current project, so a change never lands in a project the user did not look at.'
+ ),
+ marketing_frequency_cap_max_messages: zod
+ .number()
+ .min(1)
+ .max(workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapMaxMessagesMax)
+ .nullish()
+ .describe(
+ 'The most marketing messages one person gets in the window, across all workflows and broadcasts. Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. Transactional messages are never capped. The recommended cap is 1 message every 2 days.'
+ ),
+ marketing_frequency_cap_window_days: zod
+ .number()
+ .min(1)
+ .max(workflowSendingRulesPartialUpdateBodyMarketingFrequencyCapWindowDaysMax)
+ .nullish()
+ .describe(
+ 'The length of the rolling frequency cap window, in days. Set it together with marketing_frequency_cap_max_messages, or set both to null to turn the cap off.'
+ ),
+ email_tracking_consent_mode: zod
+ .enum(['off', 'opt_out', 'opt_in'])
+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')
+ .optional()
+ .describe(
+ "Whether tracking opens and clicks on marketing email needs the recipient's consent. 'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' tracks only recipients who consented. Transactional email is never affected.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"
+ ),
+ capture_workflows_engagement_events: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights and funnels. These events count toward the project's event usage."
+ ),
+})
+
/**
* Whether a project is set up to send messages from workflows.
*/
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index 24775a723193..a8148ffeccfc 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -32,6 +32,7 @@ export const VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI = 'ui://posthog/visual-review-
export const WORKFLOW_RESOURCE_URI = 'ui://posthog/workflow.html'
export const WORKFLOW_DATA_SUGGESTIONS_RESOURCE_URI = 'ui://posthog/workflow-data-suggestions.html'
export const WORKFLOW_LIST_RESOURCE_URI = 'ui://posthog/workflow-list.html'
+export const WORKFLOW_SENDING_RULES_RESOURCE_URI = 'ui://posthog/workflow-sending-rules.html'
export const WORKFLOW_SETUP_STATUS_RESOURCE_URI = 'ui://posthog/workflow-setup-status.html'
export type UiAppKey =
@@ -67,6 +68,7 @@ export type UiAppKey =
| 'workflow'
| 'workflow-data-suggestions'
| 'workflow-list'
+ | 'workflow-sending-rules'
| 'workflow-setup-status'
export const URI_MAP: Record<UiAppKey, string> = {
@@ -102,6 +104,7 @@ export const URI_MAP: Record<UiAppKey, string> = {
workflow: WORKFLOW_RESOURCE_URI,
'workflow-data-suggestions': WORKFLOW_DATA_SUGGESTIONS_RESOURCE_URI,
'workflow-list': WORKFLOW_LIST_RESOURCE_URI,
+ 'workflow-sending-rules': WORKFLOW_SENDING_RULES_RESOURCE_URI,
'workflow-setup-status': WORKFLOW_SETUP_STATUS_RESOURCE_URI,
}
@@ -138,6 +141,7 @@ export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [
'vision-observation-list',
'workflow',
'workflow-list',
+ 'workflow-sending-rules',
'workflow-setup-status',
]
@@ -344,6 +348,13 @@ export const UI_APPS: Array<{
description: 'Workflow List view',
appDir: 'generated/workflow-list',
},
+ {
+ name: 'PostHog Sending Rules',
+ uri: WORKFLOW_SENDING_RULES_RESOURCE_URI,
+ description:
+ 'Sending rules for the project, with a button to apply the recommended frequency cap and a switch for engagement events.',
+ appDir: 'workflow-sending-rules',
+ },
{
name: 'PostHog Messaging Setup',
uri: WORKFLOW_SETUP_STATUS_RESOURCE_URI,
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index dd9693519866..bc840ab6ba28 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -618,6 +618,64 @@ const workflowsRestoreRevision = (): ToolBase<ReturnType<typeof WorkflowsRestore
},
})
+const WorkflowsSendingRulesGetSchema = () => z.object({})
+
+const workflowsSendingRulesGet = (): ToolBase<
+ ReturnType<typeof WorkflowsSendingRulesGetSchema>,
+ Schemas.WorkflowSendingRules
+> =>
+ withUiApp('workflow-sending-rules', {
+ name: 'workflows-sending-rules-get',
+ schema: WorkflowsSendingRulesGetSchema(),
+ handler: async (context: Context, _params: z.infer<ReturnType<typeof WorkflowsSendingRulesGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.WorkflowSendingRules>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/workflow_sending_rules/current/`,
+ })
+ return result
+ },
+ })
+
+const WorkflowsSendingRulesUpdateSchema = () => {
+ const WorkflowSendingRulesPartialUpdateBody = orvalSchemas.WorkflowSendingRulesPartialUpdateBody()
+ return WorkflowSendingRulesPartialUpdateBody
+}
+
+const workflowsSendingRulesUpdate = (): ToolBase<
+ ReturnType<typeof WorkflowsSendingRulesUpdateSchema>,
+ Schemas.WorkflowSendingRules
+> =>
+ withUiApp('workflow-sending-rules', {
+ name: 'workflows-sending-rules-update',
+ schema: WorkflowsSendingRulesUpdateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsSendingRulesUpdateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.expected_project_id !== undefined) {
+ body['expected_project_id'] = params.expected_project_id
+ }
+ if (params.marketing_frequency_cap_max_messages !== undefined) {
+ body['marketing_frequency_cap_max_messages'] = params.marketing_frequency_cap_max_messages
+ }
+ if (params.marketing_frequency_cap_window_days !== undefined) {
+ body['marketing_frequency_cap_window_days'] = params.marketing_frequency_cap_window_days
+ }
+ if (params.email_tracking_consent_mode !== undefined) {
+ body['email_tracking_consent_mode'] = params.email_tracking_consent_mode
+ }
+ if (params.capture_workflows_engagement_events !== undefined) {
+ body['capture_workflows_engagement_events'] = params.capture_workflows_engagement_events
+ }
+ const result = await context.api.request<Schemas.WorkflowSendingRules>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/workflow_sending_rules/current/`,
+ body,
+ })
+ return result
+ },
+ })
+
const WorkflowsSetupStatusSchema = () => z.object({})
const workflowsSetupStatus = (): ToolBase<ReturnType<typeof WorkflowsSetupStatusSchema>, Schemas.WorkflowSetupStatus> =>
@@ -874,6 +932,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'workflows-patch-graph': workflowsPatchGraph,
'workflows-publish': workflowsPublish,
'workflows-restore-revision': workflowsRestoreRevision,
+ 'workflows-sending-rules-get': workflowsSendingRulesGet,
+ 'workflows-sending-rules-update': workflowsSendingRulesUpdate,
'workflows-setup-status': workflowsSetupStatus,
'workflows-stats': workflowsStats,
'workflows-suggest': workflowsSuggest,
diff --git a/services/mcp/src/ui-apps/apps/workflow-sending-rules.tsx b/services/mcp/src/ui-apps/apps/workflow-sending-rules.tsx
new file mode 100644
index 000000000000..bb5e474d84da
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/workflow-sending-rules.tsx
@@ -0,0 +1,96 @@
+import '../styles/tailwind.css'
+
+import type { App } from '@modelcontextprotocol/ext-apps'
+import { useCallback, useState } from 'react'
+import { createRoot } from 'react-dom/client'
+
+import { type WorkflowSendingRulesData, WorkflowSendingRulesView } from 'products/workflows/mcp/apps'
+
+import { AppWrapper } from '../components/AppWrapper'
+
+const SAVE_FAILED = "We couldn't save the sending rules. Only project admins can change them."
+const FALLBACK_FAILED = "We couldn't save the sending rules or ask in the chat. Try again from the chat."
+
+function WorkflowSendingRulesApp(): JSX.Element {
+ return (
+ <AppWrapper<WorkflowSendingRulesData> appName="PostHog Sending Rules">
+ {({ data, app }) => (data ? <WorkflowSendingRulesContent initial={data} app={app} /> : null)}
+ </AppWrapper>
+ )
+}
+
+function WorkflowSendingRulesContent({
+ initial,
+ app,
+}: {
+ initial: WorkflowSendingRulesData
+ app: App | null
+}): JSX.Element {
+ const [data, setData] = useState(initial)
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+
+ const save = useCallback(
+ async (changes: Partial<WorkflowSendingRulesData>, chatRequest: string): Promise<void> => {
+ if (!app) {
+ return
+ }
+ setSaving(true)
+ setError(null)
+ try {
+ const result = await app.callServerTool({
+ name: 'workflows-sending-rules-update',
+ // Pins the save to the project this card shows, in case the chat switched projects since.
+ arguments: { ...changes, expected_project_id: data.project_id },
+ })
+ const saved = result.structuredContent as unknown as WorkflowSendingRulesData | undefined
+ if (result.isError || !saved) {
+ setError(SAVE_FAILED)
+ } else {
+ setData(saved)
+ }
+ } catch {
+ // The host cannot call tools from an app, so the agent makes the change from the chat instead.
+ try {
+ await app.sendMessage({ role: 'user', content: [{ type: 'text', text: chatRequest }] })
+ } catch {
+ setError(FALLBACK_FAILED)
+ }
+ } finally {
+ setSaving(false)
+ }
+ },
+ [app, data.project_id]
+ )
+
+ return (
+ <WorkflowSendingRulesView
+ data={data}
+ saving={saving}
+ error={error}
+ onApplyRecommendedCap={
+ app
+ ? () =>
+ void save(
+ { marketing_frequency_cap_max_messages: 1, marketing_frequency_cap_window_days: 2 },
+ 'Set the frequency cap to 1 marketing email every 2 days with workflows-sending-rules-update.'
+ )
+ : undefined
+ }
+ onEngagementEventsChange={
+ app
+ ? (enabled) =>
+ void save(
+ { capture_workflows_engagement_events: enabled },
+ `Turn ${enabled ? 'on' : 'off'} email engagement events with workflows-sending-rules-update.`
+ )
+ : undefined
+ }
+ />
+ )
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<WorkflowSendingRulesApp />)
+}
diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
index 7bd805ad62df..ea1692786b4c 100644
--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
@@ -50,11 +50,13 @@ import { TraceSpanListView, TraceSpanView, type TraceSpanData, type TraceSpanLis
import {
EmailTemplateView,
WorkflowListView,
+ WorkflowSendingRulesView,
WorkflowSetupStatusView,
WorkflowView,
type EmailTemplateData,
type WorkflowData,
type WorkflowListData,
+ type WorkflowSendingRulesData,
type WorkflowSetupStatusData,
} from 'products/workflows/mcp/apps'
@@ -448,6 +450,7 @@ export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchPro
),
workflow: ({ data }) => <WorkflowView workflow={data as WorkflowData} />,
'workflow-list': ({ data, app }) => <WorkflowListContent data={data as WorkflowListData} app={app} />,
+ 'workflow-sending-rules': ({ data }) => <WorkflowSendingRulesView data={data as WorkflowSendingRulesData} />,
'workflow-setup-status': ({ data, openLink }) => (
<WorkflowSetupStatusView data={data as WorkflowSetupStatusData} openLink={openLink} />
),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-sending-rules-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-sending-rules-get.json
new file mode 100644
index 000000000000..7b7ea9186078
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-sending-rules-get.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {},
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-sending-rules-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-sending-rules-update.json
new file mode 100644
index 000000000000..f8caed8f4a8d
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-sending-rules-update.json
@@ -0,0 +1,45 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "capture_workflows_engagement_events": {
+ "description": "Capture email sends, opens, clicks and bounces as PostHog events, so they can be used in insights and funnels. These events count toward the project's event usage.",
+ "type": "boolean"
+ },
+ "email_tracking_consent_mode": {
+ "description": "Whether tracking opens and clicks on marketing email needs the recipient's consent. 'off' follows each email step's own setting, 'opt_out' tracks unless the recipient objected, and 'opt_in' tracks only recipients who consented. Transactional email is never affected.\n\n* `off` - Off\n* `opt_out` - Opt Out\n* `opt_in` - Opt In",
+ "enum": ["off", "opt_out", "opt_in"],
+ "type": "string"
+ },
+ "expected_project_id": {
+ "description": "Optional. The project_id from the rules being changed. The update is rejected when it does not match the current project, so a change never lands in a project the user did not look at.",
+ "type": "number"
+ },
+ "marketing_frequency_cap_max_messages": {
+ "anyOf": [
+ {
+ "maximum": 1000,
+ "minimum": 1,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The most marketing messages one person gets in the window, across all workflows and broadcasts. Set it together with marketing_frequency_cap_window_days, or set both to null to turn the cap off. Transactional messages are never capped. The recommended cap is 1 message every 2 days."
+ },
+ "marketing_frequency_cap_window_days": {
+ "anyOf": [
+ {
+ "maximum": 30,
+ "minimum": 1,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The length of the rolling frequency cap window, in days. Set it together with marketing_frequency_cap_max_messages, or set both to null to turn the cap off."
+ }
+ },
+ "type": "object"
+}