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(conversations): expose ticket compose as an mcp tool (#115929)

Ben Lea946080bd8322
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index 82acc5702ebd..36c4451b766a 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -2295,6 +2295,22 @@ class TestComposeTicketAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert not Ticket.objects.filter(team=self.team).exists()
+ @parameterized.expand([("with_default_channel", True), ("without_default_channel", False)])
+ def test_compose_without_channel_id_uses_the_default_support_channel(
+ self, mock_on_commit, _name, has_default
+ ) -> None:
+ self.email_config.is_default = has_default
+ self.email_config.save()
+
+ response = self._compose({"recipient_email": "[email protected]", "message": "Hello!"})
+
+ if has_default:
+ assert response.status_code == status.HTTP_201_CREATED
+ assert Ticket.objects.get(team=self.team).email_config_id == self.email_config.id
+ else:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not Ticket.objects.filter(team=self.team).exists()
+
def test_composed_ticket_is_not_born_verified(self, mock_on_commit):
# The team typed the recipient address; the recipient never proved they control it,
# so an outbound ticket must start with unknown identity (None) — never verified.
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index c47c83b42fb7..422ff8d5bac0 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -292,7 +292,9 @@ class ComposeTicketSerializer(serializers.Serializer):
help_text="Email subject line.",
)
email_config_id = serializers.UUIDField(
- help_text="ID of the EmailChannel to send from.",
+ required=False,
+ allow_null=True,
+ help_text="ID of the support email channel to send from. Omit it to send from the team's default support channel.",
)
message = serializers.CharField(
max_length=5000,
@@ -2030,15 +2032,18 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro
status=drf_status.HTTP_400_BAD_REQUEST,
)
- email_config = EmailChannel.objects.filter(
- id=data["email_config_id"],
- team=team,
- kind=EmailChannelKind.SUPPORT,
- domain_verified=True,
- ).first()
+ email_configs = EmailChannel.objects.filter(team=team, kind=EmailChannelKind.SUPPORT, domain_verified=True)
+ if data.get("email_config_id"):
+ email_config = email_configs.filter(id=data["email_config_id"]).first()
+ else:
+ email_config = email_configs.filter(is_default=True).first()
if not email_config:
return Response(
- {"detail": "Email configuration not found or domain not verified."},
+ {
+ "detail": "Email configuration not found or domain not verified."
+ if data.get("email_config_id")
+ else "No default support email channel with a verified domain. Pass email_config_id."
+ },
status=drf_status.HTTP_400_BAD_REQUEST,
)
diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.ts
index 3161c5816ee6..4171ea77acb9 100644
--- a/products/conversations/frontend/generated/api.schemas.ts
+++ b/products/conversations/frontend/generated/api.schemas.ts
@@ -658,8 +658,11 @@ export interface ComposeTicketApi {
* @maxLength 500
*/
email_subject?: string
- /** ID of the EmailChannel to send from. */
- email_config_id: string
+ /**
+ * ID of the support email channel to send from. Omit it to send from the team's default support channel.
+ * @nullable
+ */
+ email_config_id?: string | null
/**
* Message content in markdown.
* @maxLength 5000
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index 4affac43689a..20a78515a6ee 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -333,7 +333,12 @@ export const ConversationsTicketsComposeCreateBody = /* @__PURE__ */ zod.object(
.max(conversationsTicketsComposeCreateBodyEmailSubjectMax)
.optional()
.describe('Email subject line.'),
- email_config_id: zod.uuid().describe('ID of the EmailChannel to send from.'),
+ email_config_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ "ID of the support email channel to send from. Omit it to send from the team's default support channel."
+ ),
message: zod.string().max(conversationsTicketsComposeCreateBodyMessageMax).describe('Message content in markdown.'),
rich_content: zod.unknown().optional().describe('TipTap rich content JSON for formatted messages.'),
tags: zod
diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yaml
index cd05128fbf2c..9ed3d2dadcd1 100644
--- a/products/conversations/mcp/tools.yaml
+++ b/products/conversations/mcp/tools.yaml
@@ -7,6 +7,23 @@ feature: conversations
url_prefix: /support/tickets
ui_apps: {}
tools:
+ conversations-tickets-compose-create:
+ operation: conversations_tickets_compose_create
+ enabled: true
+ scopes:
+ - ticket:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Start a support ticket by email
+ description: >
+ Create a new outbound email ticket and send its first message to the recipient. The message IS EMAILED to
+ the customer in full, from a support email channel with a verified domain. Omit email_config_id to send from
+ the team's default support channel. Use it to reach a customer who has no ticket, or who cannot read replies
+ on an existing widget ticket. To answer an existing ticket, use conversations-tickets-reply-create instead.
+ An identical request sent again within a short window returns the same ticket and sends no second email.
+ Returns the new ticket's id and ticket_number.
conversations-tickets-list:
operation: conversations_tickets_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index cb4b6e34d475..35983d3c6822 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2816,6 +2816,20 @@
"readOnlyHint": true
}
},
+ "conversations-tickets-compose-create": {
+ "description": "Create a new outbound email ticket and send its first message to the recipient. The message IS EMAILED to the customer in full, from a support email channel with a verified domain. Omit email_config_id to send from the team's default support channel. Use it to reach a customer who has no ticket, or who cannot read replies on an existing widget ticket. To answer an existing ticket, use conversations-tickets-reply-create instead. An identical request sent again within a short window returns the same ticket and sends no second email. Returns the new ticket's id and ticket_number.",
+ "category": "Conversations",
+ "feature": "conversations",
+ "summary": "Start a support ticket by email",
+ "title": "Start a support ticket by email",
+ "required_scopes": ["ticket:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"conversations-tickets-list": {
"description": "List support tickets in the project. Supports filtering by status (new, open, pending, on_hold, resolved), priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, tags, SLA state, AI triage result, date range, and search. To work with a saved ticket view, pass its short_id as the `view` parameter (find it via conversations-views-list); the view's saved filters are applied server-side, and any filter parameter passed explicitly overrides the view's value for that dimension. Results are paginated and ordered by updated_at descending by default. Returns ticket metadata including status, priority, message counts, and timestamps. Use conversations-tickets-retrieve for one ticket's full details and conversations-tickets-messages-retrieve for its message thread.",
"category": "Conversations",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c1e5b9bfdf36..44005e7ace2e 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2831,6 +2831,20 @@
"readOnlyHint": true
}
},
+ "conversations-tickets-compose-create": {
+ "description": "Create a new outbound email ticket and send its first message to the recipient. The message IS EMAILED to the customer in full, from a support email channel with a verified domain. Omit email_config_id to send from the team's default support channel. Use it to reach a customer who has no ticket, or who cannot read replies on an existing widget ticket. To answer an existing ticket, use conversations-tickets-reply-create instead. An identical request sent again within a short window returns the same ticket and sends no second email. Returns the new ticket's id and ticket_number.",
+ "category": "Conversations",
+ "feature": "conversations",
+ "summary": "Start a support ticket by email",
+ "title": "Start a support ticket by email",
+ "required_scopes": ["ticket:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"conversations-tickets-list": {
"description": "List support tickets in the project. Supports filtering by status (new, open, pending, on_hold, resolved), priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, tags, SLA state, AI triage result, date range, and search. To work with a saved ticket view, pass its short_id as the `view` parameter (find it via conversations-views-list); the view's saved filters are applied server-side, and any filter parameter passed explicitly overrides the view's value for that dimension. Results are paginated and ordered by updated_at descending by default. Returns ticket metadata including status, priority, message counts, and timestamps. Use conversations-tickets-retrieve for one ticket's full details and conversations-tickets-messages-retrieve for its message thread.",
"category": "Conversations",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 358b57b43c96..7ae046463309 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24667,8 +24667,11 @@ export namespace Schemas {
* @maxLength 500
*/
email_subject?: string;
- /** ID of the EmailChannel to send from. */
- email_config_id: string;
+ /**
+ * ID of the support email channel to send from. Omit it to send from the team's default support channel.
+ * @nullable
+ */
+ email_config_id?: string | null;
/**
* Message content in markdown.
* @maxLength 5000
diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.ts
index 375f12da2ab7..ff9523cad373 100644
--- a/services/mcp/src/generated/conversations/api.ts
+++ b/services/mcp/src/generated/conversations/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 12 enabled ops
+ * PostHog API - MCP 13 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -334,6 +334,60 @@ export const ConversationsTicketsReplyCreateBody = () => zod
})
.describe('Payload for posting a reply or internal note to a ticket.')
+/**
+ * Create a new outbound ticket and send the first message to the customer.
+ *
+ * Idempotent within a short window: an identical compose retried while the first is still
+ * in flight returns 409, and one retried after it committed returns the same ticket with a
+ * 200. Only a genuinely new request creates a ticket and emails the customer.
+ */
+export const ConversationsTicketsComposeCreateParams = () => 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 conversationsTicketsComposeCreateBodyRecipientDistinctIdMax = 400
+
+export const conversationsTicketsComposeCreateBodyEmailSubjectMax = 500
+
+export const conversationsTicketsComposeCreateBodyMessageMax = 5000
+
+export const conversationsTicketsComposeCreateBodyTagsItemMax = 255
+
+export const conversationsTicketsComposeCreateBodyTagsMax = 100
+
+export const ConversationsTicketsComposeCreateBody = () => zod.object({
+ recipient_email: zod.email().describe('Recipient email address.'),
+ recipient_distinct_id: zod
+ .string()
+ .max(conversationsTicketsComposeCreateBodyRecipientDistinctIdMax)
+ .optional()
+ .describe('PostHog distinct_id to link the ticket to a person. Falls back to recipient_email.'),
+ email_subject: zod
+ .string()
+ .max(conversationsTicketsComposeCreateBodyEmailSubjectMax)
+ .optional()
+ .describe('Email subject line.'),
+ email_config_id: zod
+ .string()
+ .nullish()
+ .describe(
+ "ID of the support email channel to send from. Omit it to send from the team's default support channel."
+ ),
+ message: zod.string().max(conversationsTicketsComposeCreateBodyMessageMax).describe('Message content in markdown.'),
+ rich_content: zod.unknown().optional().describe('TipTap rich content JSON for formatted messages.'),
+ tags: zod
+ .array(zod.string().max(conversationsTicketsComposeCreateBodyTagsItemMax))
+ .max(conversationsTicketsComposeCreateBodyTagsMax)
+ .optional()
+ .describe(
+ 'Tags to apply to the new ticket, e.g. to mark its source. Each is normalized (lowercased, trimmed). Up to 100.'
+ ),
+})
+
export const ConversationsViewsListParams = () => zod.object({
project_id: zod
.string()
diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.ts
index 1c1276d7d99b..bbdffba423c0 100644
--- a/services/mcp/src/lib/instructions.ts
+++ b/services/mcp/src/lib/instructions.ts
@@ -211,6 +211,7 @@ export class ToolDomainExtractor {
'cancel',
'claim',
'complete',
+ 'compose',
'copy',
'disable',
'discard',
diff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.ts
index 66e11748e6dd..2443e448cdc9 100644
--- a/services/mcp/src/tools/generated/conversations.ts
+++ b/services/mcp/src/tools/generated/conversations.ts
@@ -12,6 +12,50 @@ import {
} from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const ConversationsTicketsComposeCreateSchema = () => {
+ const ConversationsTicketsComposeCreateBody = orvalSchemas.ConversationsTicketsComposeCreateBody()
+ return ConversationsTicketsComposeCreateBody
+}
+
+const conversationsTicketsComposeCreate = (): ToolBase<
+ ReturnType<typeof ConversationsTicketsComposeCreateSchema>,
+ Schemas.ComposeTicketResponse
+> => ({
+ name: 'conversations-tickets-compose-create',
+ schema: ConversationsTicketsComposeCreateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ConversationsTicketsComposeCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.recipient_email !== undefined) {
+ body['recipient_email'] = params.recipient_email
+ }
+ if (params.recipient_distinct_id !== undefined) {
+ body['recipient_distinct_id'] = params.recipient_distinct_id
+ }
+ if (params.email_subject !== undefined) {
+ body['email_subject'] = params.email_subject
+ }
+ if (params.email_config_id !== undefined) {
+ body['email_config_id'] = params.email_config_id
+ }
+ if (params.message !== undefined) {
+ body['message'] = params.message
+ }
+ if (params.rich_content !== undefined) {
+ body['rich_content'] = params.rich_content
+ }
+ if (params.tags !== undefined) {
+ body['tags'] = params.tags
+ }
+ const result = await context.api.request<Schemas.ComposeTicketResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/conversations/tickets/compose/`,
+ body,
+ })
+ return result
+ },
+})
+
const ConversationsTicketsListSchema = () => {
const ConversationsTicketsListQueryParams = orvalSchemas.ConversationsTicketsListQueryParams()
return ConversationsTicketsListQueryParams
@@ -467,6 +511,7 @@ const conversationsViewsUpdate = (): ToolBase<
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'conversations-tickets-compose-create': conversationsTicketsComposeCreate,
'conversations-tickets-list': conversationsTicketsList,
'conversations-tickets-messages-retrieve': conversationsTicketsMessagesRetrieve,
'conversations-tickets-notes-create': conversationsTicketsNotesCreate,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-compose-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-compose-create.json
new file mode 100644
index 000000000000..3ff4bb5991d5
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-compose-create.json
@@ -0,0 +1,51 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "email_config_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "ID of the support email channel to send from. Omit it to send from the team's default support channel."
+ },
+ "email_subject": {
+ "description": "Email subject line.",
+ "maxLength": 500,
+ "type": "string"
+ },
+ "message": {
+ "description": "Message content in markdown.",
+ "maxLength": 5000,
+ "type": "string"
+ },
+ "recipient_distinct_id": {
+ "description": "PostHog distinct_id to link the ticket to a person. Falls back to recipient_email.",
+ "maxLength": 400,
+ "type": "string"
+ },
+ "recipient_email": {
+ "description": "Recipient email address.",
+ "format": "email",
+ "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$",
+ "type": "string"
+ },
+ "rich_content": {
+ "description": "TipTap rich content JSON for formatted messages."
+ },
+ "tags": {
+ "description": "Tags to apply to the new ticket, e.g. to mark its source. Each is normalized (lowercased, trimmed). Up to 100.",
+ "items": {
+ "maxLength": 255,
+ "type": "string"
+ },
+ "maxItems": 100,
+ "type": "array"
+ }
+ },
+ "required": ["recipient_email", "message"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.ts
index 0ec8f3084b25..335adf7cbf93 100644
--- a/services/mcp/tests/unit/instructions.test.ts
+++ b/services/mcp/tests/unit/instructions.test.ts
@@ -126,6 +126,7 @@ describe('buildToolDomainsBlock', () => {
'cancel',
'claim',
'complete',
+ 'compose',
'copy',
'disable',
'discard',