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(persons): set several person properties in one request (#125379)

Meikel Ratzf73c91f773d1
diff --git a/posthog/api/person.py b/posthog/api/person.py
index f7ca7ac49bdb..765df3317c4f 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -1,4 +1,5 @@
import re
+import json
import uuid
import builtins
import dataclasses
@@ -219,13 +220,29 @@ class PersonsDeleteSustainedThrottle(PersonalApiKeyRateThrottle):
class PersonUpdatePropertyRequestSerializer(serializers.Serializer):
- key = serializers.CharField(help_text="The property key to set.")
- value = serializers.JSONField(help_text="The property value. Can be a string, number, boolean, or object.")
+ key = serializers.CharField(
+ required=False, help_text="The property key to set. Pair it with 'value' to set one property."
+ )
+ value = serializers.JSONField(
+ required=False, help_text="The property value. Can be a string, number, boolean, or object."
+ )
+ properties = serializers.DictField(
+ required=False,
+ child=serializers.JSONField(),
+ help_text=(
+ "Property keys and values to set together, instead of 'key' and 'value'. "
+ "One request sets up to 1000 properties and emits a single $set event."
+ ),
+ )
-# Matches the cap on the persons bulk-delete endpoint; also keeps the resulting
-# capture event safely under the ~1 MB Kafka message limit.
-MAX_UNSET_KEYS_PER_REQUEST = 1000
+# Matches the cap on the persons bulk-delete endpoint.
+MAX_PROPERTY_KEYS_PER_REQUEST = 1000
+
+# Capture refuses an event over the ~1 MB Kafka message limit, and _set_properties
+# discards that failure, so an oversized request would answer 202 having written
+# nothing. The headroom covers the event envelope around the properties.
+MAX_PROPERTIES_PAYLOAD_BYTES = 900_000
@extend_schema_field(
@@ -236,7 +253,7 @@ MAX_UNSET_KEYS_PER_REQUEST = 1000
"type": "array",
"items": {"type": "string", "minLength": 1},
"minItems": 1,
- "maxItems": MAX_UNSET_KEYS_PER_REQUEST,
+ "maxItems": MAX_PROPERTY_KEYS_PER_REQUEST,
},
]
}
@@ -252,7 +269,7 @@ class PersonDeletePropertyRequestSerializer(serializers.Serializer):
fields = super().get_fields()
# The handler reads validated_data["$unset"], so the field name must include the $ prefix.
fields["$unset"] = UnsetPropertyKeysField(
- max_items=MAX_UNSET_KEYS_PER_REQUEST,
+ max_items=MAX_PROPERTY_KEYS_PER_REQUEST,
help_text="A property key, or a list of property keys, to remove from this person.",
)
return fields
@@ -1461,31 +1478,52 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
@extend_schema(request=PersonUpdatePropertyRequestSerializer, parameters=[_PERSON_ID_PARAMETER])
@action(methods=["POST"], detail=True, required_scopes=["person:write"])
def update_property(self, request: request.Request, pk=None, **kwargs) -> response.Response:
- if "value" not in request.data:
- return Response(
- {
- "attr": "value",
- "code": "This field is required.",
- "detail": "required",
- "type": "validation_error",
- },
- status=400,
+ properties = request.data.get("properties")
+ if properties is None:
+ if "value" not in request.data:
+ return Response(
+ {
+ "attr": "value",
+ "code": "This field is required.",
+ "detail": "required",
+ "type": "validation_error",
+ },
+ status=400,
+ )
+ if request.data.get("key") is None:
+ return Response(
+ {
+ "attr": "key",
+ "code": "This field is required.",
+ "detail": "required",
+ "type": "validation_error",
+ },
+ status=400,
+ )
+ properties = {request.data["key"]: request.data["value"]}
+ elif not isinstance(properties, dict) or not properties:
+ raise ValidationError(
+ {"properties": "Provide 'properties' as a non-empty object of property keys to values."}
)
- if request.data.get("key") is None:
- return Response(
+ elif len(properties) > MAX_PROPERTY_KEYS_PER_REQUEST:
+ raise ValidationError(
+ {"properties": f"Set at most {MAX_PROPERTY_KEYS_PER_REQUEST} properties in one request."}
+ )
+
+ payload_size = len(json.dumps(properties, default=str).encode())
+ if payload_size > MAX_PROPERTIES_PAYLOAD_BYTES:
+ raise ValidationError(
{
- "attr": "key",
- "code": "This field is required.",
- "detail": "required",
- "type": "validation_error",
- },
- status=400,
+ "properties": f"Property values total {payload_size} bytes, over the "
+ f"{MAX_PROPERTIES_PAYLOAD_BYTES} byte limit for one request. Send them in smaller batches."
+ }
)
- key = request.data["key"]
+
non_writable = self._get_non_writable_person_properties(request)
- if key in non_writable:
- raise ValidationError(f'You do not have write access to the property "{key}".')
- self._set_properties({key: request.data["value"]}, request.user)
+ for key in properties:
+ if key in non_writable:
+ raise ValidationError(f'You do not have write access to the property "{key}".')
+ self._set_properties(properties, request.user)
return Response(status=202)
@validated_request(PersonDeletePropertyRequestSerializer, parameters=[_PERSON_ID_PARAMETER])
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 96b6941202bd..199b7283414b 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -1467,8 +1467,14 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.validation_error_response("required", "This field is required.", "properties"),
)
+ @parameterized.expand(
+ [
+ ("key_and_value", {"key": "foo", "value": "bar"}, {"foo": "bar"}),
+ ("properties_object", {"properties": {"foo": "bar", "baz": 1}}, {"foo": "bar", "baz": 1}),
+ ]
+ )
@mock.patch("posthog.api.person.capture_internal")
- def test_new_update_single_person_property(self, mock_capture) -> None:
+ def test_new_update_person_properties(self, _name, payload, expected, mock_capture) -> None:
person = _create_person(
team=self.team,
distinct_ids=["some_distinct_id"],
@@ -1476,8 +1482,9 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
immediate=True,
)
- self.client.post(f"/api/person/{person.uuid}/update_property", {"key": "foo", "value": "bar"})
+ response = self.client.post(f"/api/person/{person.uuid}/update_property", payload, format="json")
+ self.assertEqual(response.status_code, 202)
mock_capture.assert_called_once_with(
token=self.team.api_token,
event_name="$set",
@@ -1485,11 +1492,50 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
distinct_id="some_distinct_id",
timestamp=mock.ANY,
properties={
- "$set": {"foo": "bar"},
+ "$set": expected,
},
process_person_profile=True,
)
+ @mock.patch("posthog.api.person.capture_internal")
+ def test_update_person_properties_rejects_an_oversized_payload(self, mock_capture) -> None:
+ person = _create_person(
+ team=self.team,
+ distinct_ids=["some_distinct_id"],
+ properties={"$browser": "whatever"},
+ immediate=True,
+ )
+
+ response = self.client.post(
+ f"/api/person/{person.uuid}/update_property",
+ {"properties": {f"key_{i}": "x" * 2000 for i in range(500)}},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, 400)
+ mock_capture.assert_not_called()
+
+ @mock.patch("posthog.api.person.PersonViewSet._get_non_writable_person_properties")
+ def test_update_person_properties_rejects_a_non_writable_key_anywhere_in_the_object(
+ self, mock_non_writable
+ ) -> None:
+ mock_non_writable.return_value = {"locked"}
+ person = _create_person(
+ team=self.team,
+ distinct_ids=["some_distinct_id"],
+ properties={"$browser": "whatever"},
+ immediate=True,
+ )
+
+ response = self.client.post(
+ f"/api/person/{person.uuid}/update_property",
+ {"properties": {"writable": "ok", "locked": "nope"}},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("locked", response.json()["detail"])
+
@parameterized.expand(
[
("single_key", "foo", ["foo"]),
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index 86e45a155586..e20398eb3c82 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -3934,11 +3934,18 @@ export interface PersonSplitResponseApi {
success: boolean
}
+/**
+ * Property keys and values to set together, instead of 'key' and 'value'. One request sets up to 1000 properties and emits a single $set event.
+ */
+export type PersonUpdatePropertyRequestApiProperties = { [key: string]: unknown }
+
export interface PersonUpdatePropertyRequestApi {
- /** The property key to set. */
- key: string
+ /** The property key to set. Pair it with 'value' to set one property. */
+ key?: string
/** The property value. Can be a string, number, boolean, or object. */
- value: unknown
+ value?: unknown
+ /** Property keys and values to set together, instead of 'key' and 'value'. One request sets up to 1000 properties and emits a single $set event. */
+ properties?: PersonUpdatePropertyRequestApiProperties
}
export interface PersonBulkDeleteRequestApi {
diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.ts
index 54ea1a8dd2da..a3d8c54a6448 100644
--- a/products/persons/frontend/generated/api.ts
+++ b/products/persons/frontend/generated/api.ts
@@ -439,7 +439,7 @@ export const getPersonsUpdatePropertyCreateUrl = (
export const personsUpdatePropertyCreate = async (
projectId: string,
id: string,
- personUpdatePropertyRequestApi: PersonUpdatePropertyRequestApi,
+ personUpdatePropertyRequestApi?: PersonUpdatePropertyRequestApi,
params?: PersonsUpdatePropertyCreateParams,
options?: RequestInit
): Promise<void> => {
diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.ts
index 27464741a5e7..c7765f47cc8e 100644
--- a/products/persons/frontend/generated/api.zod.ts
+++ b/products/persons/frontend/generated/api.zod.ts
@@ -83,8 +83,14 @@ export const PersonsSplitCreateBody = /* @__PURE__ */ zod.object({
* This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.
*/
export const PersonsUpdatePropertyCreateBody = /* @__PURE__ */ zod.object({
- key: zod.string().describe('The property key to set.'),
- value: zod.unknown().describe('The property value. Can be a string, number, boolean, or object.'),
+ key: zod.string().optional().describe("The property key to set. Pair it with 'value' to set one property."),
+ value: zod.unknown().optional().describe('The property value. Can be a string, number, boolean, or object.'),
+ properties: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ "Property keys and values to set together, instead of 'key' and 'value'. One request sets up to 1000 properties and emits a single $set event."
+ ),
})
/**
diff --git a/products/persons/mcp/tools.yaml b/products/persons/mcp/tools.yaml
index 7236d12a9a6a..c2e88d14cf68 100644
--- a/products/persons/mcp/tools.yaml
+++ b/products/persons/mcp/tools.yaml
@@ -101,10 +101,11 @@ tools:
readOnly: false
destructive: false
idempotent: true
- title: Set person property
+ title: Set person properties
description: >
- Set a single property on a person. The property is updated asynchronously via the event pipeline ($set).
- Returns 202 Accepted.
+ Set properties on a person. Pass key and value for one property, or properties for up to 1000 in a single
+ request, which is one call and one $set event instead of one call per property. Properties are updated
+ asynchronously via the event pipeline ($set). Returns 202 Accepted.
exclude_params:
- format
persons-retrieve:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 96227a34d3d8..8620772f55db 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11448,11 +11448,11 @@
}
},
"persons-property-set": {
- "description": "Set a single property on a person. The property is updated asynchronously via the event pipeline ($set). Returns 202 Accepted.",
+ "description": "Set properties on a person. Pass key and value for one property, or properties for up to 1000 in a single request, which is one call and one $set event instead of one call per property. Properties are updated asynchronously via the event pipeline ($set). Returns 202 Accepted.",
"category": "Persons",
"feature": "persons",
- "summary": "Set person property",
- "title": "Set person property",
+ "summary": "Set person properties",
+ "title": "Set person properties",
"required_scopes": ["person:write"],
"api_operations": ["POST /api/projects/{project_id}/persons/{id}/update_property/"],
"annotations": {
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 5c94a4f5f855..3fdf93356762 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -12092,11 +12092,11 @@
}
},
"persons-property-set": {
- "description": "Set a single property on a person. The property is updated asynchronously via the event pipeline ($set). Returns 202 Accepted.",
+ "description": "Set properties on a person. Pass key and value for one property, or properties for up to 1000 in a single request, which is one call and one $set event instead of one call per property. Properties are updated asynchronously via the event pipeline ($set). Returns 202 Accepted.",
"category": "Persons",
"feature": "persons",
- "summary": "Set person property",
- "title": "Set person property",
+ "summary": "Set person properties",
+ "title": "Set person properties",
"required_scopes": ["person:write"],
"api_operations": ["POST /api/projects/{project_id}/persons/{id}/update_property/"],
"annotations": {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c67fe649a152..1c379085fc87 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -94961,11 +94961,18 @@ export namespace Schemas {
success: boolean;
}
+ /**
+ * Property keys and values to set together, instead of 'key' and 'value'. One request sets up to 1000 properties and emits a single $set event.
+ */
+ export type PersonUpdatePropertyRequestProperties = { [key: string]: unknown };
+
export interface PersonUpdatePropertyRequest {
- /** The property key to set. */
- key: string;
+ /** The property key to set. Pair it with 'value' to set one property. */
+ key?: string;
/** The property value. Can be a string, number, boolean, or object. */
- value: unknown;
+ value?: unknown;
+ /** Property keys and values to set together, instead of 'key' and 'value'. One request sets up to 1000 properties and emits a single $set event. */
+ properties?: PersonUpdatePropertyRequestProperties;
}
export interface _Summary {
diff --git a/services/mcp/src/generated/persons/api.ts b/services/mcp/src/generated/persons/api.ts
index a81b39998030..2d7ebcd36f9d 100644
--- a/services/mcp/src/generated/persons/api.ts
+++ b/services/mcp/src/generated/persons/api.ts
@@ -213,8 +213,14 @@ export const PersonsUpdatePropertyCreateQueryParams = () => zod.object({
})
export const PersonsUpdatePropertyCreateBody = () => zod.object({
- key: zod.string().describe('The property key to set.'),
- value: zod.unknown().describe('The property value. Can be a string, number, boolean, or object.'),
+ key: zod.string().optional().describe("The property key to set. Pair it with 'value' to set one property."),
+ value: zod.unknown().optional().describe('The property value. Can be a string, number, boolean, or object.'),
+ properties: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ "Property keys and values to set together, instead of 'key' and 'value'. One request sets up to 1000 properties and emits a single $set event."
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/persons.ts b/services/mcp/src/tools/generated/persons.ts
index b346229dbc7a..d7ea9bccf3ed 100644
--- a/services/mcp/src/tools/generated/persons.ts
+++ b/services/mcp/src/tools/generated/persons.ts
@@ -159,6 +159,9 @@ const personsPropertySet = (): ToolBase<ReturnType<typeof PersonsPropertySetSche
if (params.value !== undefined) {
body['value'] = params.value
}
+ if (params.properties !== undefined) {
+ body['properties'] = params.properties
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/persons/${encodeURIComponent(String(params.id))}/update_property/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-set.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-set.json
index fd4931d1bb9f..46016c39aacf 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-set.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-set.json
@@ -6,13 +6,21 @@
"type": "string"
},
"key": {
- "description": "The property key to set.",
+ "description": "The property key to set. Pair it with 'value' to set one property.",
"type": "string"
},
+ "properties": {
+ "additionalProperties": {},
+ "description": "Property keys and values to set together, instead of 'key' and 'value'. One request sets up to 1000 properties and emits a single $set event.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
"value": {
"description": "The property value. Can be a string, number, boolean, or object."
}
},
- "required": ["id", "key", "value"],
+ "required": ["id"],
"type": "object"
}