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(api): declare response schemas for group and person lookups (#104025)

Thomas Obermüllerd49f665f26d3
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index f32cc1b37690..41b68aa3fd6d 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -8,7 +8,7 @@ from django.utils import timezone
import structlog
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter
+from drf_spectacular.utils import OpenApiParameter, PolymorphicProxySerializer, extend_schema_field, inline_serializer
from opentelemetry import trace
from rest_framework import mixins, request, response, serializers, status, viewsets
from rest_framework.exceptions import NotFound, ValidationError
@@ -23,6 +23,7 @@ from posthog.api.capture import CaptureInternalError, capture_internal
from posthog.api.documentation import extend_schema
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import SerializedGroupActorSerializer, SerializedPersonActorSerializer
from posthog.api.utils import action
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard
@@ -249,6 +250,8 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
class GroupSerializer(serializers.HyperlinkedModelSerializer):
+ group_properties = serializers.DictField(child=serializers.JSONField(), help_text="The group's properties.")
+
class Meta:
model = Group
fields = ["group_type_index", "group_key", "group_properties", "created_at"]
@@ -273,6 +276,47 @@ class CreateGroupSerializer(serializers.ModelSerializer):
fields = ["group_type_index", "group_key", "group_properties"]
+# The action rejects a null value, so the schema lists the JSON types it accepts rather than
+# leaving the field as an untyped blob.
+@extend_schema_field(
+ {
+ "oneOf": [
+ {"type": "string"},
+ {"type": "number"},
+ {"type": "boolean"},
+ {"type": "object"},
+ # Without `items` the zod generator emits a bare `zod.array()`, which does not compile.
+ {"type": "array", "items": {}},
+ ]
+ }
+)
+class GroupPropertyValueField(serializers.JSONField):
+ pass
+
+
+class GroupUpdatePropertyRequestSerializer(serializers.Serializer):
+ key = serializers.CharField(help_text="Name of the property to set.")
+ value = GroupPropertyValueField(help_text="Value to set. Any JSON value other than null.")
+
+
+# The key is `$unset`, which no field name can carry, so the body is declared inline.
+GROUP_DELETE_PROPERTY_REQUEST_SCHEMA = inline_serializer(
+ name="GroupDeleteProperty",
+ fields={"$unset": serializers.CharField(help_text="Name of the property to delete.")},
+)
+
+
+RELATED_ACTORS_SCHEMA = PolymorphicProxySerializer(
+ component_name="RelatedActor",
+ serializers={
+ "person": SerializedPersonActorSerializer,
+ "group": SerializedGroupActorSerializer,
+ },
+ resource_type_field_name="type",
+ many=True,
+)
+
+
class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
scope_object = "group"
# DRF needs a queryset for model/basename resolution, but every action is overridden
@@ -533,7 +577,8 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
"Use for read-only lookups (e.g. resolving a group's display name) that should not have side effects.",
required=False,
),
- ]
+ ],
+ responses={200: FindGroupSerializer},
)
@action(methods=["GET"], detail=False, required_scopes=["group:read"])
def find(self, request: request.Request, **kw) -> response.Response:
@@ -575,7 +620,9 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
description="Specify the key of the group to find",
required=True,
),
- ]
+ ],
+ request=GroupUpdatePropertyRequestSerializer,
+ responses={200: GroupSerializer},
)
@action(methods=["POST"], detail=False, required_scopes=["group:write"])
def update_property(self, request: request.Request, **_kw) -> response.Response:
@@ -657,7 +704,9 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
description="Specify the key of the group to find",
required=True,
),
- ]
+ ],
+ request=GROUP_DELETE_PROPERTY_REQUEST_SCHEMA,
+ responses={200: GroupSerializer},
)
@action(methods=["POST"], detail=False, required_scopes=["group:write"])
def delete_property(self, request: request.Request, **_kw) -> response.Response:
@@ -784,8 +833,8 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
OpenApiParameter(
"group_type_index",
OpenApiTypes.INT,
- description="Specify the group type to find",
- required=True,
+ description="Group type of the actor to find related actors for. Omit when the actor is a person.",
+ required=False,
),
OpenApiParameter(
"id",
@@ -793,7 +842,8 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
description="Specify the id of the user to find groups for",
required=True,
),
- ]
+ ],
+ responses={200: RELATED_ACTORS_SCHEMA},
)
@action(methods=["GET"], detail=False, required_scopes=["group:read"])
def related(self, request: request.Request, pk=None, **kw) -> response.Response:
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx
index 76993f6f526a..e16071cdd37a 100644
--- a/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookWidgetViews.stories.tsx
@@ -406,6 +406,7 @@ const meta: Meta = {
results: recordings,
version: 1,
},
+ '/api/projects/:team_id/groups/find': group,
'/api/environments/:team_id/groups/find': group,
'/api/environments/:team_id/error_tracking/issues/:id/': errorTrackingIssue,
'/api/environments/:team_id/error_tracking/issues/:id/fingerprints/': [],
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index da588d5e27b7..530a1cef11e6 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -44,7 +44,7 @@ from posthog.api.services.flags_service import (
PropertyMatchingVersionConflictError,
batch_evaluate_flag_for_team,
)
-from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
+from posthog.api.shared import SearchMatchTypeSerializerMixin, SerializedPersonActorSerializer, UserBasicSerializer
from posthog.api.utils import action, parse_actor_property_filters
from posthog.cdp.filters import build_behavioral_event_expr
from posthog.clickhouse.query_tagging import Feature, tag_queries
@@ -121,25 +121,8 @@ from products.feature_flags.backend.realtime_targeting import is_realtime_cohort
from products.product_analytics.backend.facade.models import Insight
-# Mirrors SerializedPerson in posthog/hogql_queries/serialized_actors.py.
-# Nullability mirrors the TypedDict: only Optional[...] fields are nullable; matched_recordings
-# and value_at_data_point are always present in the response (always-set keys), even if empty/None.
-class CohortPersonResultSerializer(serializers.Serializer):
- id = serializers.CharField()
- uuid = serializers.UUIDField()
- type = serializers.ChoiceField(choices=["person"])
- name = serializers.CharField()
- distinct_ids = serializers.ListField(child=serializers.CharField())
- properties = serializers.DictField()
- created_at = serializers.DateTimeField(allow_null=True)
- last_seen_at = serializers.DateTimeField(allow_null=True)
- is_identified = serializers.BooleanField(allow_null=True)
- matched_recordings = serializers.ListField(child=serializers.DictField())
- value_at_data_point = serializers.FloatField(allow_null=True)
-
-
class CohortPersonsResponseSerializer(serializers.Serializer):
- results = CohortPersonResultSerializer(many=True)
+ results = SerializedPersonActorSerializer(many=True)
next = serializers.URLField(allow_null=True)
previous = serializers.URLField(allow_null=True)
@@ -642,14 +625,6 @@ class CSVConfig:
GENERIC_ERROR = "An error occurred while processing your CSV file. Please try again or contact support if the problem persists."
-class CohortMinimalSerializer(serializers.ModelSerializer):
- """Minimal serializer for cohort references (e.g., person cohorts endpoint)."""
-
- class Meta:
- model = Cohort
- fields = ["id", "name", "count"]
-
-
@extend_schema_field(CohortFilters) # type: ignore[arg-type]
class CohortFiltersField(serializers.JSONField):
"""Custom JSONField that exposes proper OpenAPI schema for cohort filters."""
diff --git a/posthog/api/person.py b/posthog/api/person.py
index b773f1fff7a6..58fb5646dc3d 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -487,6 +487,20 @@ class PersonPropertiesAtTimeResponseSerializer(serializers.Serializer):
)
+# Not in `posthog/api/cohort.py` because that module cannot be imported here at module level: it
+# reaches back into this one through `posthog/hogql_queries/actors_query_runner.py`.
+class CohortMinimalSerializer(serializers.ModelSerializer):
+ """Minimal serializer for cohort references, read by the person cohorts endpoint."""
+
+ class Meta:
+ model = Cohort
+ fields = ["id", "name", "count"]
+
+
+class PersonCohortsResponseSerializer(serializers.Serializer):
+ results = CohortMinimalSerializer(many=True, help_text="Cohorts the person currently belongs to.")
+
+
_PERSON_ID_PARAMETER = OpenApiParameter(
"id",
OpenApiTypes.STR,
@@ -1364,28 +1378,17 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
description="The person ID or UUID to get cohorts for.",
required=True,
),
- ]
+ ],
+ responses={200: PersonCohortsResponseSerializer},
)
@action(methods=["GET"], detail=False, required_scopes=["person:read", "cohort:read"])
def cohorts(self, request: request.Request, **kwargs) -> response.Response:
- from posthog.api.cohort import CohortMinimalSerializer
-
- team = cast(User, request.user).team
- if not team:
- return response.Response(
- {
- "message": "Could not retrieve team",
- "detail": "Could not validate team associated with user",
- },
- status=400,
- )
-
# Only person.uuid is used below, so skip the distinct-id fetch entirely.
with personhog_caller_tag("persons/cohorts"):
person = get_person_by_pk_or_uuid(self.team_id, request.GET["person_id"], distinct_id_limit=0)
if person is None:
raise NotFound()
- cohort_ids = get_all_cohort_ids_by_person_uuid(str(person.uuid), team)
+ cohort_ids = get_all_cohort_ids_by_person_uuid(str(person.uuid), self.team)
# nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get (IDs from team-scoped ClickHouse query)
cohorts = Cohort.objects.filter(pk__in=cohort_ids, deleted=False)
diff --git a/posthog/api/shared.py b/posthog/api/shared.py
index c928f5f8b602..db505beaf40e 100644
--- a/posthog/api/shared.py
+++ b/posthog/api/shared.py
@@ -334,6 +334,54 @@ class FiltersSerializer(serializers.Serializer):
filter_test_accounts = serializers.BooleanField(required=False)
+# These mirror the TypedDicts in posthog/hogql_queries/serialized_actors.py, so a field added
+# there needs adding here. Only the Optional[...] ones are nullable; the rest are always-set keys.
+#
+# `type` is a const string rather than a single-value ChoiceField, because a ChoiceField emits an
+# enum component and `type` collides as a component name under --fail-on-warn. The decorator must
+# annotate a field class, not a field instance: DRF rebuilds each field from its stored kwargs when
+# the serializer binds, which drops an instance-level annotation and the discriminator with it.
+@extend_schema_field({"type": "string", "const": "person"})
+class _PersonActorTypeField(serializers.CharField):
+ pass
+
+
+@extend_schema_field({"type": "string", "const": "group"})
+class _GroupActorTypeField(serializers.CharField):
+ pass
+
+
+class SerializedActorSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="The person's UUID, or the group's key.")
+ properties = serializers.DictField(child=serializers.JSONField(), help_text="The actor's properties.")
+ created_at = serializers.DateTimeField(allow_null=True, help_text="When the actor was first seen.")
+ matched_recordings = serializers.ListField(
+ child=serializers.DictField(child=serializers.JSONField()),
+ help_text="Recordings that matched the query. Empty unless the endpoint asks for them.",
+ )
+ value_at_data_point = serializers.FloatField(
+ allow_null=True,
+ help_text="The actor's value at the data point it was queried for. Null unless the query computes one.",
+ )
+
+
+class SerializedPersonActorSerializer(SerializedActorSerializer):
+ type = _PersonActorTypeField(help_text="Marks this actor as a person.")
+ uuid = serializers.UUIDField(help_text="The person's UUID. Same value as `id`.")
+ name = serializers.CharField(help_text="Display name, resolved from the person's properties or distinct IDs.")
+ distinct_ids = serializers.ListField(
+ child=serializers.CharField(), help_text="The person's distinct IDs, newest first."
+ )
+ last_seen_at = serializers.DateTimeField(allow_null=True, help_text="When the person was last seen.")
+ is_identified = serializers.BooleanField(allow_null=True, help_text="Whether the person has been identified.")
+
+
+class SerializedGroupActorSerializer(SerializedActorSerializer):
+ type = _GroupActorTypeField(help_text="Marks this actor as a group.")
+ group_key = serializers.CharField(help_text="Key identifying the group within its group type.")
+ group_type_index = serializers.IntegerField(help_text="Index of the group type this group belongs to.")
+
+
class OrganizationNotificationLockSerializer(serializers.Serializer):
setting = serializers.ChoiceField(
choices=sorted(LOCKABLE_NOTIFICATION_SETTINGS),
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 642b4658483e..01f6f51c6efc 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -518,39 +518,51 @@ export interface PatchedAddPersonsToStaticCohortRequestApi {
}
/**
- * * `person` - person
+ * The actor's properties.
*/
-export type CohortPersonResultTypeEnumApi =
- (typeof CohortPersonResultTypeEnumApi)[keyof typeof CohortPersonResultTypeEnumApi]
+export type SerializedPersonActorApiProperties = { [key: string]: unknown }
-export const CohortPersonResultTypeEnumApi = {
- Person: 'person',
-} as const
-
-export type CohortPersonResultApiProperties = { [key: string]: unknown }
-
-export type CohortPersonResultApiMatchedRecordingsItem = { [key: string]: unknown }
+export type SerializedPersonActorApiMatchedRecordingsItem = { [key: string]: unknown }
-export interface CohortPersonResultApi {
+export interface SerializedPersonActorApi {
+ /** The person's UUID, or the group's key. */
id: string
+ /** The actor's properties. */
+ properties: SerializedPersonActorApiProperties
+ /**
+ * When the actor was first seen.
+ * @nullable
+ */
+ created_at: string | null
+ /** Recordings that matched the query. Empty unless the endpoint asks for them. */
+ matched_recordings: SerializedPersonActorApiMatchedRecordingsItem[]
+ /**
+ * The actor's value at the data point it was queried for. Null unless the query computes one.
+ * @nullable
+ */
+ value_at_data_point: number | null
+ /** Marks this actor as a person. */
+ type: 'person'
+ /** The person's UUID. Same value as `id`. */
uuid: string
- type: CohortPersonResultTypeEnumApi
+ /** Display name, resolved from the person's properties or distinct IDs. */
name: string
+ /** The person's distinct IDs, newest first. */
distinct_ids: string[]
- properties: CohortPersonResultApiProperties
- /** @nullable */
- created_at: string | null
- /** @nullable */
+ /**
+ * When the person was last seen.
+ * @nullable
+ */
last_seen_at: string | null
- /** @nullable */
+ /**
+ * Whether the person has been identified.
+ * @nullable
+ */
is_identified: boolean | null
- matched_recordings: CohortPersonResultApiMatchedRecordingsItem[]
- /** @nullable */
- value_at_data_point: number | null
}
export interface CohortPersonsResponseApi {
- results: CohortPersonResultApi[]
+ results: SerializedPersonActorApi[]
/** @nullable */
next: string | null
/** @nullable */
diff --git a/products/groups/frontend/generated/api.schemas.ts b/products/groups/frontend/generated/api.schemas.ts
index 633a2ad8d3fe..8ecb0740057b 100644
--- a/products/groups/frontend/generated/api.schemas.ts
+++ b/products/groups/frontend/generated/api.schemas.ts
@@ -7,6 +7,11 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * The group's properties.
+ */
+export type GroupApiGroupProperties = { [key: string]: unknown }
+
export interface GroupApi {
/**
* @minimum -2147483648
@@ -15,7 +20,8 @@ export interface GroupApi {
group_type_index: number
/** @maxLength 400 */
group_key: string
- group_properties?: unknown
+ /** The group's properties. */
+ group_properties: GroupApiGroupProperties
readonly created_at: string
}
@@ -30,6 +36,140 @@ export interface CreateGroupApi {
group_properties?: unknown
}
+export interface GroupDeletePropertyApi {
+ /** Name of the property to delete. */
+ $unset: string
+}
+
+/**
+ * The group's properties.
+ */
+export type FindGroupApiGroupProperties = { [key: string]: unknown }
+
+export interface FindGroupApi {
+ /**
+ * @minimum -2147483648
+ * @maximum 2147483647
+ */
+ group_type_index: number
+ /** @maxLength 400 */
+ group_key: string
+ /** The group's properties. */
+ group_properties: FindGroupApiGroupProperties
+ readonly created_at: string
+ /** @nullable */
+ readonly notebook: string | null
+}
+
+/**
+ * Marks this actor as a person.
+ */
+export type SerializedPersonActorApiType =
+ (typeof SerializedPersonActorApiType)[keyof typeof SerializedPersonActorApiType]
+
+export const SerializedPersonActorApiType = {
+ Person: 'person',
+} as const
+
+/**
+ * The actor's properties.
+ */
+export type SerializedPersonActorApiProperties = { [key: string]: unknown }
+
+export type SerializedPersonActorApiMatchedRecordingsItem = { [key: string]: unknown }
+
+export interface SerializedPersonActorApi {
+ /** The person's UUID, or the group's key. */
+ id: string
+ /** The actor's properties. */
+ properties: SerializedPersonActorApiProperties
+ /**
+ * When the actor was first seen.
+ * @nullable
+ */
+ created_at: string | null
+ /** Recordings that matched the query. Empty unless the endpoint asks for them. */
+ matched_recordings: SerializedPersonActorApiMatchedRecordingsItem[]
+ /**
+ * The actor's value at the data point it was queried for. Null unless the query computes one.
+ * @nullable
+ */
+ value_at_data_point: number | null
+ /** Marks this actor as a person. */
+ type: SerializedPersonActorApiType
+ /** The person's UUID. Same value as `id`. */
+ uuid: string
+ /** Display name, resolved from the person's properties or distinct IDs. */
+ name: string
+ /** The person's distinct IDs, newest first. */
+ distinct_ids: string[]
+ /**
+ * When the person was last seen.
+ * @nullable
+ */
+ last_seen_at: string | null
+ /**
+ * Whether the person has been identified.
+ * @nullable
+ */
+ is_identified: boolean | null
+}
+
+/**
+ * Marks this actor as a group.
+ */
+export type SerializedGroupActorApiType = (typeof SerializedGroupActorApiType)[keyof typeof SerializedGroupActorApiType]
+
+export const SerializedGroupActorApiType = {
+ Group: 'group',
+} as const
+
+/**
+ * The actor's properties.
+ */
+export type SerializedGroupActorApiProperties = { [key: string]: unknown }
+
+export type SerializedGroupActorApiMatchedRecordingsItem = { [key: string]: unknown }
+
+export interface SerializedGroupActorApi {
+ /** The person's UUID, or the group's key. */
+ id: string
+ /** The actor's properties. */
+ properties: SerializedGroupActorApiProperties
+ /**
+ * When the actor was first seen.
+ * @nullable
+ */
+ created_at: string | null
+ /** Recordings that matched the query. Empty unless the endpoint asks for them. */
+ matched_recordings: SerializedGroupActorApiMatchedRecordingsItem[]
+ /**
+ * The actor's value at the data point it was queried for. Null unless the query computes one.
+ * @nullable
+ */
+ value_at_data_point: number | null
+ /** Marks this actor as a group. */
+ type: SerializedGroupActorApiType
+ /** Key identifying the group within its group type. */
+ group_key: string
+ /** Index of the group type this group belongs to. */
+ group_type_index: number
+}
+
+export type RelatedActorApi = SerializedPersonActorApi | SerializedGroupActorApi
+
+/**
+ * Value to set. Any JSON value other than null.
+ */
+export type GroupUpdatePropertyRequestApiValue = string | number | boolean | { [key: string]: unknown } | unknown[]
+
+export interface GroupUpdatePropertyRequestApi {
+ /** Name of the property to set. */
+ key: string
+ /** Value to set. Any JSON value other than null. */
+ value: GroupUpdatePropertyRequestApiValue
+}
+
export type GroupsListParams = {
/**
* Pagination cursor returned in the `next` URL of a previous response
@@ -86,11 +226,11 @@ export type GroupsFindRetrieveParams = {
skip_create_notebook?: boolean
}
-export type GroupsRelatedRetrieveParams = {
+export type GroupsRelatedListParams = {
/**
- * Specify the group type to find
+ * Group type of the actor to find related actors for. Omit when the actor is a person.
*/
- group_type_index: number
+ group_type_index?: number
/**
* Specify the id of the user to find groups for
*/
diff --git a/products/groups/frontend/generated/api.ts b/products/groups/frontend/generated/api.ts
index 5d21b88ab873..438a74946a04 100644
--- a/products/groups/frontend/generated/api.ts
+++ b/products/groups/frontend/generated/api.ts
@@ -10,32 +10,19 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
CreateGroupApi,
+ FindGroupApi,
GroupApi,
+ GroupDeletePropertyApi,
+ GroupUpdatePropertyRequestApi,
GroupsActivityRetrieveParams,
GroupsDeletePropertyCreateParams,
GroupsFindRetrieveParams,
GroupsListParams,
- GroupsRelatedRetrieveParams,
+ GroupsRelatedListParams,
GroupsUpdatePropertyCreateParams,
+ RelatedActorApi,
} from './api.schemas'
-// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
-type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
-
-type WritableKeys<T> = {
- [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
-}[keyof T]
-
-type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
-type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
-
-type Writable<T> = Pick<T, WritableKeys<T>>
-type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
- ? {
- [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
- }
- : DistributeReadOnlyOverUnions<T>
-
export const getGroupsListUrl = (projectId: string, params: GroupsListParams) => {
const normalizedParams = new URLSearchParams()
@@ -132,15 +119,15 @@ export const getGroupsDeletePropertyCreateUrl = (projectId: string, params: Grou
export const groupsDeletePropertyCreate = async (
projectId: string,
- groupApi: NonReadonly<GroupApi>,
+ groupDeletePropertyApi: GroupDeletePropertyApi,
params: GroupsDeletePropertyCreateParams,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getGroupsDeletePropertyCreateUrl(projectId, params), {
+): Promise<GroupApi> => {
+ return apiMutator<GroupApi>(getGroupsDeletePropertyCreateUrl(projectId, params), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(groupApi),
+ body: JSON.stringify(groupDeletePropertyApi),
})
}
@@ -164,8 +151,8 @@ export const groupsFindRetrieve = async (
projectId: string,
params: GroupsFindRetrieveParams,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getGroupsFindRetrieveUrl(projectId, params), {
+): Promise<FindGroupApi> => {
+ return apiMutator<FindGroupApi>(getGroupsFindRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -182,7 +169,7 @@ export const groupsPropertyValuesRetrieve = async (projectId: string, options?:
})
}
-export const getGroupsRelatedRetrieveUrl = (projectId: string, params: GroupsRelatedRetrieveParams) => {
+export const getGroupsRelatedListUrl = (projectId: string, params: GroupsRelatedListParams) => {
const normalizedParams = new URLSearchParams()
Object.entries(params || {}).forEach(([key, value]) => {
@@ -198,12 +185,12 @@ export const getGroupsRelatedRetrieveUrl = (projectId: string, params: GroupsRel
: `/api/projects/${projectId}/groups/related/`
}
-export const groupsRelatedRetrieve = async (
+export const groupsRelatedList = async (
projectId: string,
- params: GroupsRelatedRetrieveParams,
+ params: GroupsRelatedListParams,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getGroupsRelatedRetrieveUrl(projectId, params), {
+): Promise<RelatedActorApi[]> => {
+ return apiMutator<RelatedActorApi[]>(getGroupsRelatedListUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -227,14 +214,14 @@ export const getGroupsUpdatePropertyCreateUrl = (projectId: string, params: Grou
export const groupsUpdatePropertyCreate = async (
projectId: string,
- groupApi: NonReadonly<GroupApi>,
+ groupUpdatePropertyRequestApi: GroupUpdatePropertyRequestApi,
params: GroupsUpdatePropertyCreateParams,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getGroupsUpdatePropertyCreateUrl(projectId, params), {
+): Promise<GroupApi> => {
+ return apiMutator<GroupApi>(getGroupsUpdatePropertyCreateUrl(projectId, params), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(groupApi),
+ body: JSON.stringify(groupUpdatePropertyRequestApi),
})
}
diff --git a/products/groups/frontend/generated/api.zod.ts b/products/groups/frontend/generated/api.zod.ts
index 5bfcf061857f..c2863b14e608 100644
--- a/products/groups/frontend/generated/api.zod.ts
+++ b/products/groups/frontend/generated/api.zod.ts
@@ -20,30 +20,13 @@ export const GroupsCreateBody = /* @__PURE__ */ zod.object({
group_properties: zod.unknown().optional(),
})
-export const groupsDeletePropertyCreateBodyGroupTypeIndexMin = -2147483648
-export const groupsDeletePropertyCreateBodyGroupTypeIndexMax = 2147483647
-
-export const groupsDeletePropertyCreateBodyGroupKeyMax = 400
-
export const GroupsDeletePropertyCreateBody = /* @__PURE__ */ zod.object({
- group_type_index: zod
- .number()
- .min(groupsDeletePropertyCreateBodyGroupTypeIndexMin)
- .max(groupsDeletePropertyCreateBodyGroupTypeIndexMax),
- group_key: zod.string().max(groupsDeletePropertyCreateBodyGroupKeyMax),
- group_properties: zod.unknown().optional(),
+ $unset: zod.string().describe('Name of the property to delete.'),
})
-export const groupsUpdatePropertyCreateBodyGroupTypeIndexMin = -2147483648
-export const groupsUpdatePropertyCreateBodyGroupTypeIndexMax = 2147483647
-
-export const groupsUpdatePropertyCreateBodyGroupKeyMax = 400
-
export const GroupsUpdatePropertyCreateBody = /* @__PURE__ */ zod.object({
- group_type_index: zod
- .number()
- .min(groupsUpdatePropertyCreateBodyGroupTypeIndexMin)
- .max(groupsUpdatePropertyCreateBodyGroupTypeIndexMax),
- group_key: zod.string().max(groupsUpdatePropertyCreateBodyGroupKeyMax),
- group_properties: zod.unknown().optional(),
+ key: zod.string().describe('Name of the property to set.'),
+ value: zod
+ .union([zod.string(), zod.number(), zod.boolean(), zod.looseObject({}), zod.array(zod.unknown())])
+ .describe('Value to set. Any JSON value other than null.'),
})
diff --git a/products/groups/frontend/logics/groupLogic.ts b/products/groups/frontend/logics/groupLogic.ts
index 09fc488f2c8e..863d3da46fc9 100644
--- a/products/groups/frontend/logics/groupLogic.ts
+++ b/products/groups/frontend/logics/groupLogic.ts
@@ -3,16 +3,15 @@ import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
-import api from 'lib/api'
+import api, { ApiConfig } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
import { capitalizeFirstLetter } from 'lib/utils/strings'
-import { getRelativeNextPath, toParams } from 'lib/utils/url'
+import { getRelativeNextPath } from 'lib/utils/url'
import { Scene } from 'scenes/sceneTypes'
-import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
@@ -28,6 +27,7 @@ import { groupDisplayId } from 'products/persons/frontend/components/GroupActorD
import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'
import type { Noun } from '../../../../frontend/src/models/groupsModel'
import type { GroupType } from '../../../../frontend/src/types'
+import { groupsFindRetrieve } from '../generated/api'
function getGroupEventsQuery(groupTypeIndex: number, groupKey: string): DataTableNode {
return {
@@ -75,7 +75,6 @@ export interface groupLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
- currentTeamId: number | null // teamLogic
backNavigation: GroupBackNavigation | null
backTo: Breadcrumb
breadcrumbs: Breadcrumb[]
@@ -149,10 +148,10 @@ export interface groupLogicActions {
payload?: any
}
loadGroupSuccess: (
- groupData: Group | null,
+ groupData: Group,
payload?: any
) => {
- groupData: Group | null
+ groupData: Group
payload?: any
}
resetGroupEventsQuery: () => {
@@ -180,11 +179,11 @@ export interface groupLogicMeta {
groupKey: string
) => boolean
groupTypeName: (
- aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun,
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun, // groupsModel
groupTypeIndex: number
) => string
groupTypeNamePlural: (
- aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun,
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun, // groupsModel
groupTypeIndex: number
) => string
groupType: (groupTypes: Map<GroupTypeIndex, GroupType>, groupTypeIndex: number) => string | null
@@ -221,7 +220,7 @@ export interface groupLogicMeta {
) => boolean
backNavigation: (searchParams: Record<string, any>) => GroupBackNavigation | null
backTo: (
- aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun,
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun, // groupsModel
groupTypeIndex: number,
backNavigation: GroupBackNavigation | null
) => Breadcrumb
@@ -247,14 +246,7 @@ export const groupLogic = kea<groupLogicType>([
path((key) => ['scenes', 'groups', 'groupLogic', key]),
connect(() => ({
actions: [groupsModel, ['createDetailDashboard']],
- values: [
- teamLogic,
- ['currentTeamId'],
- groupsModel,
- ['groupTypes', 'aggregationLabel'],
- featureFlagLogic,
- ['featureFlags'],
- ],
+ values: [groupsModel, ['groupTypes', 'aggregationLabel'], featureFlagLogic, ['featureFlags']],
})),
actions(() => ({
setGroupData: (group: Group) => ({ group }),
@@ -264,17 +256,20 @@ export const groupLogic = kea<groupLogicType>([
editProperty: (key: string, newValue?: string | number | boolean | null) => ({ key, newValue }),
deleteProperty: (key: string) => ({ key }),
})),
- loaders(({ values, props }) => ({
+ loaders(({ props }) => ({
groupData: [
null as Group | null,
{
- loadGroup: async () => {
- const params = { group_type_index: props.groupTypeIndex, group_key: props.groupKey }
- const url = `api/environments/${values.currentTeamId}/groups/find?${toParams(params)}`
- // groupsFindRetrieve returns Promise<void> because the endpoint declares no
- // response schema, so it cannot type the Group this loader returns.
- // nosemgrep: prefer-codegen-api
- return await api.get(url)
+ loadGroup: async (): Promise<Group> => {
+ // The generated parameter is named projectId because OpenAPI renders the
+ // path segment as {project_id}, but the groups routes register on team_id, so
+ // this takes a team id. A project id resolves the wrong environment.
+ const group = await groupsFindRetrieve(String(ApiConfig.getCurrentTeamId()), {
+ group_type_index: props.groupTypeIndex,
+ group_key: props.groupKey,
+ })
+ // Group narrows group_type_index to the five indexes a team can have.
+ return { ...group, group_type_index: group.group_type_index as GroupTypeIndex }
},
},
],
diff --git a/products/groups/frontend/logics/relatedGroupsLogic.ts b/products/groups/frontend/logics/relatedGroupsLogic.ts
index 9daaab67a104..c41d084402b6 100644
--- a/products/groups/frontend/logics/relatedGroupsLogic.ts
+++ b/products/groups/frontend/logics/relatedGroupsLogic.ts
@@ -91,8 +91,8 @@ export const relatedGroupsLogic = kea<relatedGroupsLogicType>([
group_type_index: props.groupTypeIndex,
id: props.id,
})}`
- // groupsRelatedRetrieve returns Promise<void> because the endpoint declares no
- // response schema, so it cannot type the ActorType list this loader returns.
+ // groupsRelatedList returns RelatedActorApi, which ActorType cannot hold:
+ // ~/types has is_identified non-nullable and distinct_ids optional.
// nosemgrep: prefer-codegen-api
return await api.get(url)
},
diff --git a/products/persons/frontend/components/PersonCohorts.tsx b/products/persons/frontend/components/PersonCohorts.tsx
index 87fd3f4d577f..452cda4ba6ca 100644
--- a/products/persons/frontend/components/PersonCohorts.tsx
+++ b/products/persons/frontend/components/PersonCohorts.tsx
@@ -5,8 +5,7 @@ import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { Link } from 'lib/lemon-ui/Link'
import { urls } from 'scenes/urls'
-import { CohortType } from '~/types'
-
+import type { CohortMinimalApi } from '../generated/api.schemas'
import { personsLogic } from '../logics/personsLogic'
export function PersonCohorts(): JSX.Element {
@@ -17,7 +16,7 @@ export function PersonCohorts(): JSX.Element {
loadCohorts()
}, [person, loadCohorts])
- const columns: LemonTableColumns<CohortType> = [
+ const columns: LemonTableColumns<CohortMinimalApi> = [
{
title: 'Name',
dataIndex: 'name',
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index c2ea39330802..8e2ccbfe18a8 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -329,6 +329,29 @@ export interface PersonBulkDeleteResponseApi {
deletion_errors?: PersonBulkDeleteResponseApiDeletionErrorsItem[]
}
+/**
+ * Minimal serializer for cohort references, read by the person cohorts endpoint.
+ */
+export interface CohortMinimalApi {
+ readonly id: number
+ /**
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null
+ /**
+ * @minimum -2147483648
+ * @maximum 2147483647
+ * @nullable
+ */
+ count?: number | null
+}
+
+export interface PersonCohortsResponseApi {
+ /** Cohorts the person currently belongs to. */
+ results: CohortMinimalApi[]
+}
+
export interface AsyncDeletionStatusApi {
/** The UUID of the person whose events are queued for deletion. */
person_uuid: string
diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.ts
index ac31a8dff745..574560c8381a 100644
--- a/products/persons/frontend/generated/api.ts
+++ b/products/persons/frontend/generated/api.ts
@@ -15,6 +15,7 @@ import type {
PatchedPersonRecordApi,
PersonBulkDeleteRequestApi,
PersonBulkDeleteResponseApi,
+ PersonCohortsResponseApi,
PersonDeletePropertyRequestApi,
PersonPropertiesAtTimeResponseApi,
PersonRecordApi,
@@ -601,8 +602,8 @@ export const personsCohortsRetrieve = async (
projectId: string,
params: PersonsCohortsRetrieveParams,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getPersonsCohortsRetrieveUrl(projectId, params), {
+): Promise<PersonCohortsResponseApi> => {
+ return apiMutator<PersonCohortsResponseApi>(getPersonsCohortsRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/persons/frontend/logics/personsLogic.tsx b/products/persons/frontend/logics/personsLogic.tsx
index be16dd510f5c..678b04c24dc2 100644
--- a/products/persons/frontend/logics/personsLogic.tsx
+++ b/products/persons/frontend/logics/personsLogic.tsx
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { decodeParams, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
-import api, { CountedPaginatedResponse } from 'lib/api'
+import api, { ApiConfig, CountedPaginatedResponse } from 'lib/api'
import { TriggerExportProps } from 'lib/components/ExportButton/exporter'
import { convertPropertyGroupToProperties, isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'
import { FEATURE_FLAGS, PERSON_DISPLAY_NAME_COLUMN_NAME } from 'lib/constants'
@@ -28,7 +28,6 @@ import {
ActivityScope,
AnyPropertyFilter,
Breadcrumb,
- CohortType,
ExporterFormat,
PersonListParams,
PersonPropertyFilter,
@@ -39,6 +38,8 @@ import type { TeamPublicType, TeamType } from '~/types'
import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from 'products/customer_analytics/frontend/constants'
+import { personsCohortsRetrieve } from '../generated/api'
+import type { CohortMinimalApi } from '../generated/api.schemas'
import {
asDisplay,
coercePropertyValue,
@@ -128,7 +129,7 @@ export interface personsLogicValues {
| 'https://posthog.com/docs/api/persons'
breadcrumbs: Breadcrumb[]
cohortId: number | 'new' | undefined
- cohorts: CohortType[] | null
+ cohorts: CohortMinimalApi[] | null
cohortsLoading: boolean
currentTab: PersonsTabType
defaultTab: PersonsTabType.PROFILE | PersonsTabType.PROPERTIES
@@ -186,10 +187,10 @@ export interface personsLogicActions {
errorObject?: any
}
loadCohortsSuccess: (
- cohorts: CohortType[] | null,
+ cohorts: CohortMinimalApi[] | null,
payload?: any
) => {
- cohorts: CohortType[] | null
+ cohorts: CohortMinimalApi[] | null
payload?: any
}
loadPerson: (id: string) => {
@@ -480,16 +481,17 @@ export const personsLogic = kea<personsLogicType>([
},
],
cohorts: [
- null as CohortType[] | null,
+ null as CohortMinimalApi[] | null,
{
- loadCohorts: async (): Promise<CohortType[] | null> => {
+ loadCohorts: async (): Promise<CohortMinimalApi[] | null> => {
if (!values.person?.id) {
return null
}
- // personsCohortsRetrieve returns Promise<void> because the endpoint declares no
- // response schema, so it cannot type the CohortType list this loader returns.
- // nosemgrep: prefer-codegen-api
- const response = await api.get(`api/person/cohorts/?person_id=${values.person?.id}`)
+ // projectId takes a team id here: the persons routes register on
+ // team_id even though OpenAPI renders the segment as {project_id}.
+ const response = await personsCohortsRetrieve(String(ApiConfig.getCurrentTeamId()), {
+ person_id: String(values.person.id),
+ })
return response.results
},
},
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f218583f4764..148e0047f4d9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19822,40 +19822,80 @@ export namespace Schemas {
_create_static_person_ids?: string[];
}
- export type CohortPersonResultProperties = { [key: string]: unknown };
-
- export type CohortPersonResultMatchedRecordingsItem = { [key: string]: unknown };
+ /**
+ * Minimal serializer for cohort references, read by the person cohorts endpoint.
+ */
+ export interface CohortMinimal {
+ readonly id: number;
+ /**
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null;
+ /**
+ * @minimum -2147483648
+ * @maximum 2147483647
+ * @nullable
+ */
+ count?: number | null;
+ }
/**
- * * `person` - person
+ * Marks this actor as a person.
*/
- export type CohortPersonResultTypeEnum = typeof CohortPersonResultTypeEnum[keyof typeof CohortPersonResultTypeEnum];
+ export type SerializedPersonActorType = typeof SerializedPersonActorType[keyof typeof SerializedPersonActorType];
- export const CohortPersonResultTypeEnum = {
+ export const SerializedPersonActorType = {
Person: 'person',
} as const;
- export interface CohortPersonResult {
+ /**
+ * The actor's properties.
+ */
+ export type SerializedPersonActorProperties = { [key: string]: unknown };
+
+ export type SerializedPersonActorMatchedRecordingsItem = { [key: string]: unknown };
+
+ export interface SerializedPersonActor {
+ /** The person's UUID, or the group's key. */
id: string;
+ /** The actor's properties. */
+ properties: SerializedPersonActorProperties;
+ /**
+ * When the actor was first seen.
+ * @nullable
+ */
+ created_at: string | null;
+ /** Recordings that matched the query. Empty unless the endpoint asks for them. */
+ matched_recordings: SerializedPersonActorMatchedRecordingsItem[];
+ /**
+ * The actor's value at the data point it was queried for. Null unless the query computes one.
+ * @nullable
+ */
+ value_at_data_point: number | null;
+ /** Marks this actor as a person. */
+ type: SerializedPersonActorType;
+ /** The person's UUID. Same value as `id`. */
uuid: string;
- type: CohortPersonResultTypeEnum;
+ /** Display name, resolved from the person's properties or distinct IDs. */
name: string;
+ /** The person's distinct IDs, newest first. */
distinct_ids: string[];
- properties: CohortPersonResultProperties;
- /** @nullable */
- created_at: string | null;
- /** @nullable */
+ /**
+ * When the person was last seen.
+ * @nullable
+ */
last_seen_at: string | null;
- /** @nullable */
+ /**
+ * Whether the person has been identified.
+ * @nullable
+ */
is_identified: boolean | null;
- matched_recordings: CohortPersonResultMatchedRecordingsItem[];
- /** @nullable */
- value_at_data_point: number | null;
}
export interface CohortPersonsResponse {
- results: CohortPersonResult[];
+ results: SerializedPersonActor[];
/** @nullable */
next: string | null;
/** @nullable */
@@ -45358,6 +45398,26 @@ export namespace Schemas {
add_images_to_comment_on_pr?: boolean;
}
+ /**
+ * The group's properties.
+ */
+ export type FindGroupGroupProperties = { [key: string]: unknown };
+
+ export interface FindGroup {
+ /**
+ * @minimum -2147483648
+ * @maximum 2147483647
+ */
+ group_type_index: number;
+ /** @maxLength 400 */
+ group_key: string;
+ /** The group's properties. */
+ group_properties: FindGroupGroupProperties;
+ readonly created_at: string;
+ /** @nullable */
+ readonly notebook: string | null;
+ }
+
export interface FlagValueItem {
name: unknown;
}
@@ -46501,6 +46561,11 @@ export namespace Schemas {
Symbol: 'symbol',
} as const;
+ /**
+ * The group's properties.
+ */
+ export type GroupGroupProperties = { [key: string]: unknown };
+
export interface Group {
/**
* @minimum -2147483648
@@ -46509,10 +46574,16 @@ export namespace Schemas {
group_type_index: number;
/** @maxLength 400 */
group_key: string;
- group_properties?: unknown;
+ /** The group's properties. */
+ group_properties: GroupGroupProperties;
readonly created_at: string;
}
+ export interface GroupDeleteProperty {
+ /** Name of the property to delete. */
+ $unset: string;
+ }
+
export interface GroupType {
readonly group_type: string;
readonly group_type_index: number;
@@ -46534,6 +46605,18 @@ export namespace Schemas {
created_at?: string | null;
}
+ /**
+ * Value to set. Any JSON value other than null.
+ */
+ export type GroupUpdatePropertyRequestValue = string | number | boolean | { [key: string]: unknown } | unknown[];
+
+ export interface GroupUpdatePropertyRequest {
+ /** Name of the property to set. */
+ key: string;
+ /** Value to set. Any JSON value other than null. */
+ value: GroupUpdatePropertyRequestValue;
+ }
+
/**
* Filter definition for the metric. Two shapes are accepted, discriminated by an optional `source` key.
*
@@ -76092,6 +76175,11 @@ export namespace Schemas {
deletion_errors?: PersonBulkDeleteResponseDeletionErrorsItem[];
}
+ export interface PersonCohortsResponse {
+ /** Cohorts the person currently belongs to. */
+ results: CohortMinimal[];
+ }
+
export interface PersonDeletePropertyRequest {
/** A property key, or a list of property keys, to remove from this person. */
$unset: string | string[];
@@ -82301,6 +82389,50 @@ export namespace Schemas {
Redshift: 'Redshift',
} as const;
+ /**
+ * Marks this actor as a group.
+ */
+ export type SerializedGroupActorType = typeof SerializedGroupActorType[keyof typeof SerializedGroupActorType];
+
+
+ export const SerializedGroupActorType = {
+ Group: 'group',
+ } as const;
+
+ /**
+ * The actor's properties.
+ */
+ export type SerializedGroupActorProperties = { [key: string]: unknown };
+
+ export type SerializedGroupActorMatchedRecordingsItem = { [key: string]: unknown };
+
+ export interface SerializedGroupActor {
+ /** The person's UUID, or the group's key. */
+ id: string;
+ /** The actor's properties. */
+ properties: SerializedGroupActorProperties;
+ /**
+ * When the actor was first seen.
+ * @nullable
+ */
+ created_at: string | null;
+ /** Recordings that matched the query. Empty unless the endpoint asks for them. */
+ matched_recordings: SerializedGroupActorMatchedRecordingsItem[];
+ /**
+ * The actor's value at the data point it was queried for. Null unless the query computes one.
+ * @nullable
+ */
+ value_at_data_point: number | null;
+ /** Marks this actor as a group. */
+ type: SerializedGroupActorType;
+ /** Key identifying the group within its group type. */
+ group_key: string;
+ /** Index of the group type this group belongs to. */
+ group_type_index: number;
+ }
+
+ export type RelatedActor = SerializedPersonActor | SerializedGroupActor;
+
export interface RelationshipReject {
/** Why the proposal is rejected. Persisted so it is never re-proposed. */
rejection_reason?: string;
@@ -106060,11 +106192,11 @@ export namespace Schemas {
skip_create_notebook?: boolean;
};
- export type GroupsRelatedRetrieveParams = {
+ export type GroupsRelatedListParams = {
/**
- * Specify the group type to find
+ * Group type of the actor to find related actors for. Omit when the actor is a person.
*/
- group_type_index: number;
+ group_type_index?: number;
/**
* Specify the id of the user to find groups for
*/
diff --git a/services/mcp/src/tools/generated/persons.ts b/services/mcp/src/tools/generated/persons.ts
index 1b9dcb834a3e..3adbe12b2cfa 100644
--- a/services/mcp/src/tools/generated/persons.ts
+++ b/services/mcp/src/tools/generated/persons.ts
@@ -47,12 +47,15 @@ const PersonsCohortsRetrieveSchema = () => {
return PersonsCohortsRetrieveQueryParams.omit({ format: true })
}
-const personsCohortsRetrieve = (): ToolBase<ReturnType<typeof PersonsCohortsRetrieveSchema>, unknown> => ({
+const personsCohortsRetrieve = (): ToolBase<
+ ReturnType<typeof PersonsCohortsRetrieveSchema>,
+ Schemas.PersonCohortsResponse
+> => ({
name: 'persons-cohorts-retrieve',
schema: PersonsCohortsRetrieveSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof PersonsCohortsRetrieveSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas.PersonCohortsResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/persons/cohorts/`,
query: {