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(messaging): manage message categories with api keys and mcp (#123314)

Harley Alexander4e27f6dbcb75
diff --git a/products/messaging/backend/presentation/views/message_categories.py b/products/messaging/backend/presentation/views/message_categories.py
index a0d1e54e6c9c..80b4e77b226d 100644
--- a/products/messaging/backend/presentation/views/message_categories.py
+++ b/products/messaging/backend/presentation/views/message_categories.py
@@ -41,18 +41,55 @@ from products.messaging.backend.facade.customerio import (
class MessageCategorySerializer(serializers.Serializer):
- id = serializers.UUIDField(read_only=True)
- key = serializers.CharField(max_length=64)
- name = serializers.CharField(max_length=128)
- description = serializers.CharField(allow_blank=True, required=False, style={"base_template": "textarea.html"})
+ id = serializers.UUIDField(
+ read_only=True,
+ help_text=(
+ "Category ID. Workflow message steps take it as `message_category_id`, and the opt-out of messages "
+ "step takes it as its `category_id` input."
+ ),
+ )
+ key = serializers.CharField(
+ max_length=64,
+ help_text=(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. "
+ "Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ )
+ name = serializers.CharField(max_length=128, help_text="Display name of the category, shown in the PostHog app.")
+ description = serializers.CharField(
+ allow_blank=True,
+ required=False,
+ style={"base_template": "textarea.html"},
+ help_text="Internal notes about which messages belong to this category. Recipients don't see it.",
+ )
public_description = serializers.CharField(
- allow_blank=True, required=False, style={"base_template": "textarea.html"}
+ allow_blank=True,
+ required=False,
+ style={"base_template": "textarea.html"},
+ help_text="Description that recipients see next to the category on the preferences page.",
+ )
+ category_type = serializers.ChoiceField(
+ choices=MESSAGE_CATEGORY_TYPE_CHOICES,
+ required=False,
+ help_text=(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. "
+ "`transactional`: for messages a recipient must get, such as receipts or password resets. "
+ "Sends ignore opt-outs, and the category doesn't appear on the preferences page. "
+ "Set `message_category_type` on a workflow message step to the type of its category."
+ ),
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the category was created.")
+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the category was last changed.")
+ created_by = serializers.IntegerField(
+ source="created_by_id",
+ read_only=True,
+ allow_null=True,
+ help_text="ID of the user who created the category. Null when the user no longer exists.",
+ )
+ deleted = serializers.BooleanField(
+ required=False,
+ help_text="Set to true to archive the category. Archived categories don't appear in lists.",
)
- category_type = serializers.ChoiceField(choices=MESSAGE_CATEGORY_TYPE_CHOICES, required=False)
- created_at = serializers.DateTimeField(read_only=True)
- updated_at = serializers.DateTimeField(read_only=True)
- created_by = serializers.IntegerField(source="created_by_id", read_only=True, allow_null=True)
- deleted = serializers.BooleanField(required=False)
def validate(self, data):
if self.instance is None:
@@ -105,12 +142,19 @@ class MessageCategoryViewSet(
ForbidDestroyModel,
viewsets.ModelViewSet,
):
- scope_object = "INTERNAL"
+ scope_object = "hog_flow"
+ # Categories are team-wide and belong to no single workflow. Without this, a member with access
+ # to one workflow could read and rewrite every category, because the permission falls back to
+ # "has access to any hog_flow object".
+ requires_resource_level_access = True
+ # The default read and write actions cover the category CRUD. The Customer.io actions below are
+ # in neither list, so API keys can't call them and they stay session-only: they store and
+ # remove third-party credentials.
serializer_class = MessageCategorySerializer
def _category(self) -> MessageCategoryRow:
- # INTERNAL scope has no object-level access rules, so a team-scoped lookup is the whole check.
+ # Categories have no object-level access rules, so a team-scoped lookup is the whole check.
try:
return get_category(self.team_id, self.kwargs["pk"])
except MessageCategoryMissing:
diff --git a/products/messaging/backend/tests/api/test_message_categories.py b/products/messaging/backend/tests/api/test_message_categories.py
index 6252bd06a72b..b00f96f40713 100644
--- a/products/messaging/backend/tests/api/test_message_categories.py
+++ b/products/messaging/backend/tests/api/test_message_categories.py
@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, patch
from django.core.files.uploadedfile import SimpleUploadedFile
+from parameterized import parameterized
from rest_framework import status
from posthog.models import Team
@@ -279,6 +280,41 @@ class TestMessageCategoryAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+class TestMessageCategoryPersonalAPIKeyAccess(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("list_with_read_scope", ["hog_flow:read"], "get", "", status.HTTP_200_OK),
+ ("create_with_write_scope", ["hog_flow:write"], "post", "", status.HTTP_201_CREATED),
+ ("update_with_write_scope", ["hog_flow:write"], "patch", "{id}/", status.HTTP_200_OK),
+ ("create_with_read_scope_forbidden", ["hog_flow:read"], "post", "", status.HTTP_403_FORBIDDEN),
+ ("update_with_read_scope_forbidden", ["hog_flow:read"], "patch", "{id}/", status.HTTP_403_FORBIDDEN),
+ ("list_with_unrelated_scope_forbidden", ["insight:read"], "get", "", status.HTTP_403_FORBIDDEN),
+ (
+ "customerio_credentials_stay_session_only",
+ ["hog_flow:write"],
+ "post",
+ "save_track_config/",
+ status.HTTP_403_FORBIDDEN,
+ ),
+ ]
+ )
+ def test_personal_api_key_scope_enforcement(self, _name, scopes, method, path, expected_status):
+ category = MessageCategory.objects.create(team=self.team, name="Newsletter", key="newsletter")
+ api_key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ url = f"/api/projects/{self.team.id}/messaging_categories/{path.format(id=category.id)}"
+ data = {"name": "Product updates", "key": "product_updates"} if method == "post" else {"name": "Renamed"}
+
+ response = getattr(self.client, method)(url, data=data if method != "get" else None, format="json")
+
+ assert response.status_code == expected_status, response.json()
+ if expected_status == status.HTTP_201_CREATED:
+ created = MessageCategory.objects.get(id=response.json()["id"])
+ assert (created.team_id, created.created_by_id) == (self.team.id, self.user.id)
+
+
class TestOptOutSyncConfigAPI(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index 5381b7626d80..1926edc940eb 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -19,18 +19,37 @@ export const MessageCategoryTypeEnumApi = {
} as const
export interface MessageCategoryApi {
+ /** Category ID. Workflow message steps take it as `message_category_id`, and the opt-out of messages step takes it as its `category_id` input. */
readonly id: string
- /** @maxLength 64 */
+ /**
+ * Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation.
+ * @maxLength 64
+ */
key: string
- /** @maxLength 128 */
+ /**
+ * Display name of the category, shown in the PostHog app.
+ * @maxLength 128
+ */
name: string
+ /** Internal notes about which messages belong to this category. Recipients don't see it. */
description?: string
+ /** Description that recipients see next to the category on the preferences page. */
public_description?: string
+ /** `marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.
+ *
+ * * `marketing` - Marketing
+ * * `transactional` - Transactional */
category_type?: MessageCategoryTypeEnumApi
+ /** When the category was created. */
readonly created_at: string
+ /** When the category was last changed. */
readonly updated_at: string
- /** @nullable */
+ /**
+ * ID of the user who created the category. Null when the user no longer exists.
+ * @nullable
+ */
readonly created_by: number | null
+ /** Set to true to archive the category. Archived categories don't appear in lists. */
deleted?: boolean
}
@@ -44,18 +63,37 @@ export interface PaginatedMessageCategoryListApi {
}
export interface PatchedMessageCategoryApi {
+ /** Category ID. Workflow message steps take it as `message_category_id`, and the opt-out of messages step takes it as its `category_id` input. */
readonly id?: string
- /** @maxLength 64 */
+ /**
+ * Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation.
+ * @maxLength 64
+ */
key?: string
- /** @maxLength 128 */
+ /**
+ * Display name of the category, shown in the PostHog app.
+ * @maxLength 128
+ */
name?: string
+ /** Internal notes about which messages belong to this category. Recipients don't see it. */
description?: string
+ /** Description that recipients see next to the category on the preferences page. */
public_description?: string
+ /** `marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.
+ *
+ * * `marketing` - Marketing
+ * * `transactional` - Transactional */
category_type?: MessageCategoryTypeEnumApi
+ /** When the category was created. */
readonly created_at?: string
+ /** When the category was last changed. */
readonly updated_at?: string
- /** @nullable */
+ /**
+ * ID of the user who created the category. Null when the user no longer exists.
+ * @nullable
+ */
readonly created_by?: number | null
+ /** Set to true to archive the category. Archived categories don't appear in lists. */
deleted?: boolean
}
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index 3816dda855be..a465ae49a882 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -14,15 +14,35 @@ export const messagingCategoriesCreateBodyKeyMax = 64
export const messagingCategoriesCreateBodyNameMax = 128
export const MessagingCategoriesCreateBody = /* @__PURE__ */ zod.object({
- key: zod.string().max(messagingCategoriesCreateBodyKeyMax),
- name: zod.string().max(messagingCategoriesCreateBodyNameMax),
- description: zod.string().optional(),
- public_description: zod.string().optional(),
+ key: zod
+ .string()
+ .max(messagingCategoriesCreateBodyKeyMax)
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesCreateBodyNameMax)
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
category_type: zod
.enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
+ .optional()
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+ deleted: zod
+ .boolean()
.optional()
- .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional'),
- deleted: zod.boolean().optional(),
+ .describe("Set to true to archive the category. Archived categories don't appear in lists."),
})
export const messagingCategoriesUpdateBodyKeyMax = 64
@@ -30,15 +50,35 @@ export const messagingCategoriesUpdateBodyKeyMax = 64
export const messagingCategoriesUpdateBodyNameMax = 128
export const MessagingCategoriesUpdateBody = /* @__PURE__ */ zod.object({
- key: zod.string().max(messagingCategoriesUpdateBodyKeyMax),
- name: zod.string().max(messagingCategoriesUpdateBodyNameMax),
- description: zod.string().optional(),
- public_description: zod.string().optional(),
+ key: zod
+ .string()
+ .max(messagingCategoriesUpdateBodyKeyMax)
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesUpdateBodyNameMax)
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
category_type: zod
.enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
.optional()
- .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional'),
- deleted: zod.boolean().optional(),
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+ deleted: zod
+ .boolean()
+ .optional()
+ .describe("Set to true to archive the category. Archived categories don't appear in lists."),
})
export const messagingCategoriesPartialUpdateBodyKeyMax = 64
@@ -46,15 +86,37 @@ export const messagingCategoriesPartialUpdateBodyKeyMax = 64
export const messagingCategoriesPartialUpdateBodyNameMax = 128
export const MessagingCategoriesPartialUpdateBody = /* @__PURE__ */ zod.object({
- key: zod.string().max(messagingCategoriesPartialUpdateBodyKeyMax).optional(),
- name: zod.string().max(messagingCategoriesPartialUpdateBodyNameMax).optional(),
- description: zod.string().optional(),
- public_description: zod.string().optional(),
+ key: zod
+ .string()
+ .max(messagingCategoriesPartialUpdateBodyKeyMax)
+ .optional()
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
category_type: zod
.enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
+ .optional()
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+ deleted: zod
+ .boolean()
.optional()
- .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional'),
- deleted: zod.boolean().optional(),
+ .describe("Set to true to archive the category. Archived categories don't appear in lists."),
})
/**
@@ -67,15 +129,35 @@ export const messagingCategoriesImportFromCustomerioCreateBodyKeyMax = 64
export const messagingCategoriesImportFromCustomerioCreateBodyNameMax = 128
export const MessagingCategoriesImportFromCustomerioCreateBody = /* @__PURE__ */ zod.object({
- key: zod.string().max(messagingCategoriesImportFromCustomerioCreateBodyKeyMax),
- name: zod.string().max(messagingCategoriesImportFromCustomerioCreateBodyNameMax),
- description: zod.string().optional(),
- public_description: zod.string().optional(),
+ key: zod
+ .string()
+ .max(messagingCategoriesImportFromCustomerioCreateBodyKeyMax)
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesImportFromCustomerioCreateBodyNameMax)
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
category_type: zod
.enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
+ .optional()
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+ deleted: zod
+ .boolean()
.optional()
- .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional'),
- deleted: zod.boolean().optional(),
+ .describe("Set to true to archive the category. Archived categories don't appear in lists."),
})
/**
@@ -87,15 +169,35 @@ export const messagingCategoriesImportPreferencesCsvCreateBodyKeyMax = 64
export const messagingCategoriesImportPreferencesCsvCreateBodyNameMax = 128
export const MessagingCategoriesImportPreferencesCsvCreateBody = /* @__PURE__ */ zod.object({
- key: zod.string().max(messagingCategoriesImportPreferencesCsvCreateBodyKeyMax),
- name: zod.string().max(messagingCategoriesImportPreferencesCsvCreateBodyNameMax),
- description: zod.string().optional(),
- public_description: zod.string().optional(),
+ key: zod
+ .string()
+ .max(messagingCategoriesImportPreferencesCsvCreateBodyKeyMax)
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesImportPreferencesCsvCreateBodyNameMax)
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
category_type: zod
.enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
.optional()
- .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional'),
- deleted: zod.boolean().optional(),
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+ deleted: zod
+ .boolean()
+ .optional()
+ .describe("Set to true to archive the category. Archived categories don't appear in lists."),
})
/**
@@ -112,15 +214,35 @@ export const messagingCategoriesSaveTrackConfigCreateBodyKeyMax = 64
export const messagingCategoriesSaveTrackConfigCreateBodyNameMax = 128
export const MessagingCategoriesSaveTrackConfigCreateBody = /* @__PURE__ */ zod.object({
- key: zod.string().max(messagingCategoriesSaveTrackConfigCreateBodyKeyMax),
- name: zod.string().max(messagingCategoriesSaveTrackConfigCreateBodyNameMax),
- description: zod.string().optional(),
- public_description: zod.string().optional(),
+ key: zod
+ .string()
+ .max(messagingCategoriesSaveTrackConfigCreateBodyKeyMax)
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesSaveTrackConfigCreateBodyNameMax)
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
category_type: zod
.enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
.optional()
- .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional'),
- deleted: zod.boolean().optional(),
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+ deleted: zod
+ .boolean()
+ .optional()
+ .describe("Set to true to archive the category. Archived categories don't appear in lists."),
})
/**
@@ -135,15 +257,35 @@ export const messagingCategoriesSaveWebhookConfigCreateBodyKeyMax = 64
export const messagingCategoriesSaveWebhookConfigCreateBodyNameMax = 128
export const MessagingCategoriesSaveWebhookConfigCreateBody = /* @__PURE__ */ zod.object({
- key: zod.string().max(messagingCategoriesSaveWebhookConfigCreateBodyKeyMax),
- name: zod.string().max(messagingCategoriesSaveWebhookConfigCreateBodyNameMax),
- description: zod.string().optional(),
- public_description: zod.string().optional(),
+ key: zod
+ .string()
+ .max(messagingCategoriesSaveWebhookConfigCreateBodyKeyMax)
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesSaveWebhookConfigCreateBodyNameMax)
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
category_type: zod
.enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
+ .optional()
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+ deleted: zod
+ .boolean()
.optional()
- .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional'),
- deleted: zod.boolean().optional(),
+ .describe("Set to true to archive the category. Archived categories don't appear in lists."),
})
/**
diff --git a/products/messaging/mcp/tools.yaml b/products/messaging/mcp/tools.yaml
index a04daf1c8122..cf44c7a2922c 100644
--- a/products/messaging/mcp/tools.yaml
+++ b/products/messaging/mcp/tools.yaml
@@ -7,6 +7,72 @@ feature: messaging
url_prefix: /workflows
ui_apps: {}
tools:
+ message-categories-create:
+ operation: messaging_categories_create
+ enabled: true
+ scopes:
+ - hog_flow:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create a message category
+ description: >
+ Create a message category, the topic a workflow message belongs to, such as a newsletter or product updates.
+ Recipients can opt out of a marketing category, and sends skip the recipients who did. Use a transactional
+ category for messages a recipient must get, such as receipts or password resets: those sends ignore
+ opt-outs. Pass the returned id as message_category_id on a workflow email step, and set the step's
+ message_category_type to the same category_type. The opt-out of messages step takes the id as its
+ category_id input. Call message-categories-list first: the key must be unique in the project and can't
+ change after creation.
+ exclude_params:
+ - deleted
+ message-categories-get:
+ operation: messaging_categories_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a message category
+ description: >
+ Get a message category by ID, with its key, name, descriptions, and category_type (marketing categories can
+ be opted out of, transactional categories ignore opt-outs).
+ message-categories-list:
+ operation: messaging_categories_list
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List message categories
+ description: >
+ List the project's message categories. Recipients can opt out of a marketing category, and transactional
+ categories ignore opt-outs. Use a category's id as message_category_id on a workflow email step or as the
+ category_id input of the opt-out of messages step, and its key as category_key in the opt-outs tools.
+ message-categories-update:
+ operation: messaging_categories_partial_update
+ enabled: true
+ scopes:
+ - hog_flow:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update a message category
+ description: >
+ Change a message category's name, description, public_description, or category_type. Only the fields you
+ pass change, and the key can't change. Workflow steps keep the message_category_type they were saved with,
+ so after a category_type change, update the message_category_type of the steps that use this category. A
+ transactional send ignores opt-outs, so confirm a change to transactional with the user first.
+ exclude_params:
+ - key
+ - deleted
opt-outs-add:
operation: messaging_preferences_bulk_add_opt_outs_create
enabled: true
diff --git a/products/workflows/backend/tests/api/test_message_preferences_access_control.py b/products/workflows/backend/tests/api/test_message_preferences_access_control.py
index 7f4d8fe531c9..e46169c08c25 100644
--- a/products/workflows/backend/tests/api/test_message_preferences_access_control.py
+++ b/products/workflows/backend/tests/api/test_message_preferences_access_control.py
@@ -11,14 +11,16 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
from products.access_control.backend.models.access_control import AccessControl
+from products.messaging.backend.facade.testing import create_message_category_for_test
@pytest.mark.ee
class TestMessagePreferencesAccessControl(APIBaseTest):
"""
- Guards the resource-level RBAC gate on `/api/projects/:id/messaging_preferences/`.
+ Guards the resource-level RBAC gate on `/api/projects/:id/messaging_preferences/` and
+ `/api/projects/:id/messaging_categories/`.
- The endpoints act on team-wide data (every opted-out recipient, every add/remove) but carry
+ The endpoints act on team-wide data (every opted-out recipient, every category) but carry
no per-workflow object. `AccessControlPermission` alone falls back to "does the user have
access to any single hog_flow object?" — which would let a member granted access to one
workflow read or rewrite the entire team's opt-out list.
@@ -107,3 +109,28 @@ class TestMessagePreferencesAccessControl(APIBaseTest):
).status_code
== bulk_status
)
+
+ @parameterized.expand(
+ [
+ ("object_editor", status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN),
+ ("resource_viewer", status.HTTP_200_OK, status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN),
+ ("resource_editor", status.HTTP_200_OK, status.HTTP_201_CREATED, status.HTTP_200_OK),
+ ]
+ )
+ def test_message_category_access_matrix(
+ self, grant_type: str, read_status: int, create_status: int, update_status: int
+ ) -> None:
+ category_id = create_message_category_for_test(team_id=self.team.id, key="newsletter", name="Newsletter")
+ self.client.force_login(getattr(self, grant_type))
+ base_url = f"/api/projects/{self.team.id}/messaging_categories/"
+
+ assert self.client.get(base_url).status_code == read_status
+ assert self.client.get(f"{base_url}{category_id}/").status_code == read_status
+ assert (
+ self.client.post(base_url, {"key": f"{grant_type}_cat", "name": "New"}, format="json").status_code
+ == create_status
+ )
+ assert (
+ self.client.patch(f"{base_url}{category_id}/", {"name": "Renamed"}, format="json").status_code
+ == update_status
+ )
diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.md
index bebada398e82..d34810da4b42 100644
--- a/products/workflows/skills/building-workflows/references/graph-schema.md
+++ b/products/workflows/skills/building-workflows/references/graph-schema.md
@@ -218,7 +218,7 @@ A `function` node with `template_id: "template-posthog-opt-out-of-messages"` add
}
```
-- **`category_id` is a literal, not a template.** Use a marketing message category's `id` (UUID), listed by `GET /api/projects/:project_id/messaging_categories/`, or `"$all"` for all marketing messages. If the user names a category you can't look up, ask them for it rather than guess. Never put `{...}` expressions in it. A save with a category the project doesn't have fails.
+- **`category_id` is a literal, not a template.** Use a marketing message category's `id` (UUID), listed by `message-categories-list`, or `"$all"` for all marketing messages. If the category doesn't exist yet and the user's request covers creating it, for example an import that brings its own categories, create it with `message-categories-create`. Otherwise ask the user for it rather than guess. Never put `{...}` expressions in it. A save with a category the project doesn't have fails.
- `identifier` is who to opt out. It defaults to `{person.properties.email}`. Use the same value as the recipient of the email step it should suppress, because opt-outs match the recipient exactly.
- Only marketing categories work, because transactional messages ignore opt-outs. A save with a transactional category fails.
- The step fails, and the workflow log says why, when `identifier` is empty or the category was deleted. It never passes silently.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 7579ba8e759b..6eea11b3c6ab 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10644,6 +10644,66 @@
"readOnlyHint": true
}
},
+ "message-categories-create": {
+ "description": "Create a message category, the topic a workflow message belongs to, such as a newsletter or product updates. Recipients can opt out of a marketing category, and sends skip the recipients who did. Use a transactional category for messages a recipient must get, such as receipts or password resets: those sends ignore opt-outs. Pass the returned id as message_category_id on a workflow email step, and set the step's message_category_type to the same category_type. The opt-out of messages step takes the id as its category_id input. Call message-categories-list first: the key must be unique in the project and can't change after creation.",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "Create a message category",
+ "title": "Create a message category",
+ "required_scopes": ["hog_flow:write"],
+ "api_operations": ["POST /api/projects/{project_id}/messaging_categories/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "message-categories-get": {
+ "description": "Get a message category by ID, with its key, name, descriptions, and category_type (marketing categories can be opted out of, transactional categories ignore opt-outs).",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "Get a message category",
+ "title": "Get a message category",
+ "required_scopes": ["hog_flow:read"],
+ "api_operations": ["GET /api/projects/{project_id}/messaging_categories/{id}/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "message-categories-list": {
+ "description": "List the project's message categories. Recipients can opt out of a marketing category, and transactional categories ignore opt-outs. Use a category's id as message_category_id on a workflow email step or as the category_id input of the opt-out of messages step, and its key as category_key in the opt-outs tools.",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "List message categories",
+ "title": "List message categories",
+ "required_scopes": ["hog_flow:read"],
+ "api_operations": ["GET /api/projects/{project_id}/messaging_categories/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "message-categories-update": {
+ "description": "Change a message category's name, description, public_description, or category_type. Only the fields you pass change, and the key can't change. Workflow steps keep the message_category_type they were saved with, so after a category_type change, update the message_category_type of the steps that use this category. A transactional send ignores opt-outs, so confirm a change to transactional with the user first.",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "Update a message category",
+ "title": "Update a message category",
+ "required_scopes": ["hog_flow:write"],
+ "api_operations": ["PATCH /api/projects/{project_id}/messaging_categories/{id}/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"metric-attribute-values-list": {
"description": "List the values of one attribute key of a metric, from the most frequent value to the least frequent. Use it to find the exact value for a filter, for example the service.name of a service.",
"category": "Metrics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index b10f517d55b9..14bf3a03b498 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11059,6 +11059,66 @@
"readOnlyHint": true
}
},
+ "message-categories-create": {
+ "description": "Create a message category, the topic a workflow message belongs to, such as a newsletter or product updates. Recipients can opt out of a marketing category, and sends skip the recipients who did. Use a transactional category for messages a recipient must get, such as receipts or password resets: those sends ignore opt-outs. Pass the returned id as message_category_id on a workflow email step, and set the step's message_category_type to the same category_type. The opt-out of messages step takes the id as its category_id input. Call message-categories-list first: the key must be unique in the project and can't change after creation.",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "Create a message category",
+ "title": "Create a message category",
+ "required_scopes": ["hog_flow:write"],
+ "api_operations": ["POST /api/projects/{project_id}/messaging_categories/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "message-categories-get": {
+ "description": "Get a message category by ID, with its key, name, descriptions, and category_type (marketing categories can be opted out of, transactional categories ignore opt-outs).",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "Get a message category",
+ "title": "Get a message category",
+ "required_scopes": ["hog_flow:read"],
+ "api_operations": ["GET /api/projects/{project_id}/messaging_categories/{id}/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "message-categories-list": {
+ "description": "List the project's message categories. Recipients can opt out of a marketing category, and transactional categories ignore opt-outs. Use a category's id as message_category_id on a workflow email step or as the category_id input of the opt-out of messages step, and its key as category_key in the opt-outs tools.",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "List message categories",
+ "title": "List message categories",
+ "required_scopes": ["hog_flow:read"],
+ "api_operations": ["GET /api/projects/{project_id}/messaging_categories/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
+ "message-categories-update": {
+ "description": "Change a message category's name, description, public_description, or category_type. Only the fields you pass change, and the key can't change. Workflow steps keep the message_category_type they were saved with, so after a category_type change, update the message_category_type of the steps that use this category. A transactional send ignores opt-outs, so confirm a change to transactional with the user first.",
+ "category": "Messaging",
+ "feature": "messaging",
+ "summary": "Update a message category",
+ "title": "Update a message category",
+ "required_scopes": ["hog_flow:write"],
+ "api_operations": ["PATCH /api/projects/{project_id}/messaging_categories/{id}/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"metric-attribute-values-list": {
"description": "List the values of one attribute key of a metric, from the most frequent value to the least frequent. Use it to find the exact value for a filter, for example the service.name of a service.",
"category": "Metrics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8467b4e963ea..54cb2a4eb448 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -71014,18 +71014,37 @@ export namespace Schemas {
} as const;
export interface MessageCategory {
+ /** Category ID. Workflow message steps take it as `message_category_id`, and the opt-out of messages step takes it as its `category_id` input. */
readonly id: string;
- /** @maxLength 64 */
+ /**
+ * Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation.
+ * @maxLength 64
+ */
key: string;
- /** @maxLength 128 */
+ /**
+ * Display name of the category, shown in the PostHog app.
+ * @maxLength 128
+ */
name: string;
+ /** Internal notes about which messages belong to this category. Recipients don't see it. */
description?: string;
+ /** Description that recipients see next to the category on the preferences page. */
public_description?: string;
+ /** `marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.
+ *
+ * * `marketing` - Marketing
+ * * `transactional` - Transactional */
category_type?: MessageCategoryTypeEnum;
+ /** When the category was created. */
readonly created_at: string;
+ /** When the category was last changed. */
readonly updated_at: string;
- /** @nullable */
+ /**
+ * ID of the user who created the category. Null when the user no longer exists.
+ * @nullable
+ */
readonly created_by: number | null;
+ /** Set to true to archive the category. Archived categories don't appear in lists. */
deleted?: boolean;
}
@@ -87961,18 +87980,37 @@ export namespace Schemas {
}
export interface PatchedMessageCategory {
+ /** Category ID. Workflow message steps take it as `message_category_id`, and the opt-out of messages step takes it as its `category_id` input. */
readonly id?: string;
- /** @maxLength 64 */
+ /**
+ * Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation.
+ * @maxLength 64
+ */
key?: string;
- /** @maxLength 128 */
+ /**
+ * Display name of the category, shown in the PostHog app.
+ * @maxLength 128
+ */
name?: string;
+ /** Internal notes about which messages belong to this category. Recipients don't see it. */
description?: string;
+ /** Description that recipients see next to the category on the preferences page. */
public_description?: string;
+ /** `marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.
+ *
+ * * `marketing` - Marketing
+ * * `transactional` - Transactional */
category_type?: MessageCategoryTypeEnum;
+ /** When the category was created. */
readonly created_at?: string;
+ /** When the category was last changed. */
readonly updated_at?: string;
- /** @nullable */
+ /**
+ * ID of the user who created the category. Null when the user no longer exists.
+ * @nullable
+ */
readonly created_by?: number | null;
+ /** Set to true to archive the category. Archived categories don't appear in lists. */
deleted?: boolean;
}
diff --git a/services/mcp/src/generated/messaging/api.ts b/services/mcp/src/generated/messaging/api.ts
index 7279f6335497..a4fca0f98805 100644
--- a/services/mcp/src/generated/messaging/api.ts
+++ b/services/mcp/src/generated/messaging/api.ts
@@ -3,11 +3,107 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 3 enabled ops
+ * PostHog API - MCP 7 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
+export const MessagingCategoriesListParams = () => 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 MessagingCategoriesListQueryParams = () => zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+export const MessagingCategoriesCreateParams = () => 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 messagingCategoriesCreateBodyKeyMax = 64
+
+export const messagingCategoriesCreateBodyNameMax = 128
+
+export const MessagingCategoriesCreateBody = () => zod.object({
+ key: zod
+ .string()
+ .max(messagingCategoriesCreateBodyKeyMax)
+ .describe(
+ "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation."
+ ),
+ name: zod
+ .string()
+ .max(messagingCategoriesCreateBodyNameMax)
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
+ category_type: zod
+ .enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
+ .optional()
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+})
+
+export const MessagingCategoriesRetrieveParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this message category.'),
+ 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 MessagingCategoriesPartialUpdateParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this message category.'),
+ 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 messagingCategoriesPartialUpdateBodyNameMax = 128
+
+export const MessagingCategoriesPartialUpdateBody = () => zod.object({
+ name: zod
+ .string()
+ .max(messagingCategoriesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Display name of the category, shown in the PostHog app.'),
+ description: zod
+ .string()
+ .optional()
+ .describe("Internal notes about which messages belong to this category. Recipients don't see it."),
+ public_description: zod
+ .string()
+ .optional()
+ .describe('Description that recipients see next to the category on the preferences page.'),
+ category_type: zod
+ .enum(['marketing', 'transactional'])
+ .describe('\* `marketing` - Marketing\n\* `transactional` - Transactional')
+ .optional()
+ .describe(
+ "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n\* `marketing` - Marketing\n\* `transactional` - Transactional"
+ ),
+})
+
/**
* Opt every recipient in the list out of the category named on their entry, or a default category.
* @summary Add multiple recipients to the opt-out list
diff --git a/services/mcp/src/tools/generated/messaging.ts b/services/mcp/src/tools/generated/messaging.ts
index 2ae45ac41451..668db51e625c 100644
--- a/services/mcp/src/tools/generated/messaging.ts
+++ b/services/mcp/src/tools/generated/messaging.ts
@@ -3,8 +3,128 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/messaging/api'
+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const MessageCategoriesCreateSchema = () => {
+ const MessagingCategoriesCreateBody = orvalSchemas.MessagingCategoriesCreateBody()
+ return MessagingCategoriesCreateBody
+}
+
+const messageCategoriesCreate = (): ToolBase<
+ ReturnType<typeof MessageCategoriesCreateSchema>,
+ Schemas.MessageCategory
+> => ({
+ name: 'message-categories-create',
+ schema: MessageCategoriesCreateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof MessageCategoriesCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.key !== undefined) {
+ body['key'] = params.key
+ }
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.public_description !== undefined) {
+ body['public_description'] = params.public_description
+ }
+ if (params.category_type !== undefined) {
+ body['category_type'] = params.category_type
+ }
+ const result = await context.api.request<Schemas.MessageCategory>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_categories/`,
+ body,
+ })
+ return result
+ },
+})
+
+const MessageCategoriesGetSchema = () => {
+ const MessagingCategoriesRetrieveParams = orvalSchemas.MessagingCategoriesRetrieveParams()
+ return MessagingCategoriesRetrieveParams.omit({ project_id: true })
+}
+
+const messageCategoriesGet = (): ToolBase<ReturnType<typeof MessageCategoriesGetSchema>, Schemas.MessageCategory> => ({
+ name: 'message-categories-get',
+ schema: MessageCategoriesGetSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof MessageCategoriesGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.MessageCategory>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_categories/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const MessageCategoriesListSchema = () => {
+ const MessagingCategoriesListQueryParams = orvalSchemas.MessagingCategoriesListQueryParams()
+ return MessagingCategoriesListQueryParams
+}
+
+const messageCategoriesList = (): ToolBase<
+ ReturnType<typeof MessageCategoriesListSchema>,
+ WithPostHogUrl<Schemas.PaginatedMessageCategoryList>
+> => ({
+ name: 'message-categories-list',
+ schema: MessageCategoriesListSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof MessageCategoriesListSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedMessageCategoryList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_categories/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return await withPostHogUrl(context, result, '/workflows')
+ },
+})
+
+const MessageCategoriesUpdateSchema = () => {
+ const MessagingCategoriesPartialUpdateBody = orvalSchemas.MessagingCategoriesPartialUpdateBody()
+ const MessagingCategoriesPartialUpdateParams = orvalSchemas.MessagingCategoriesPartialUpdateParams()
+ return MessagingCategoriesPartialUpdateParams.omit({ project_id: true }).extend(
+ MessagingCategoriesPartialUpdateBody.shape
+ )
+}
+
+const messageCategoriesUpdate = (): ToolBase<
+ ReturnType<typeof MessageCategoriesUpdateSchema>,
+ Schemas.MessageCategory
+> => ({
+ name: 'message-categories-update',
+ schema: MessageCategoriesUpdateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof MessageCategoriesUpdateSchema>>) => {
+ 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.public_description !== undefined) {
+ body['public_description'] = params.public_description
+ }
+ if (params.category_type !== undefined) {
+ body['category_type'] = params.category_type
+ }
+ const result = await context.api.request<Schemas.MessageCategory>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_categories/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
const OptOutsAddSchema = () => {
const MessagingPreferencesBulkAddOptOutsCreateBody = orvalSchemas.MessagingPreferencesBulkAddOptOutsCreateBody()
return MessagingPreferencesBulkAddOptOutsCreateBody
@@ -82,6 +202,10 @@ const optOutsRemove = (): ToolBase<ReturnType<typeof OptOutsRemoveSchema>, Schem
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'message-categories-create': messageCategoriesCreate,
+ 'message-categories-get': messageCategoriesGet,
+ 'message-categories-list': messageCategoriesList,
+ 'message-categories-update': messageCategoriesUpdate,
'opt-outs-add': optOutsAdd,
'opt-outs-list': optOutsList,
'opt-outs-remove': optOutsRemove,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-create.json
new file mode 100644
index 000000000000..17953d3dc726
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-create.json
@@ -0,0 +1,30 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "category_type": {
+ "description": "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n* `marketing` - Marketing\n* `transactional` - Transactional",
+ "enum": ["marketing", "transactional"],
+ "type": "string"
+ },
+ "description": {
+ "description": "Internal notes about which messages belong to this category. Recipients don't see it.",
+ "type": "string"
+ },
+ "key": {
+ "description": "Stable identifier for the category, unique within the project, for example `newsletter`. Opt-out lists and preference imports refer to categories by key. You can't change the key after creation.",
+ "maxLength": 64,
+ "type": "string"
+ },
+ "name": {
+ "description": "Display name of the category, shown in the PostHog app.",
+ "maxLength": 128,
+ "type": "string"
+ },
+ "public_description": {
+ "description": "Description that recipients see next to the category on the preferences page.",
+ "type": "string"
+ }
+ },
+ "required": ["key", "name"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-get.json
new file mode 100644
index 000000000000..e3bfa84fcd8c
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-get.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this message category.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-list.json
new file mode 100644
index 000000000000..8331b796ac73
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-list.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-update.json
new file mode 100644
index 000000000000..e590da5bdaeb
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/message-categories-update.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "category_type": {
+ "description": "`marketing` (the default): recipients can opt out of it, and sends skip recipients who did. `transactional`: for messages a recipient must get, such as receipts or password resets. Sends ignore opt-outs, and the category doesn't appear on the preferences page. Set `message_category_type` on a workflow message step to the type of its category.\n\n* `marketing` - Marketing\n* `transactional` - Transactional",
+ "enum": ["marketing", "transactional"],
+ "type": "string"
+ },
+ "description": {
+ "description": "Internal notes about which messages belong to this category. Recipients don't see it.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this message category.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Display name of the category, shown in the PostHog app.",
+ "maxLength": 128,
+ "type": "string"
+ },
+ "public_description": {
+ "description": "Description that recipients see next to the category on the preferences page.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}