:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat: add MCP tools to read and reply to ticket threads (#62692)
Alex Vf3eb44772267
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex d78653760a28..69fe01e2b576 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -1,5 +1,6 @@import jsonfrom datetime import timedelta+from decimal import Decimalfrom posthog.test.base import (APIBaseTest,@@ -28,6 +29,7 @@ from posthog.models import ActivityLog, Comment, Organization, Tag, Userfrom posthog.models.person import Personfrom posthog.personhog_client.test_helpers import PersonhogTestMixin+from products.conversations.backend.api.tickets import TicketReplyRequestSerializerfrom products.conversations.backend.models import Ticket, TicketAssignmentfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Statusfrom products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_email@@ -1653,6 +1655,8 @@ class TestTicketPersonalAPIKeyScopes(APIBaseTest):def setUp(self):super().setUp()+ self.team.conversations_enabled = True+ self.team.save()self.ticket = Ticket.objects.create_with_number(team=self.team,channel_source=Channel.WIDGET,@@ -1700,3 +1704,367 @@ class TestTicketPersonalAPIKeyScopes(APIBaseTest):url = f"/api/projects/{self.team.id}/conversations/tickets/{action}/"response = self.client.post(url, {}, format="json")assert response.status_code == expected_status, f"{_name}: {response.status_code} != {expected_status}"++ @parameterized.expand(+ [+ ("messages_with_read", "messages", "get", ["ticket:read"], status.HTTP_200_OK),+ ("messages_with_write", "messages", "get", ["ticket:write"], status.HTTP_200_OK),+ ("messages_wrong_scope", "messages", "get", ["insight:read"], status.HTTP_403_FORBIDDEN),+ ("reply_with_write", "reply", "post", ["ticket:write"], status.HTTP_201_CREATED),+ ("reply_with_read_only", "reply", "post", ["ticket:read"], status.HTTP_403_FORBIDDEN),+ ("reply_wrong_scope", "reply", "post", ["insight:write"], status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_messages_and_reply_scopes(self, _name, action, method, scopes, expected_status):+ self._auth_with_pak(scopes)++ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/{action}/"+ if method == "post":+ response = self.client.post(url, {"message": "test reply"}, format="json")+ else:+ response = getattr(self.client, method)(url)+ assert response.status_code == expected_status, f"{_name}: {response.status_code} != {expected_status}"++[email protected](transaction, "on_commit", side_effect=immediate_on_commit)+class TestTicketMessagesAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.EMAIL,+ widget_session_id="test-session",+ distinct_id="user-1",+ status=Status.OPEN,+ anonymous_traits={"name": "Alice", "email": "[email protected]"},+ )+ self.url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/messages/"++ def test_messages_returns_thread_in_order(self, mock_on_commit):+ base = timezone.now()+ # Stamp explicit, strictly-increasing created_at so ordering can't tie on fast DBs.+ for offset, (content, author_type, is_private, author) in enumerate(+ [+ ("Hello from customer", "customer", False, None),+ ("Hi there!", "support", False, self.user),+ ("Internal note", "support", True, self.user),+ ]+ ):+ comment = Comment.objects.create(+ team=self.team,+ created_by=author,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content=content,+ item_context={"author_type": author_type, "is_private": is_private},+ )+ Comment.objects.filter(id=comment.id).update(created_at=base + timedelta(seconds=offset))++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ body = response.json()["results"]+ assert len(body) == 3+ assert body[0]["content"] == "Hello from customer"+ assert body[0]["author_type"] == "customer"+ assert body[0]["author_name"] == "Alice"+ assert body[0]["is_private"] is False+ assert body[1]["content"] == "Hi there!"+ assert body[1]["author_type"] == "support"+ assert body[1]["is_private"] is False+ assert body[2]["content"] == "Internal note"+ assert body[2]["is_private"] is True++ def test_messages_includes_private_notes(self, mock_on_commit):+ Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Secret internal note",+ item_context={"author_type": "support", "is_private": True},+ )++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["is_private"] is True+ assert results[0]["content"] == "Secret internal note"++ def test_messages_excludes_deleted(self, mock_on_commit):+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Visible",+ item_context={"author_type": "customer"},+ )+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Deleted",+ item_context={"author_type": "customer"},+ deleted=True,+ )++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["content"] == "Visible"++ def test_messages_correct_response_shape(self, mock_on_commit):+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="test",+ item_context={"author_type": "customer"},+ )++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ msg = response.json()["results"][0]+ assert set(msg.keys()) == {+ "id",+ "content",+ "rich_content",+ "author_type",+ "author_name",+ "is_private",+ "created_at",+ }++ def test_messages_lookup_by_ticket_number(self, mock_on_commit):+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="msg",+ item_context={"author_type": "customer"},+ )++ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.ticket_number}/messages/"+ response = self.client.get(url)+ assert response.status_code == status.HTTP_200_OK+ assert len(response.json()["results"]) == 1++ @parameterized.expand(+ [+ ("customer_with_name", {"name": "Bob", "email": "[email protected]"}, "customer", "Bob"),+ ("customer_email_fallback", {"email": "[email protected]"}, "customer", "[email protected]"),+ ("customer_default", {}, "customer", "Customer"),+ ("ai_author", {}, "AI", "PostHog Assistant"),+ ("support_without_user", {}, "support", "Support"),+ ]+ )+ def test_messages_author_name_resolution(self, mock_on_commit, _name, traits, author_type, expected_name):+ self.ticket.anonymous_traits = traits+ self.ticket.save(update_fields=["anonymous_traits"])+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="msg",+ item_context={"author_type": author_type},+ )++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"][0]["author_name"] == expected_name++ @parameterized.expand(+ [+ ("real_true", True, True),+ ("string_false_is_not_private", "false", False),+ ("string_true_is_not_private", "true", False),+ ("missing", None, False),+ ]+ )+ def test_messages_is_private_only_exact_true(self, mock_on_commit, _name, stored_value, expected):+ item_context: dict = {"author_type": "support"}+ if stored_value is not None:+ item_context["is_private"] = stored_value+ Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="msg",+ item_context=item_context,+ )++ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"][0]["is_private"] is expected++ def test_messages_cross_team_404(self, mock_on_commit):+ from posthog.models.team import Team++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ other_ticket = Ticket.objects.create_with_number(+ team=other_team,+ channel_source=Channel.WIDGET,+ widget_session_id="other",+ distinct_id="other-user",+ status=Status.NEW,+ )++ url = f"/api/projects/{self.team.id}/conversations/tickets/{other_ticket.id}/messages/"+ response = self.client.get(url)+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_messages_empty_thread(self, mock_on_commit):+ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["results"] == []+ assert body["count"] == 0++ def test_messages_pagination(self, mock_on_commit):+ base = timezone.now()+ for i in range(5):+ comment = Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content=f"msg-{i}",+ item_context={"author_type": "customer"},+ )+ Comment.objects.filter(id=comment.id).update(created_at=base + timedelta(seconds=i))++ response = self.client.get(self.url, {"limit": 2})+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["count"] == 5+ assert len(body["results"]) == 2+ assert body["results"][0]["content"] == "msg-0"+ assert body["next"] is not None++ response = self.client.get(self.url, {"limit": 2, "offset": 4})+ body = response.json()+ assert len(body["results"]) == 1+ assert body["results"][0]["content"] == "msg-4"++[email protected](transaction, "on_commit", side_effect=immediate_on_commit)+class TestTicketReplyAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.team.conversations_enabled = True+ self.team.save()+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.EMAIL,+ widget_session_id="test-session",+ distinct_id="user-1",+ status=Status.OPEN,+ )+ self.url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/reply/"++ @parameterized.expand(+ [+ ("public", False),+ ("private", True),+ ]+ )+ def test_reply_creates_comment(self, mock_on_commit, _name, is_private):+ response = self.client.post(self.url, {"message": "A reply", "is_private": is_private}, format="json")+ assert response.status_code == status.HTTP_201_CREATED+ body = response.json()+ assert body["content"] == "A reply"+ assert body["author_type"] == "support"+ assert body["is_private"] is is_private+ assert body["author_name"] == (self.user.first_name or self.user.email)++ comment = Comment.objects.get(id=body["id"])+ assert comment.created_by == self.user+ assert comment.scope == "conversations_ticket"+ assert comment.item_id == str(self.ticket.id)+ assert comment.item_context == {"author_type": "support", "is_private": is_private}++ def test_reply_defaults_is_private_to_false(self, mock_on_commit):+ response = self.client.post(self.url, {"message": "Hi"}, format="json")+ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["is_private"] is False++ def test_reply_with_rich_content(self, mock_on_commit):+ rich = {"type": "doc", "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hi"}]}]}+ response = self.client.post(self.url, {"message": "Hi", "rich_content": rich}, format="json")+ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["rich_content"] == rich++ @parameterized.expand(+ [+ ("blank", {"message": " "}),+ ("missing", {}),+ ("rich_content_too_large", {"message": "hi", "rich_content": {"x": "y" * 200_000}}),+ ]+ )+ def test_reply_invalid_payload_rejected(self, mock_on_commit, _name, payload):+ response = self.client.post(self.url, payload, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_reply_cross_team_404(self, mock_on_commit):+ from posthog.models.team import Team++ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ other_ticket = Ticket.objects.create_with_number(+ team=other_team,+ channel_source=Channel.WIDGET,+ widget_session_id="other",+ distinct_id="other-user",+ status=Status.NEW,+ )++ url = f"/api/projects/{self.team.id}/conversations/tickets/{other_ticket.id}/reply/"+ response = self.client.post(url, {"message": "hi"}, format="json")+ assert response.status_code == status.HTTP_404_NOT_FOUND++ @parameterized.expand(+ [+ ("public_reply_is_emailed", False, True),+ ("private_note_is_not_emailed", True, False),+ ]+ )+ @patch("products.conversations.backend.signals.send_email_reply")+ def test_reply_fans_out_to_customer_only_when_public(+ self, _name, is_private, expect_delivery, mock_send_email_reply, mock_on_commit+ ):+ # The post_save signal only delivers over email when the ticket is an+ # email channel with email enabled and a sender address.+ self.ticket.email_from = "[email protected]"+ self.ticket.save(update_fields=["email_from"])+ self.team.conversations_settings = {"email_enabled": True}+ self.team.save(update_fields=["conversations_settings"])++ response = self.client.post(self.url, {"message": "Reply body", "is_private": is_private}, format="json")+ assert response.status_code == status.HTTP_201_CREATED++ if expect_delivery:+ mock_send_email_reply.delay.assert_called_once()+ else:+ mock_send_email_reply.delay.assert_not_called()++ @patch("products.conversations.backend.signals.send_email_reply")+ def test_reply_rejected_when_conversations_disabled(self, mock_send_email_reply, mock_on_commit):+ self.team.conversations_enabled = False+ self.team.save()++ response = self.client.post(self.url, {"message": "Hi"}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ # Guard runs before the comment is created, so no fan-out is triggered.+ assert not Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).exists()+ mock_send_email_reply.delay.assert_not_called()++ def test_reply_rich_content_non_json_serializable_rejected(self, mock_on_commit):+ # A non-JSON-serializable value can't arrive over HTTP (the body is already+ # parsed JSON), so validate at the serializer level directly.+ serializer = TicketReplyRequestSerializer(data={"message": "hi", "rich_content": {"amount": Decimal("1.2")}})+ assert not serializer.is_valid()+ assert "rich_content" in serializer.errorsdiff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 96680be9bb66..3a4994a13007 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -13,7 +13,7 @@ from django.utils import timezoneimport structlogfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_viewfrom loginas.utils import is_impersonated_sessionfrom rest_framework import (pagination,@@ -74,6 +74,57 @@ class SuggestReplyErrorSerializer(serializers.Serializer):error_type = serializers.CharField(required=False)+class TicketMessageSerializer(serializers.Serializer):+ """A single message in a ticket thread (output-only)."""++ id = serializers.UUIDField(read_only=True, help_text="Message (comment) UUID.")+ content = serializers.CharField(read_only=True, help_text="Plain-text message body.")+ rich_content = serializers.JSONField(read_only=True, allow_null=True, help_text="TipTap rich content JSON, if any.")+ author_type = serializers.CharField(read_only=True, help_text="One of: customer, support, AI.")+ author_name = serializers.CharField(read_only=True, help_text="Display name of the author.")+ is_private = serializers.BooleanField(+ read_only=True, help_text="True for internal notes not visible to the customer."+ )+ created_at = serializers.DateTimeField(read_only=True)+++class TicketReplyRequestSerializer(serializers.Serializer):+ """Payload for posting a reply or internal note to a ticket."""++ message = serializers.CharField(+ max_length=5000,+ help_text="Reply content in markdown.",+ )+ is_private = serializers.BooleanField(+ default=False,+ help_text=(+ "If true, store as an internal note (not sent to the customer). "+ "If false, the reply is delivered to the customer over the ticket's channel."+ ),+ )+ rich_content = serializers.JSONField(+ required=False,+ allow_null=True,+ help_text="Optional TipTap rich content JSON for formatted messages.",+ )++ def validate_message(self, value: str) -> str:+ if not value or not value.strip():+ raise serializers.ValidationError("Message content is required.")+ return value.strip()++ def validate_rich_content(self, value: object) -> object:+ if value is None:+ return value+ try:+ serialized = json.dumps(value)+ except (TypeError, ValueError) as e:+ raise serializers.ValidationError("Rich content must be JSON-serializable.") from e+ if len(serialized) > 100_000:+ raise serializers.ValidationError("Rich content too large (max 100KB).")+ return value++class ComposeTicketSerializer(serializers.Serializer):recipient_email = serializers.EmailField(help_text="Recipient email address.",@@ -107,7 +158,13 @@ class ComposeTicketSerializer(serializers.Serializer):return value.strip()def validate_rich_content(self, value: object) -> object:- if value is not None and len(json.dumps(value)) > 100_000:+ if value is None:+ return value+ try:+ serialized = json.dumps(value)+ except (TypeError, ValueError) as e:+ raise serializers.ValidationError("Rich content must be JSON-serializable.") from e+ if len(serialized) > 100_000:raise serializers.ValidationError("Rich content too large (max 100KB).")return value@@ -146,6 +203,11 @@ class TicketPagination(pagination.LimitOffsetPagination):max_limit = 1000+class TicketMessagePagination(pagination.LimitOffsetPagination):+ default_limit = 50+ max_limit = 200++MAX_TAG_FILTER_VALUES = 50@@ -248,10 +310,24 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):return None+TICKET_ID_PARAM = OpenApiParameter(+ name="id",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.PATH,+ description="The ticket's UUID or its numeric ticket number.",+)+++@extend_schema_view(+ retrieve=extend_schema(parameters=[TICKET_ID_PARAM]),+ update=extend_schema(parameters=[TICKET_ID_PARAM]),+ partial_update=extend_schema(parameters=[TICKET_ID_PARAM]),+ destroy=extend_schema(parameters=[TICKET_ID_PARAM]),+)class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "ticket"- scope_object_read_actions = ["list", "retrieve", "unread_count"]- scope_object_write_actions = ["create", "update", "partial_update", "patch", "compose"]+ scope_object_read_actions = ["list", "retrieve", "unread_count", "messages"]+ scope_object_write_actions = ["create", "update", "partial_update", "patch", "compose", "reply"]queryset = Ticket.objects.all()serializer_class = TicketSerializerpermission_classes = [IsAuthenticated, APIScopePermission, PostHogFeatureFlagPermission]@@ -976,6 +1052,109 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modreturn Response({"count": count})+ @extend_schema(+ parameters=[TICKET_ID_PARAM],+ responses={200: TicketMessageSerializer(many=True)},+ )+ @action(detail=True, methods=["get"], pagination_class=TicketMessagePagination)+ def messages(self, request, *args, **kwargs):+ """Return the message thread for a ticket, ordered chronologically (paginated)."""+ ticket = self.get_object()++ comments = (+ Comment.objects.filter(+ team_id=self.team_id,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ deleted=False,+ )+ .select_related("created_by")+ .order_by("created_at")+ )++ page = self.paginate_queryset(comments)+ comments_to_serialize = page if page is not None else list(comments)++ message_list = [self._serialize_message(comment, ticket) for comment in comments_to_serialize]+ data = TicketMessageSerializer(message_list, many=True).data++ if page is not None:+ return self.get_paginated_response(data)+ return Response(data)++ def _serialize_message(self, comment: Comment, ticket: Ticket) -> dict:+ item_context = comment.item_context or {}+ author_type = item_context.get("author_type", "customer")++ if comment.created_by:+ author_name = comment.created_by.first_name or comment.created_by.email+ elif author_type == "customer":+ traits = ticket.anonymous_traits or {}+ author_name = traits.get("name") or traits.get("email") or "Customer"+ elif author_type == "AI":+ author_name = "PostHog Assistant"+ else:+ author_name = "Support"++ return {+ "id": comment.id,+ "content": comment.content,+ "rich_content": comment.rich_content,+ "author_type": author_type,+ "author_name": author_name,+ "is_private": item_context.get("is_private") is True,+ "created_at": comment.created_at,+ }++ @extend_schema(+ parameters=[TICKET_ID_PARAM],+ request=TicketReplyRequestSerializer,+ responses={+ 201: OpenApiResponse(response=TicketMessageSerializer),+ },+ )+ @action(+ detail=True,+ methods=["post"],+ pagination_class=None,+ throttle_classes=[ComposeTicketBurstThrottle, ComposeTicketSustainedThrottle],+ )+ def reply(self, request, *args, **kwargs):+ """Post a reply or internal note to a ticket.++ With is_private=false, the reply is delivered to the customer via the+ ticket's channel (email, Slack, Teams, GitHub). With is_private=true,+ the message is stored as an internal note only visible to team members.+ """+ ticket = self.get_object()++ if not self.team.conversations_enabled:+ return Response(+ {"detail": "Conversations is not enabled."},+ status=drf_status.HTTP_400_BAD_REQUEST,+ )++ serializer = TicketReplyRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data++ is_private = data["is_private"]++ comment = Comment.objects.create(+ team=self.team,+ created_by=request.user,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content=data["message"],+ rich_content=data.get("rich_content"),+ item_context={"author_type": "support", "is_private": is_private},+ )++ return Response(+ TicketMessageSerializer(self._serialize_message(comment, ticket)).data,+ status=drf_status.HTTP_201_CREATED,+ )+@extend_schema(request=ComposeTicketSerializer,responses={diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex cd2da6867c08..72269effcc75 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -537,6 +537,49 @@ export interface PatchedTicketApi {tags?: unknown[]}+/**+ * A single message in a ticket thread (output-only).+ */+export interface TicketMessageApi {+ /** Message (comment) UUID. */+ readonly id: string+ /** Plain-text message body. */+ readonly content: string+ /** TipTap rich content JSON, if any. */+ readonly rich_content: unknown+ /** One of: customer, support, AI. */+ readonly author_type: string+ /** Display name of the author. */+ readonly author_name: string+ /** True for internal notes not visible to the customer. */+ readonly is_private: boolean+ readonly created_at: string+}++export interface PaginatedTicketMessageListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: TicketMessageApi[]+}++/**+ * Payload for posting a reply or internal note to a ticket.+ */+export interface TicketReplyRequestApi {+ /**+ * Reply content in markdown.+ * @maxLength 5000+ */+ message: string+ /** If true, store as an internal note (not sent to the customer). If false, the reply is delivered to the customer over the ticket's channel. */+ is_private?: boolean+ /** Optional TipTap rich content JSON for formatted messages. */+ rich_content?: unknown+}+export interface SuggestReplyResponseApi {suggestion: string}@@ -780,6 +823,17 @@ export const ConversationsTicketsListSla = {OnTrack: 'on-track',} as const+export type ConversationsTicketsMessagesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type ConversationsViewsListParams = {/*** Number of results to return per page.diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 8321b2e89377..33cd8fce95d6 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -18,16 +18,20 @@ import type {ConversationApi,ConversationsListParams,ConversationsTicketsListParams,+ ConversationsTicketsMessagesListParams,ConversationsViewsListParams,MessageApi,MessageMinimalApi,PaginatedConversationMinimalListApi,PaginatedTicketListApi,+ PaginatedTicketMessageListApi,PaginatedTicketViewListApi,PatchedConversationApi,PatchedTicketApi,SuggestReplyResponseApi,TicketApi,+ TicketMessageApi,+ TicketReplyRequestApi,TicketViewApi,} from './api.schemas'@@ -377,6 +381,66 @@ export const conversationsTicketsDestroy = async (})}+export const getConversationsTicketsMessagesListUrl = (+ projectId: string,+ id: string,+ params?: ConversationsTicketsMessagesListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/conversations/tickets/${id}/messages/?${stringifiedParams}`+ : `/api/projects/${projectId}/conversations/tickets/${id}/messages/`+}++/**+ * Return the message thread for a ticket, ordered chronologically (paginated).+ */+export const conversationsTicketsMessagesList = async (+ projectId: string,+ id: string,+ params?: ConversationsTicketsMessagesListParams,+ options?: RequestInit+): Promise<PaginatedTicketMessageListApi> => {+ return apiMutator<PaginatedTicketMessageListApi>(getConversationsTicketsMessagesListUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}++export const getConversationsTicketsReplyCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/conversations/tickets/${id}/reply/`+}++/**+ * Post a reply or internal note to a ticket.+ *+ * With is_private=false, the reply is delivered to the customer via the+ * ticket's channel (email, Slack, Teams, GitHub). With is_private=true,+ * the message is stored as an internal note only visible to team members.+ */+export const conversationsTicketsReplyCreate = async (+ projectId: string,+ id: string,+ ticketReplyRequestApi: TicketReplyRequestApi,+ options?: RequestInit+): Promise<TicketMessageApi> => {+ return apiMutator<TicketMessageApi>(getConversationsTicketsReplyCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(ticketReplyRequestApi),+ })+}+export const getConversationsTicketsSuggestReplyCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/conversations/tickets/${id}/suggest_reply/`}diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 3f41a2ccd5e9..a59774a53abe 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -176,6 +176,30 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod}).describe('Serializer mixin that handles tags for objects.')+/**+ * Post a reply or internal note to a ticket.+ *+ * With is_private=false, the reply is delivered to the customer via the+ * ticket's channel (email, Slack, Teams, GitHub). With is_private=true,+ * the message is stored as an internal note only visible to team members.+ */+export const conversationsTicketsReplyCreateBodyMessageMax = 5000++export const conversationsTicketsReplyCreateBodyIsPrivateDefault = false++export const ConversationsTicketsReplyCreateBody = /* @__PURE__ */ zod+ .object({+ message: zod.string().max(conversationsTicketsReplyCreateBodyMessageMax).describe('Reply content in markdown.'),+ is_private: zod+ .boolean()+ .default(conversationsTicketsReplyCreateBodyIsPrivateDefault)+ .describe(+ "If true, store as an internal note (not sent to the customer). If false, the reply is delivered to the customer over the ticket's channel."+ ),+ rich_content: zod.unknown().optional().describe('Optional TipTap rich content JSON for formatted messages.'),+ })+ .describe('Payload for posting a reply or internal note to a ticket.')+/*** Update the status of multiple tickets in a single request.*diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex 977df4ba594c..0d7292e9d8d0 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -89,6 +89,36 @@ tools:- unread_team_count- created_at- updated_at+ conversations-tickets-messages-retrieve:+ operation: conversations_tickets_messages_list+ enabled: true+ scopes:+ - ticket:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Read support ticket messages+ description: >+ Return a support ticket's message thread, ordered chronologically. The response is paginated (default 50,+ max 200 per page) — use the limit and offset query params to page through long threads, and read count/next+ from the response envelope. Includes all messages from the customer, team members, and AI, as well as+ private internal notes. Each message contains author_type, author_name, content, and an is_private flag+ indicating internal notes.+ conversations-tickets-reply-create:+ operation: conversations_tickets_reply_create+ enabled: true+ scopes:+ - ticket:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Reply to support ticket+ description: >+ Post a reply or internal note to a support ticket. IMPORTANT: With is_private=false (the default), the reply+ IS DELIVERED to the customer via the ticket's channel (email, Slack, Teams, or GitHub). Set is_private=true+ to store an internal note visible only to team members.conversations-tickets-retrieve:operation: conversations_tickets_retrieveenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 9d722a8072c4..909752182109 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -953,6 +953,34 @@"readOnlyHint": true}},+ "conversations-tickets-messages-retrieve": {+ "description": "Return a support ticket's message thread, ordered chronologically. The response is paginated (default 50, max 200 per page) — use the limit and offset query params to page through long threads, and read count/next from the response envelope. Includes all messages from the customer, team members, and AI, as well as private internal notes. Each message contains author_type, author_name, content, and an is_private flag indicating internal notes.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Read support ticket messages",+ "title": "Read support ticket messages",+ "required_scopes": ["ticket:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "conversations-tickets-reply-create": {+ "description": "Post a reply or internal note to a support ticket. IMPORTANT: With is_private=false (the default), the reply IS DELIVERED to the customer via the ticket's channel (email, Slack, Teams, or GitHub). Set is_private=true to store an internal note visible only to team members.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Reply to support ticket",+ "title": "Reply to support ticket",+ "required_scopes": ["ticket:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"conversations-tickets-retrieve": {"description": "Get a specific support ticket by ID or ticket number. Returns full ticket details including status, priority, assignee, message count, channel info, person data, and session context.","category": "Conversations",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex fae751e30e2f..6f298c545903 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -969,6 +969,34 @@"readOnlyHint": true}},+ "conversations-tickets-messages-retrieve": {+ "description": "Return a support ticket's message thread, ordered chronologically. The response is paginated (default 50, max 200 per page) — use the limit and offset query params to page through long threads, and read count/next from the response envelope. Includes all messages from the customer, team members, and AI, as well as private internal notes. Each message contains author_type, author_name, content, and an is_private flag indicating internal notes.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Read support ticket messages",+ "title": "Read support ticket messages",+ "required_scopes": ["ticket:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "conversations-tickets-reply-create": {+ "description": "Post a reply or internal note to a support ticket. IMPORTANT: With is_private=false (the default), the reply IS DELIVERED to the customer via the ticket's channel (email, Slack, Teams, or GitHub). Set is_private=true to store an internal note visible only to team members.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Reply to support ticket",+ "title": "Reply to support ticket",+ "required_scopes": ["ticket:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"conversations-tickets-retrieve": {"description": "Get a specific support ticket by ID or ticket number. Returns full ticket details including status, priority, assignee, message count, channel info, person data, and session context.","category": "Conversations",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9da1a475fb64..2299a9275352 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27836,6 +27836,34 @@ export namespace Schemas {results: Ticket[];}+ /**+ * A single message in a ticket thread (output-only).+ */+ export interface TicketMessage {+ /** Message (comment) UUID. */+ readonly id: string;+ /** Plain-text message body. */+ readonly content: string;+ /** TipTap rich content JSON, if any. */+ readonly rich_content: unknown;+ /** One of: customer, support, AI. */+ readonly author_type: string;+ /** Display name of the author. */+ readonly author_name: string;+ /** True for internal notes not visible to the customer. */+ readonly is_private: boolean;+ readonly created_at: string;+ }++ export interface PaginatedTicketMessageList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: TicketMessage[];+ }+/*** Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.*/@@ -41517,6 +41545,21 @@ export namespace Schemas {metadata: TextReprMetadata;}+ /**+ * Payload for posting a reply or internal note to a ticket.+ */+ export interface TicketReplyRequest {+ /**+ * Reply content in markdown.+ * @maxLength 5000+ */+ message: string;+ /** If true, store as an internal note (not sent to the customer). If false, the reply is delivered to the customer over the ticket's channel. */+ is_private?: boolean;+ /** Optional TipTap rich content JSON for formatted messages. */+ rich_content?: unknown;+ }+export interface TopPage {/** Host for the page, if recorded. */host: string;@@ -48244,6 +48287,17 @@ export namespace Schemas {OnTrack: 'on-track',} as const;+ export type ConversationsTicketsMessagesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type ConversationsViewsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex 034b15f04d6e..da714456407e 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 3 enabled ops+ * PostHog API - MCP 5 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -111,7 +111,7 @@ export const ConversationsTicketsListQueryParams = /* @__PURE__ */ zod.object({* Get single ticket and mark as read by team.*/export const ConversationsTicketsRetrieveParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this ticket.'),+ id: zod.string().describe("The ticket's UUID or its numeric ticket number."),project_id: zod.string().describe(@@ -120,7 +120,7 @@ export const ConversationsTicketsRetrieveParams = /* @__PURE__ */ zod.object({})export const ConversationsTicketsPartialUpdateParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this ticket.'),+ id: zod.string().describe("The ticket's UUID or its numeric ticket number."),project_id: zod.string().describe(@@ -157,3 +157,53 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zodtags: zod.array(zod.unknown()).optional(),}).describe('Serializer mixin that handles tags for objects.')++/**+ * Return the message thread for a ticket, ordered chronologically (paginated).+ */+export const ConversationsTicketsMessagesListParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe("The ticket's UUID or its numeric ticket number."),+ 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 ConversationsTicketsMessagesListQueryParams = /* @__PURE__ */ 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.'),+})++/**+ * Post a reply or internal note to a ticket.+ *+ * With is_private=false, the reply is delivered to the customer via the+ * ticket's channel (email, Slack, Teams, GitHub). With is_private=true,+ * the message is stored as an internal note only visible to team members.+ */+export const ConversationsTicketsReplyCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe("The ticket's UUID or its numeric ticket number."),+ 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 conversationsTicketsReplyCreateBodyMessageMax = 5000++export const conversationsTicketsReplyCreateBodyIsPrivateDefault = false++export const ConversationsTicketsReplyCreateBody = /* @__PURE__ */ zod+ .object({+ message: zod.string().max(conversationsTicketsReplyCreateBodyMessageMax).describe('Reply content in markdown.'),+ is_private: zod+ .boolean()+ .default(conversationsTicketsReplyCreateBodyIsPrivateDefault)+ .describe(+ "If true, store as an internal note (not sent to the customer). If false, the reply is delivered to the customer over the ticket's channel."+ ),+ rich_content: zod.unknown().optional().describe('Optional TipTap rich content JSON for formatted messages.'),+ })+ .describe('Payload for posting a reply or internal note to a ticket.')diff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.tsindex 1b548a23626f..925b5744f623 100644--- a/services/mcp/src/tools/generated/conversations.ts+++ b/services/mcp/src/tools/generated/conversations.ts@@ -4,8 +4,12 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {ConversationsTicketsListQueryParams,+ ConversationsTicketsMessagesListParams,+ ConversationsTicketsMessagesListQueryParams,ConversationsTicketsPartialUpdateBody,ConversationsTicketsPartialUpdateParams,+ ConversationsTicketsReplyCreateBody,+ ConversationsTicketsReplyCreateParams,ConversationsTicketsRetrieveParams,} from '@/generated/conversations/api'import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'@@ -65,6 +69,61 @@ const conversationsTicketsList = (): ToolBase<},})+const ConversationsTicketsMessagesRetrieveSchema = ConversationsTicketsMessagesListParams.omit({+ project_id: true,+}).extend(ConversationsTicketsMessagesListQueryParams.shape)++const conversationsTicketsMessagesRetrieve = (): ToolBase<+ typeof ConversationsTicketsMessagesRetrieveSchema,+ Schemas.PaginatedTicketMessageList+> => ({+ name: 'conversations-tickets-messages-retrieve',+ schema: ConversationsTicketsMessagesRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof ConversationsTicketsMessagesRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedTicketMessageList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/conversations/tickets/${encodeURIComponent(String(params.id))}/messages/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return result+ },+})++const ConversationsTicketsReplyCreateSchema = ConversationsTicketsReplyCreateParams.omit({ project_id: true }).extend(+ ConversationsTicketsReplyCreateBody.shape+)++const conversationsTicketsReplyCreate = (): ToolBase<+ typeof ConversationsTicketsReplyCreateSchema,+ Schemas.TicketMessage+> => ({+ name: 'conversations-tickets-reply-create',+ schema: ConversationsTicketsReplyCreateSchema,+ handler: async (context: Context, params: z.infer<typeof ConversationsTicketsReplyCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.message !== undefined) {+ body['message'] = params.message+ }+ if (params.is_private !== undefined) {+ body['is_private'] = params.is_private+ }+ if (params.rich_content !== undefined) {+ body['rich_content'] = params.rich_content+ }+ const result = await context.api.request<Schemas.TicketMessage>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/conversations/tickets/${encodeURIComponent(String(params.id))}/reply/`,+ body,+ })+ return result+ },+})+const ConversationsTicketsRetrieveSchema = ConversationsTicketsRetrieveParams.omit({ project_id: true })const conversationsTicketsRetrieve = (): ToolBase<@@ -146,6 +205,8 @@ const conversationsTicketsUpdate = (): ToolBase<export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'conversations-tickets-list': conversationsTicketsList,+ 'conversations-tickets-messages-retrieve': conversationsTicketsMessagesRetrieve,+ 'conversations-tickets-reply-create': conversationsTicketsReplyCreate,'conversations-tickets-retrieve': conversationsTicketsRetrieve,'conversations-tickets-update': conversationsTicketsUpdate,}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-messages-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-messages-retrieve.jsonnew file mode 100644index 000000000000..f8f7ccef1593--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-messages-retrieve.json@@ -0,0 +1,19 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "The ticket's UUID or its numeric ticket number.",+ "type": "string"+ },+ "limit": {+ "description": "Number of results to return per page.",+ "type": "number"+ },+ "offset": {+ "description": "The initial index from which to return the results.",+ "type": "number"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-reply-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-reply-create.jsonnew file mode 100644index 000000000000..497e8a793864--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-reply-create.json@@ -0,0 +1,24 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "The ticket's UUID or its numeric ticket number.",+ "type": "string"+ },+ "is_private": {+ "default": false,+ "description": "If true, store as an internal note (not sent to the customer). If false, the reply is delivered to the customer over the ticket's channel.",+ "type": "boolean"+ },+ "message": {+ "description": "Reply content in markdown.",+ "maxLength": 5000,+ "type": "string"+ },+ "rich_content": {+ "description": "Optional TipTap rich content JSON for formatted messages."+ }+ },+ "required": ["id", "message"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-retrieve.jsonindex 83bd4796d716..71c3a866dd88 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-retrieve.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-retrieve.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"id": {- "description": "A UUID string identifying this ticket.",+ "description": "The ticket's UUID or its numeric ticket number.","type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.jsonindex c75cbfe9924a..8c04c1e6f155 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"id": {- "description": "A UUID string identifying this ticket.",+ "description": "The ticket's UUID or its numeric ticket number.","type": "string"},"priority": {