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(mcp): read and set event definition owners (#124718)

Thomas Obermüller4133487f16bd
diff --git a/ee/api/ee_event_definition.py b/ee/api/ee_event_definition.py
index 131104fdcfca..7e0e4dd8a84c 100644
--- a/ee/api/ee_event_definition.py
+++ b/ee/api/ee_event_definition.py
@@ -1,6 +1,9 @@
+from typing import TYPE_CHECKING
+
from django.utils import timezone
import posthoganalytics
+from drf_spectacular.extensions import OpenApiSerializerExtension
from rest_framework import serializers
from posthog.api.shared import UserBasicSerializer
@@ -11,6 +14,33 @@ from posthog.models.organization import OrganizationMembership
from ee.models.event_definition import EnterpriseEventDefinition
+if TYPE_CHECKING:
+ from drf_spectacular.openapi import AutoSchema
+ from drf_spectacular.utils import Direction
+
+
+class EnterpriseEventDefinitionSerializerExtension(OpenApiSerializerExtension):
+ """Documents `owner` as a user ID in request bodies, and as the user object that `to_representation` returns."""
+
+ target_class = "ee.api.ee_event_definition.EnterpriseEventDefinitionSerializer"
+
+ def get_name(self, auto_schema: "AutoSchema", direction: "Direction") -> str | None:
+ # One component cannot describe both `owner` shapes. A PATCH body already gets its own "Patched"
+ # component, so only POST and PUT bodies need a name apart from the response.
+ if direction == "request" and not getattr(self.target, "partial", False):
+ return "EnterpriseEventDefinitionRequest"
+ return None
+
+ def map_serializer(self, auto_schema: "AutoSchema", direction: "Direction") -> dict[str, object]:
+ schema: dict = auto_schema._map_serializer(self.target, direction, bypass_extensions=True)
+ if direction == "response":
+ schema["properties"]["owner"] = {
+ "oneOf": [auto_schema.resolve_serializer(UserBasicSerializer, direction).ref, {"type": "null"}],
+ "readOnly": True,
+ "description": "The user responsible for the event, or null when it has no owner.",
+ }
+ return schema
+
class EnterpriseEventDefinitionSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
updated_by = UserBasicSerializer(read_only=True)
@@ -65,6 +95,7 @@ class EnterpriseEventDefinitionSerializer(TaggedItemSerializerMixin, serializers
"default_columns",
"media_preview_urls",
)
+ extra_kwargs = {"owner": {"help_text": "ID of the user responsible for the event. Null removes the owner."}}
read_only_fields = [
"id",
"name",
diff --git a/ee/api/test/test_event_definition.py b/ee/api/test/test_event_definition.py
index 4568c13343ee..23da5e285306 100644
--- a/ee/api/test/test_event_definition.py
+++ b/ee/api/test/test_event_definition.py
@@ -699,6 +699,17 @@ class TestEventDefinitionEnterpriseAPI(APIBaseTest):
assert event_def.verified_by == self.user
assert event_def.verified_at is not None
+ def test_clear_owner(self):
+ License.objects.create(key="test_key", plan="enterprise", valid_until=datetime(2500, 1, 19, 3, 14, 7))
+ event = EnterpriseEventDefinition.objects.create(team=self.demo_team, name="owned_event", owner=self.user)
+
+ response = self.client.patch(f"/api/projects/@current/event_definitions/{event.id}/", {"owner": None})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["owner"] is None
+ event.refresh_from_db()
+ assert event.owner is None
+
def test_cannot_assign_owner_from_another_organization(self):
"""Owner must belong to the current organization (PATCH)."""
License.objects.create(key="test_key", plan="enterprise", valid_until=datetime(2500, 1, 19, 3, 14, 7))
diff --git a/ee/hogai/tools/read_taxonomy/core.py b/ee/hogai/tools/read_taxonomy/core.py
index b4e9aadf4ec7..e1ab680133ae 100644
--- a/ee/hogai/tools/read_taxonomy/core.py
+++ b/ee/hogai/tools/read_taxonomy/core.py
@@ -8,7 +8,7 @@ from posthog.taxonomy.dynamic_properties import PropertyScope, dynamic_property_
from ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit
from ee.hogai.chat_agent.taxonomy.entities import resolve_entity_name
-from ee.hogai.utils.helpers import format_events_yaml, get_event_description
+from ee.hogai.utils.helpers import format_events_yaml, get_event_description, get_event_owner
ENTITY_FIELD_DESCRIPTION = (
"The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. "
@@ -25,7 +25,7 @@ class ReadEvents(BaseModel):
class ReadEventProperties(BaseModel):
- """Returns the description (if one is set) and properties list for a provided event. Before calling this tool, ensure the event exists by reading events."""
+ """Returns the description and owner (if set) and properties list for a provided event. Before calling this tool, ensure the event exists by reading events."""
kind: Literal["event_properties"] = "event_properties"
event_name: str = Field(description="The name of the event that you want to retrieve properties for.")
@@ -126,6 +126,8 @@ def execute_taxonomy_query(
result = toolkit.retrieve_event_or_action_properties(query.event_name)
description = get_event_description(team, query.event_name)
prefix = f"Description of `{query.event_name}`: {description}\n\n" if description else ""
+ if owner := get_event_owner(team, query.event_name):
+ prefix += f"Owner of `{query.event_name}`: {owner}\n\n"
return f"{prefix}{result}\n\n{DYNAMIC_EVENT_PROPERTIES_HINT}"
case ReadEventSamplePropertyValues():
return toolkit.retrieve_event_or_action_property_values(query.event_name, query.property_name)
diff --git a/ee/hogai/tools/read_taxonomy/test/test_tool.py b/ee/hogai/tools/read_taxonomy/test/test_tool.py
index 4658f219c118..9b54dac25ae8 100644
--- a/ee/hogai/tools/read_taxonomy/test/test_tool.py
+++ b/ee/hogai/tools/read_taxonomy/test/test_tool.py
@@ -6,6 +6,7 @@ from langchain_core.runnables import RunnableConfig
from parameterized import parameterized
from posthog.event_usage import EventSource
+from posthog.models import Team, User
from products.posthog_ai.backend.models.assistant import Conversation
@@ -177,3 +178,68 @@ class TestReadTaxonomyTool(NonAtomicBaseTest):
else:
self.assertNotIn("Description of `quiz_retaken`", result)
self.assertIn("mixer_session_id", result)
+
+ @parameterized.expand(
+ [
+ ("custom_event", "quiz_retaken", "Ada", "Lovelace", "Ada Lovelace ([email protected])"),
+ ("core_event", "$pageview", "Ada", "Lovelace", "Ada Lovelace ([email protected])"),
+ ("owner_without_name", "quiz_retaken", "", "", "[email protected]"),
+ (
+ "name_with_line_break",
+ "quiz_retaken",
+ "Ada\n# SYSTEM:",
+ "Lovelace",
+ "Ada # SYSTEM: Lovelace ([email protected])",
+ ),
+ ]
+ )
+ @patch("ee.hogai.tools.read_taxonomy.core.TaxonomyAgentToolkit")
+ def test_event_properties_surface_event_owner(
+ self, _name, event_name, first_name, last_name, expected_owner, mock_toolkit_class
+ ):
+ mock_toolkit = mock_toolkit_class.return_value
+ mock_toolkit.retrieve_event_or_action_properties.return_value = "- mixer_session_id"
+ owner = User.objects.create_and_join(
+ self.organization, "[email protected]", None, first_name=first_name, last_name=last_name
+ )
+ EnterpriseEventDefinition.objects.create(team=self.team, name=event_name, owner=owner)
+
+ result = execute_taxonomy_query(ReadEventProperties(event_name=event_name), mock_toolkit, self.team, self.user)
+
+ self.assertIn(f"Owner of `{event_name}`: {expected_owner}\n", result)
+ self.assertIn("mixer_session_id", result)
+
+ @patch("ee.hogai.tools.read_taxonomy.core.TaxonomyAgentToolkit")
+ def test_event_properties_omit_owner_when_unset(self, mock_toolkit_class):
+ mock_toolkit = mock_toolkit_class.return_value
+ mock_toolkit.retrieve_event_or_action_properties.return_value = "- mixer_session_id"
+ EnterpriseEventDefinition.objects.create(team=self.team, name="quiz_retaken", description="Retook a quiz")
+
+ result = execute_taxonomy_query(
+ ReadEventProperties(event_name="quiz_retaken"), mock_toolkit, self.team, self.user
+ )
+
+ self.assertNotIn("Owner of", result)
+ self.assertIn("Description of `quiz_retaken`: Retook a quiz", result)
+
+ @parameterized.expand([("other_environment_same_project", True), ("other_project", False)])
+ @patch("ee.hogai.tools.read_taxonomy.core.TaxonomyAgentToolkit")
+ def test_event_properties_owner_is_scoped_to_the_project(self, _name, same_project, mock_toolkit_class):
+ mock_toolkit = mock_toolkit_class.return_value
+ mock_toolkit.retrieve_event_or_action_properties.return_value = "- mixer_session_id"
+ owner = User.objects.create_and_join(self.organization, "[email protected]", None, first_name="Ada")
+ # Without a project, the manager creates a new one for the team.
+ project_kwargs = {"project_id": self.team.project_id} if same_project else {}
+ other_team = Team.objects.create(organization=self.organization, name="other", **project_kwargs)
+ EnterpriseEventDefinition.objects.create(
+ team=other_team, project_id=other_team.project_id, name="quiz_retaken", owner=owner
+ )
+
+ result = execute_taxonomy_query(
+ ReadEventProperties(event_name="quiz_retaken"), mock_toolkit, self.team, self.user
+ )
+
+ if same_project:
+ self.assertIn("Owner of `quiz_retaken`: Ada ([email protected])\n", result)
+ else:
+ self.assertNotIn("Owner of", result)
diff --git a/ee/hogai/utils/helpers.py b/ee/hogai/utils/helpers.py
index 6f7f9d1386df..280df2cbaf2e 100644
--- a/ee/hogai/utils/helpers.py
+++ b/ee/hogai/utils/helpers.py
@@ -47,6 +47,8 @@ from posthog.security.llm_prompt_sanitization import sanitize_user_text
from posthog.settings import EE_AVAILABLE
from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, is_hidden_from_assistant
+from products.event_definitions.backend.models.property_definition import effective_project_id_expr
+
from ee.hogai.utils.anthropic import SUPPORTED_ANTHROPIC_BLOCKS
from ee.hogai.utils.types.base import (
ArtifactRefMessage,
@@ -83,6 +85,9 @@ MAX_EVENT_DESCRIPTION_LENGTH = 500
# Matches CAPTURE_V1_MAX_EVENT_NAME_LENGTH in rust/capture, which rejects a longer name at ingestion.
MAX_EVENT_NAME_LENGTH = 200
+# Covers the User model's limits: 150 characters each for first and last name, and 254 for an email.
+MAX_EVENT_OWNER_FIELD_LENGTH = 301
+
NOT_SEEN_RECENTLY_MARKER = f"(not seen in the last {LOOKBACK_DAYS} days)"
NOT_SEEN_RECENTLY_LEGEND = (
f"Events marked {NOT_SEEN_RECENTLY_MARKER} are listed for reference only. This project has sent none of them "
@@ -333,6 +338,35 @@ def get_event_description(team: Team, event_name: str) -> str | None:
return None
+def get_event_owner(team: Team, event_name: str) -> str | None:
+ """Return the owner of a single event as "Name (email)", or None if the event has no owner.
+
+ Only the enterprise `EventDefinition` model carries an `owner`, so this is a no-op on non-EE builds.
+ Core taxonomy events are looked up too: an owner only ever comes from the event definition.
+ """
+ if not EE_AVAILABLE:
+ return None
+
+ from ee.models.event_definition import (
+ EnterpriseEventDefinition, # noqa: PLC0415 — EE-only model, keep off the OSS import path
+ )
+
+ # Event definitions belong to the project, so an environment sees the owner set from any other one.
+ owner = (
+ EnterpriseEventDefinition.objects.alias(effective_project_id=effective_project_id_expr())
+ .filter(effective_project_id=team.project_id, name=event_name, owner__isnull=False)
+ .values_list("owner__first_name", "owner__last_name", "owner__email")
+ .first()
+ )
+ if owner is None:
+ return None
+ first_name, last_name, email = owner
+ # Users write their own names, so a name is untrusted text like an event description.
+ name = sanitize_user_text(f"{first_name} {last_name}", MAX_EVENT_OWNER_FIELD_LENGTH)
+ email = sanitize_user_text(email, MAX_EVENT_OWNER_FIELD_LENGTH)
+ return f"{name} ({email})" if name else email
+
+
def _get_event_definition_descriptions(
team: Team, event_names: list[str], already_described: dict[str, str]
) -> dict[str, str]:
diff --git a/products/event_definitions/frontend/generated/api.schemas.ts b/products/event_definitions/frontend/generated/api.schemas.ts
index dcf2da843eb8..c47e032636f2 100644
--- a/products/event_definitions/frontend/generated/api.schemas.ts
+++ b/products/event_definitions/frontend/generated/api.schemas.ts
@@ -83,8 +83,8 @@ export interface EnterpriseEventDefinitionApi {
readonly id: string
/** @maxLength 400 */
name: string
- /** @nullable */
- owner?: number | null
+ /** The user responsible for the event, or null when it has no owner. */
+ readonly owner?: UserBasicApi | null
/** @nullable */
description?: string | null
tags?: unknown[]
@@ -129,6 +129,51 @@ export interface PaginatedEnterpriseEventDefinitionListApi {
count_is_capped?: boolean
}
+/**
+ * Serializer mixin that handles tags for objects.
+ */
+export interface EnterpriseEventDefinitionRequestApi {
+ readonly id: string
+ /** @maxLength 400 */
+ name: string
+ /**
+ * ID of the user responsible for the event. Null removes the owner.
+ * @nullable
+ */
+ owner?: number | null
+ /** @nullable */
+ description?: string | null
+ tags?: unknown[]
+ /** @nullable */
+ readonly created_at: string | null
+ readonly updated_at: string
+ readonly updated_by: UserBasicApi
+ /** @nullable */
+ readonly last_seen_at: string | null
+ readonly last_updated_at: string
+ verified?: boolean
+ /** @nullable */
+ readonly verified_at: string | null
+ readonly verified_by: UserBasicApi
+ /** @nullable */
+ hidden?: boolean | null
+ enforcement_mode?: SchemaEnforcementModeEnumApi
+ /**
+ * Name of a single property on this event that PostHog UIs should display alongside the event (for example `$pathname` on `$pageview`). When set, surfaces like the session replay inspector show the property's value next to the event name without the user having to open the event.
+ * @maxLength 400
+ * @nullable
+ */
+ primary_property?: string | null
+ readonly is_action: boolean
+ readonly action_id: number
+ readonly is_calculating: boolean
+ readonly last_calculated_at: string
+ readonly created_by: UserBasicApi
+ post_to_slack?: boolean
+ default_columns?: string[]
+ readonly media_preview_urls: readonly string[]
+}
+
/**
* Serializer mixin that handles tags for objects.
*/
@@ -136,7 +181,10 @@ export interface PatchedEnterpriseEventDefinitionApi {
readonly id?: string
/** @maxLength 400 */
name?: string
- /** @nullable */
+ /**
+ * ID of the user responsible for the event. Null removes the owner.
+ * @nullable
+ */
owner?: number | null
/** @nullable */
description?: string | null
diff --git a/products/event_definitions/frontend/generated/api.ts b/products/event_definitions/frontend/generated/api.ts
index b985069ec857..e7f5953f25ba 100644
--- a/products/event_definitions/frontend/generated/api.ts
+++ b/products/event_definitions/frontend/generated/api.ts
@@ -12,6 +12,7 @@ import type {
BulkUpdateTagsUUIDRequestApi,
BulkUpdateTagsUUIDResponseApi,
EnterpriseEventDefinitionApi,
+ EnterpriseEventDefinitionRequestApi,
EventDefinitionBulkUpdateVerifiedRequestApi,
EventDefinitionBulkUpdateVerifiedResponseApi,
EventDefinitionRecordApi,
@@ -76,14 +77,14 @@ export const getEventDefinitionsCreateUrl = (projectId: string) => {
export const eventDefinitionsCreate = async (
projectId: string,
- enterpriseEventDefinitionApi: NonReadonly<EnterpriseEventDefinitionApi>,
+ enterpriseEventDefinitionRequestApi: NonReadonly<EnterpriseEventDefinitionRequestApi>,
options?: RequestInit
): Promise<EnterpriseEventDefinitionApi> => {
return apiMutator<EnterpriseEventDefinitionApi>(getEventDefinitionsCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(enterpriseEventDefinitionApi),
+ body: JSON.stringify(enterpriseEventDefinitionRequestApi),
})
}
@@ -109,14 +110,14 @@ export const getEventDefinitionsUpdateUrl = (projectId: string, id: string) => {
export const eventDefinitionsUpdate = async (
projectId: string,
id: string,
- enterpriseEventDefinitionApi: NonReadonly<EnterpriseEventDefinitionApi>,
+ enterpriseEventDefinitionRequestApi: NonReadonly<EnterpriseEventDefinitionRequestApi>,
options?: RequestInit
): Promise<EnterpriseEventDefinitionApi> => {
return apiMutator<EnterpriseEventDefinitionApi>(getEventDefinitionsUpdateUrl(projectId, id), {
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(enterpriseEventDefinitionApi),
+ body: JSON.stringify(enterpriseEventDefinitionRequestApi),
})
}
diff --git a/products/event_definitions/frontend/generated/api.zod.ts b/products/event_definitions/frontend/generated/api.zod.ts
index d5ba446ac12c..6999bf04b9a5 100644
--- a/products/event_definitions/frontend/generated/api.zod.ts
+++ b/products/event_definitions/frontend/generated/api.zod.ts
@@ -18,7 +18,7 @@ export const eventDefinitionsCreateBodyPostToSlackDefault = false
export const EventDefinitionsCreateBody = /* @__PURE__ */ zod
.object({
name: zod.string().max(eventDefinitionsCreateBodyNameMax),
- owner: zod.number().nullish(),
+ owner: zod.number().nullish().describe('ID of the user responsible for the event. Null removes the owner.'),
description: zod.string().nullish(),
tags: zod.array(zod.unknown()).optional(),
verified: zod.boolean().optional(),
@@ -45,7 +45,7 @@ export const eventDefinitionsUpdateBodyPostToSlackDefault = false
export const EventDefinitionsUpdateBody = /* @__PURE__ */ zod
.object({
name: zod.string().max(eventDefinitionsUpdateBodyNameMax),
- owner: zod.number().nullish(),
+ owner: zod.number().nullish().describe('ID of the user responsible for the event. Null removes the owner.'),
description: zod.string().nullish(),
tags: zod.array(zod.unknown()).optional(),
verified: zod.boolean().optional(),
@@ -72,7 +72,7 @@ export const eventDefinitionsPartialUpdateBodyPostToSlackDefault = false
export const EventDefinitionsPartialUpdateBody = /* @__PURE__ */ zod
.object({
name: zod.string().max(eventDefinitionsPartialUpdateBodyNameMax).optional(),
- owner: zod.number().nullish(),
+ owner: zod.number().nullish().describe('ID of the user responsible for the event. Null removes the owner.'),
description: zod.string().nullish(),
tags: zod.array(zod.unknown()).optional(),
verified: zod.boolean().optional(),
diff --git a/products/signals/backend/test/test_scout_tool_policy.py b/products/signals/backend/test/test_scout_tool_policy.py
index 58d29db6f03f..375af18c6e45 100644
--- a/products/signals/backend/test/test_scout_tool_policy.py
+++ b/products/signals/backend/test/test_scout_tool_policy.py
@@ -33,6 +33,7 @@ GET_ONLY_TOOLS = frozenset(
{
"agent-feedback",
"debug-mcp-ui-apps",
+ "event-definition-get",
"experiment-get-by-flag-key",
"external-data-sources-jobs",
"external-data-sync-logs",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index dc5b02913628..e90c18c47579 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5553,7 +5553,7 @@
}
},
"event-definition-create": {
- "description": "Create an event definition for an event that has not been ingested yet. Use this to define the event name, description, tags, verified state, and hidden state before the first event arrives. Fails if a definition with the same name already exists (use event-definition-update instead). Use exact event name like 'user_signed_up'.",
+ "description": "Create an event definition for an event that has not been ingested yet. Use this to define the event name, description, owner, tags, verified state, and hidden state before the first event arrives. Fails if a definition with the same name already exists (use event-definition-update instead). Use exact event name like 'user_signed_up'.",
"category": "Events & properties",
"feature": "events",
"summary": "Create an event definition.",
@@ -5566,8 +5566,22 @@
"readOnlyHint": false
}
},
+ "event-definition-get": {
+ "description": "Get one event definition by its exact name, like '$pageview' or 'user_signed_up'. Returns the description, owner, tags, verified and hidden state, first seen time, and last seen time. Use this to find who owns an event. Returns `found: false` when no definition has that name.",
+ "category": "Events & properties",
+ "feature": "events",
+ "summary": "Get an event definition by name.",
+ "title": "Get event definition",
+ "required_scopes": ["event_definition:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"event-definition-update": {
- "description": "Update event definition metadata. Can update description, tags, mark status as verified or hidden. Use exact event name like '$pageview' or 'user_signed_up'.",
+ "description": "Update event definition metadata. Can update description, owner, tags, mark status as verified or hidden. Use exact event name like '$pageview' or 'user_signed_up'.",
"category": "Events & properties",
"feature": "events",
"summary": "Update an event definition's metadata.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 7499bf74e70f..e350b2ca9f46 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -576,7 +576,7 @@
}
},
"event-definition-create": {
- "description": "Create an event definition for an event that has not been ingested yet. Use this to define the event name, description, tags, verified state, and hidden state before the first event arrives. Fails if a definition with the same name already exists (use event-definition-update instead). Use exact event name like 'user_signed_up'.",
+ "description": "Create an event definition for an event that has not been ingested yet. Use this to define the event name, description, owner, tags, verified state, and hidden state before the first event arrives. Fails if a definition with the same name already exists (use event-definition-update instead). Use exact event name like 'user_signed_up'.",
"category": "Events & properties",
"feature": "events",
"summary": "Create an event definition.",
@@ -589,8 +589,22 @@
"readOnlyHint": false
}
},
+ "event-definition-get": {
+ "description": "Get one event definition by its exact name, like '$pageview' or 'user_signed_up'. Returns the description, owner, tags, verified and hidden state, first seen time, and last seen time. Use this to find who owns an event. Returns `found: false` when no definition has that name.",
+ "category": "Events & properties",
+ "feature": "events",
+ "summary": "Get an event definition by name.",
+ "title": "Get event definition",
+ "required_scopes": ["event_definition:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"event-definition-update": {
- "description": "Update event definition metadata. Can update description, tags, mark status as verified or hidden. Use exact event name like '$pageview' or 'user_signed_up'.",
+ "description": "Update event definition metadata. Can update description, owner, tags, mark status as verified or hidden. Use exact event name like '$pageview' or 'user_signed_up'.",
"category": "Events & properties",
"feature": "events",
"summary": "Update an event definition's metadata.",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index f494fb55892f..cca13e562b43 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -482,6 +482,19 @@
"description": "Description explaining when the event is triggered",
"type": "string"
},
+ "owner": {
+ "description": "Numeric user ID of the person responsible for the event. Must be a member of the organization. To find the ID from an email, call `org-members-list` and use `user.id`. Pass null to remove the owner.",
+ "anyOf": [
+ {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"tags": {
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"type": "array",
@@ -503,6 +516,17 @@
},
"required": ["eventName"]
},
+ "EventDefinitionGetSchema": {
+ "type": "object",
+ "properties": {
+ "eventName": {
+ "type": "string",
+ "minLength": 1,
+ "description": "The exact name of the event (e.g. \"$pageview\", \"user_signed_up\")"
+ }
+ },
+ "required": ["eventName"]
+ },
"EventDefinitionUpdateInputSchema": {
"type": "object",
"properties": {
@@ -510,6 +534,19 @@
"description": "Description explaining when the event is triggered",
"type": "string"
},
+ "owner": {
+ "description": "Numeric user ID of the person responsible for the event. Must be a member of the organization. To find the ID from an email, call `org-members-list` and use `user.id`. Pass null to remove the owner.",
+ "anyOf": [
+ {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"tags": {
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"type": "array",
@@ -542,6 +579,19 @@
"description": "Description explaining when the event is triggered",
"type": "string"
},
+ "owner": {
+ "description": "Numeric user ID of the person responsible for the event. Must be a member of the organization. To find the ID from an email, call `org-members-list` and use `user.id`. Pass null to remove the owner.",
+ "anyOf": [
+ {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"tags": {
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"type": "array",
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 9d869406662b..1ed9355d3619 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -925,6 +925,7 @@ export class ApiClient {
eventName: string
data?: {
description?: string
+ owner?: number | null
tags?: string[]
verified?: boolean
hidden?: boolean
@@ -938,6 +939,20 @@ export class ApiClient {
})
},
+ getEventDefinition: async ({
+ projectId,
+ eventName,
+ }: {
+ projectId: string
+ eventName: string
+ }): Promise<Result<ApiEventDefinition>> => {
+ const searchParams = new URLSearchParams({ name: eventName })
+
+ return this.fetchJson<ApiEventDefinition>(
+ `${this.baseUrl}/api/projects/${projectId}/event_definitions/by_name/?${searchParams}`
+ )
+ },
+
updateEventDefinition: async ({
projectId,
eventName,
@@ -947,16 +962,17 @@ export class ApiClient {
eventName: string
data: {
description?: string
+ owner?: number | null
tags?: string[]
verified?: boolean
hidden?: boolean
}
}): Promise<Result<ApiEventDefinition>> => {
// Fetching the event definition by name to get its ID
- const searchParams = new URLSearchParams({ name: eventName })
- const findUrl = `${this.baseUrl}/api/projects/${projectId}/event_definitions/by_name/?${searchParams}`
-
- const findResult = await this.fetchJson<ApiEventDefinition>(findUrl)
+ const findResult: Result<ApiEventDefinition> = await this.projects().getEventDefinition({
+ projectId,
+ eventName,
+ })
if (!findResult.success) {
if (findResult.error instanceof PostHogApiError && findResult.error.status === 404) {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0fc360237426..07b315746920 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -42676,7 +42676,52 @@ export namespace Schemas {
readonly id: string;
/** @maxLength 400 */
name: string;
+ /** The user responsible for the event, or null when it has no owner. */
+ readonly owner?: UserBasic | null;
/** @nullable */
+ description?: string | null;
+ tags?: unknown[];
+ /** @nullable */
+ readonly created_at: string | null;
+ readonly updated_at: string;
+ readonly updated_by: UserBasic;
+ /** @nullable */
+ readonly last_seen_at: string | null;
+ readonly last_updated_at: string;
+ verified?: boolean;
+ /** @nullable */
+ readonly verified_at: string | null;
+ readonly verified_by: UserBasic;
+ /** @nullable */
+ hidden?: boolean | null;
+ enforcement_mode?: SchemaEnforcementModeEnum;
+ /**
+ * Name of a single property on this event that PostHog UIs should display alongside the event (for example `$pathname` on `$pageview`). When set, surfaces like the session replay inspector show the property's value next to the event name without the user having to open the event.
+ * @maxLength 400
+ * @nullable
+ */
+ primary_property?: string | null;
+ readonly is_action: boolean;
+ readonly action_id: number;
+ readonly is_calculating: boolean;
+ readonly last_calculated_at: string;
+ readonly created_by: UserBasic;
+ post_to_slack?: boolean;
+ default_columns?: string[];
+ readonly media_preview_urls: readonly string[];
+ }
+
+ /**
+ * Serializer mixin that handles tags for objects.
+ */
+ export interface EnterpriseEventDefinitionRequest {
+ readonly id: string;
+ /** @maxLength 400 */
+ name: string;
+ /**
+ * ID of the user responsible for the event. Null removes the owner.
+ * @nullable
+ */
owner?: number | null;
/** @nullable */
description?: string | null;
@@ -86363,7 +86408,10 @@ export namespace Schemas {
readonly id?: string;
/** @maxLength 400 */
name?: string;
- /** @nullable */
+ /**
+ * ID of the user responsible for the event. Null removes the owner.
+ * @nullable
+ */
owner?: number | null;
/** @nullable */
description?: string | null;
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index ce20e8e2017c..26c555a9d5da 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -764,6 +764,15 @@ const EventDefinitionTagSchema = z
export const EventDefinitionUpdateInputSchema = z.object({
description: z.string().optional().describe('Description explaining when the event is triggered'),
+ owner: z
+ .number()
+ .int()
+ .positive()
+ .nullable()
+ .optional()
+ .describe(
+ 'Numeric user ID of the person responsible for the event. Must be a member of the organization. To find the ID from an email, call `org-members-list` and use `user.id`. Pass null to remove the owner.'
+ ),
tags: z
.array(EventDefinitionTagSchema)
.optional()
@@ -785,6 +794,10 @@ export const EventDefinitionUpdateSchema = z.object({
data: EventDefinitionUpdateInputSchema.describe('The event definition data to update'),
})
+export const EventDefinitionGetSchema = z.object({
+ eventName: z.string().min(1).describe('The exact name of the event (e.g. "$pageview", "user_signed_up")'),
+})
+
export const EventDefinitionCreateSchema = z.object({
eventName: z.string().min(1).max(400).describe('The name of the event to create (e.g. "user_signed_up")'),
data: EventDefinitionUpdateInputSchema.optional().describe('Optional metadata for the new event definition'),
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 3d42da751afc..c42c031c4a4c 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -50,6 +50,7 @@ import {
import { createConnectionCallTool } from './posthogConnections/call'
// Projects
import createEventDefinition from './projects/createEventDefinition'
+import getEventDefinition from './projects/getEventDefinition'
import getProjects from './projects/getProjects'
import setActiveProject from './projects/setActive'
import updateEventDefinition from './projects/updateEventDefinition'
@@ -86,6 +87,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
'projects-get': getProjects,
'switch-project': setActiveProject,
'event-definition-create': createEventDefinition,
+ 'event-definition-get': getEventDefinition,
'event-definition-update': updateEventDefinition,
'property-definition-update': updatePropertyDefinition,
diff --git a/services/mcp/src/tools/projects/getEventDefinition.ts b/services/mcp/src/tools/projects/getEventDefinition.ts
new file mode 100644
index 000000000000..7a26af6a7323
--- /dev/null
+++ b/services/mcp/src/tools/projects/getEventDefinition.ts
@@ -0,0 +1,84 @@
+import type { z } from 'zod'
+
+import { PostHogApiError, wrapError } from '@/lib/errors'
+import { EventDefinitionGetSchema } from '@/schema/tool-inputs'
+import type { Context, ToolBase } from '@/tools/types'
+
+const schema = EventDefinitionGetSchema
+
+type Params = z.infer<typeof schema>
+
+interface EventDefinitionOwner {
+ id: number
+ email: string
+ first_name?: string
+ last_name?: string
+}
+
+/** A miss is data, not an error: agents look an event up to check whether it exists before creating it. */
+type Result =
+ | {
+ found: true
+ id: string
+ name: string
+ description: string | null
+ owner: EventDefinitionOwner | null
+ tags: unknown[]
+ verified: boolean
+ hidden: boolean | null
+ first_seen_at: string | null
+ last_seen_at: string | null
+ url: string
+ }
+ | { found: false; eventName: string; message: string }
+
+export const getEventDefinitionHandler: ToolBase<typeof schema, Result>['handler'] = async (
+ context: Context,
+ params: Params
+) => {
+ const projectId = await context.stateManager.getProjectId()
+
+ const result = await context.api.projects().getEventDefinition({ projectId, eventName: params.eventName })
+
+ if (!result.success) {
+ if (result.error instanceof PostHogApiError && result.error.status === 404) {
+ return {
+ found: false,
+ eventName: params.eventName,
+ message:
+ `No event definition named "${params.eventName}" exists in this project. ` +
+ 'Call `read-data-schema` with { "query": { "kind": "events" } } to list events, ' +
+ 'or `event-definition-create` to define it.',
+ }
+ }
+ throw wrapError(`Failed to get event definition: ${result.error.message}`, result.error)
+ }
+
+ const definition = result.data
+ const owner = definition.owner
+
+ return {
+ found: true,
+ id: definition.id,
+ name: definition.name,
+ description: definition.description ?? null,
+ owner: owner
+ ? { id: owner.id, email: owner.email, first_name: owner.first_name, last_name: owner.last_name }
+ : null,
+ tags: definition.tags ?? [],
+ verified: definition.verified ?? false,
+ hidden: definition.hidden ?? null,
+ // The UI calls this "First seen". It is null for a definition created before any event arrived.
+ first_seen_at: definition.created_at,
+ last_seen_at: definition.last_seen_at,
+ url: `${context.api.getProjectBaseUrl(projectId)}/data-management/events/${encodeURIComponent(definition.id)}`,
+ }
+}
+
+const tool = (): ToolBase<typeof schema, Result> => ({
+ name: 'event-definition-get',
+ schema,
+ handler: getEventDefinitionHandler,
+})
+
+export default tool
diff --git a/services/mcp/src/tools/projects/updateEventDefinition.ts b/services/mcp/src/tools/projects/updateEventDefinition.ts
index 71ef26205578..34a9d9dc2967 100644
--- a/services/mcp/src/tools/projects/updateEventDefinition.ts
+++ b/services/mcp/src/tools/projects/updateEventDefinition.ts
@@ -29,7 +29,7 @@ export const updateEventDefinitionHandler: ToolBase<typeof schema, Result>['hand
return {
...result.data,
- url: `${context.api.getProjectBaseUrl(projectId)}/data-management/events/${encodeURIComponent(result.data.name)}`,
+ url: `${context.api.getProjectBaseUrl(projectId)}/data-management/events/${encodeURIComponent(result.data.id)}`,
}
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-create.json
index 2c008c6087a5..3d4feac9f17e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-create.json
@@ -12,6 +12,19 @@
"description": "Mark event as no longer used/captured. Hides it from UI while preserving historical data",
"type": "boolean"
},
+ "owner": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Numeric user ID of the person responsible for the event. Must be a member of the organization. To find the ID from an email, call `org-members-list` and use `user.id`. Pass null to remove the owner."
+ },
"tags": {
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-get.json
new file mode 100644
index 000000000000..9e5fd2bb27ca
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-get.json
@@ -0,0 +1,12 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "eventName": {
+ "description": "The exact name of the event (e.g. \"$pageview\", \"user_signed_up\")",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["eventName"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-update.json
index f414229566b0..0b918ca8c5cd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-update.json
@@ -12,6 +12,19 @@
"description": "Mark event as no longer used/captured. Hides it from UI while preserving historical data",
"type": "boolean"
},
+ "owner": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Numeric user ID of the person responsible for the event. Must be a member of the organization. To find the ID from an email, call `org-members-list` and use `user.id`. Pass null to remove the owner."
+ },
"tags": {
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"items": {
diff --git a/services/mcp/tests/unit/event-definition-owner.test.ts b/services/mcp/tests/unit/event-definition-owner.test.ts
new file mode 100644
index 000000000000..19a1ce251396
--- /dev/null
+++ b/services/mcp/tests/unit/event-definition-owner.test.ts
@@ -0,0 +1,153 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { ApiClient } from '@/api/client'
+import createEventDefinition from '@/tools/projects/createEventDefinition'
+import getEventDefinition from '@/tools/projects/getEventDefinition'
+import updateEventDefinition from '@/tools/projects/updateEventDefinition'
+import type { Context } from '@/tools/types'
+
+const owner = {
+ id: 7,
+ uuid: '0190f9a6-0000-0000-0000-000000000007',
+ distinct_id: 'owner-distinct-id',
+ first_name: 'Ada',
+ last_name: 'Lovelace',
+ email: '[email protected]',
+ is_email_verified: true,
+ hedgehog_config: null,
+}
+
+const definition = {
+ id: '0190f9a6-1111-2222-3333-444444444444',
+ name: 'user_signed_up',
+ owner,
+ description: 'Fired when a user finishes sign-up',
+ tags: ['onboarding'],
+ verified: true,
+ hidden: false,
+ created_at: '2026-01-02T03:04:05Z',
+ last_seen_at: '2026-10-27T12:00:00Z',
+}
+
+function stubFetch(...responses: Response[]): ReturnType<typeof vi.fn> {
+ const fetchMock = vi.fn()
+ for (const response of responses) {
+ fetchMock.mockResolvedValueOnce(response)
+ }
+ vi.stubGlobal('fetch', fetchMock)
+ return fetchMock
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
+}
+
+function createContext(): Context {
+ return {
+ api: new ApiClient({ apiToken: 'phx_test', baseUrl: 'https://us.posthog.com' }),
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('17') } as any,
+ env: {} as any,
+ sessionManager: {} as any,
+ cache: {} as any,
+ getDistinctId: async () => 'test-distinct-id',
+ trackEvent: async () => {},
+ }
+}
+
+function requestBody(fetchMock: ReturnType<typeof vi.fn>, call: number): unknown {
+ return JSON.parse(fetchMock.mock.calls[call]![1].body)
+}
+
+describe('event definition owner', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it.each([
+ ['sets', 7],
+ ['clears', null],
+ ])('event-definition-update %s the owner', async (_label, ownerId) => {
+ const fetchMock = stubFetch(json(definition), json({ ...definition, owner: ownerId === null ? null : owner }))
+ const tool = updateEventDefinition()
+
+ // Parse through the tool schema as the server does: before `owner` was in it, the key was stripped.
+ const params = tool.schema.parse({ eventName: 'user_signed_up', data: { owner: ownerId } })
+ const result = await tool.handler(createContext(), params)
+
+ expect(fetchMock.mock.calls[1]![0]).toBe(
+ `https://us.posthog.com/api/projects/17/event_definitions/${definition.id}/`
+ )
+ expect(requestBody(fetchMock, 1)).toEqual({ owner: ownerId })
+ expect(result.url).toBe(`https://us.posthog.com/project/17/data-management/events/${definition.id}`)
+ })
+
+ it('event-definition-create sends the owner', async () => {
+ const fetchMock = stubFetch(json(definition, 201))
+ const tool = createEventDefinition()
+
+ const params = tool.schema.parse({ eventName: 'user_signed_up', data: { owner: 7 } })
+ await tool.handler(createContext(), params)
+
+ expect(requestBody(fetchMock, 0)).toEqual({ name: 'user_signed_up', owner: 7 })
+ })
+
+ it.each([0, -1, 1.5, '[email protected]'])('rejects %s as an owner ID', (ownerId) => {
+ const result = updateEventDefinition().schema.safeParse({
+ eventName: 'user_signed_up',
+ data: { owner: ownerId },
+ })
+
+ expect(result.success).toBe(false)
+ })
+
+ it('event-definition-get returns the owner and the seen times', async () => {
+ const fetchMock = stubFetch(json(definition))
+ const tool = getEventDefinition()
+
+ const result = await tool.handler(createContext(), tool.schema.parse({ eventName: 'user_signed_up' }))
+
+ expect(fetchMock.mock.calls[0]![0]).toBe(
+ 'https://us.posthog.com/api/projects/17/event_definitions/by_name/?name=user_signed_up'
+ )
+ expect(result).toEqual({
+ found: true,
+ id: definition.id,
+ name: 'user_signed_up',
+ description: 'Fired when a user finishes sign-up',
+ owner: { id: 7, email: '[email protected]', first_name: 'Ada', last_name: 'Lovelace' },
+ tags: ['onboarding'],
+ verified: true,
+ hidden: false,
+ first_seen_at: '2026-01-02T03:04:05Z',
+ last_seen_at: '2026-10-27T12:00:00Z',
+ url: `https://us.posthog.com/project/17/data-management/events/${definition.id}`,
+ })
+ })
+
+ it('event-definition-get returns a null owner when none is set', async () => {
+ stubFetch(json({ ...definition, owner: null }))
+ const tool = getEventDefinition()
+
+ const result = await tool.handler(createContext(), tool.schema.parse({ eventName: 'user_signed_up' }))
+
+ expect(result).toMatchObject({ found: true, owner: null })
+ })
+
+ it('event-definition-get reports a missing definition as data, not an error', async () => {
+ stubFetch(json({ detail: "Event definition with name 'nope' not found" }, 404))
+ const tool = getEventDefinition()
+
+ const result = await tool.handler(createContext(), tool.schema.parse({ eventName: 'nope' }))
+
+ expect(result).toMatchObject({ found: false, eventName: 'nope' })
+ })
+
+ it('event-definition-get throws on other API errors', async () => {
+ stubFetch(json({ detail: 'You do not have permission to perform this action.' }, 403))
+ const tool = getEventDefinition()
+
+ await expect(tool.handler(createContext(), tool.schema.parse({ eventName: 'user_signed_up' }))).rejects.toThrow(
+ 'Failed to get event definition'
+ )
+ })
+})