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): add event-definition-create tool (#90832)

posthog[bot]2bdf4a0477d4
diff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.py
index 3278b23f012f..8ac4cf764172 100644
--- a/posthog/api/event_definition.py
+++ b/posthog/api/event_definition.py
@@ -169,6 +169,14 @@ class EventDefinitionSerializer(TaggedItemSerializerMixin, serializers.ModelSeri
return value
def validate(self, data):
+ unsupported_metadata = {
+ field: "This field is not supported by this deployment."
+ for field in ("description", "verified", "hidden")
+ if field in self.initial_data
+ }
+ if unsupported_metadata:
+ raise serializers.ValidationError(unsupported_metadata)
+
validated_data = super().validate(data)
if "hidden" in validated_data and "verified" in validated_data:
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index 33139bdda3d0..44bfb3aaf6c8 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -377,6 +377,27 @@ class TestEventDefinitionAPI(APIBaseTest):
detail = cast(dict[str, Any], activity_log.detail)
assert detail["name"] == "my_custom_event"
+ @patch("posthog.api.event_definition.EE_AVAILABLE", False)
+ def test_create_event_definition_rejects_enterprise_metadata_without_ee(self):
+ response = self.client.post(
+ "/api/projects/@current/event_definitions/",
+ {
+ "name": "event_with_unsupported_metadata",
+ "description": "This cannot be stored without EE.",
+ "verified": True,
+ "hidden": False,
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json() == {
+ "type": "validation_error",
+ "code": "invalid_input",
+ "detail": "This field is not supported by this deployment.",
+ "attr": "description",
+ }
+ assert not EventDefinition.objects.filter(name="event_with_unsupported_metadata", team=self.demo_team).exists()
+
def test_create_event_definition_duplicate_name(self):
"""Test that creating an event with a duplicate name fails"""
EventDefinition.objects.create(team=self.demo_team, name="existing_event")
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 3ea22f51b663..5862f8f50ec5 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3787,6 +3787,20 @@
"readOnlyHint": true
}
},
+ "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'.",
+ "category": "Events & properties",
+ "feature": "events",
+ "summary": "Create an event definition.",
+ "title": "Create event definition",
+ "required_scopes": ["event_definition:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"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'.",
"category": "Events & properties",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index dbd9cec02428..0e74e8361eac 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -430,6 +430,20 @@
"readOnlyHint": true
}
},
+ "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'.",
+ "category": "Events & properties",
+ "feature": "events",
+ "summary": "Create an event definition.",
+ "title": "Create event definition",
+ "required_scopes": ["event_definition:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"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'.",
"category": "Events & properties",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 77085df1f427..7e6a693f306f 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -271,6 +271,44 @@
},
"required": ["id", "operations"]
},
+ "EventDefinitionCreateSchema": {
+ "type": "object",
+ "properties": {
+ "eventName": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 400,
+ "description": "The name of the event to create (e.g. \"user_signed_up\")"
+ },
+ "data": {
+ "description": "Optional metadata for the new event definition",
+ "type": "object",
+ "properties": {
+ "description": {
+ "description": "Description explaining when the event is triggered",
+ "type": "string"
+ },
+ "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",
+ "items": {
+ "type": "string",
+ "maxLength": 255
+ }
+ },
+ "verified": {
+ "description": "Mark as verified to indicate the event is properly instrumented and tracking correctly",
+ "type": "boolean"
+ },
+ "hidden": {
+ "description": "Mark event as no longer used/captured. Hides it from UI while preserving historical data",
+ "type": "boolean"
+ }
+ }
+ }
+ },
+ "required": ["eventName"]
+ },
"EventDefinitionUpdateInputSchema": {
"type": "object",
"properties": {
@@ -282,7 +320,8 @@
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"type": "array",
"items": {
- "type": "string"
+ "type": "string",
+ "maxLength": 255
}
},
"verified": {
@@ -313,7 +352,8 @@
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"type": "array",
"items": {
- "type": "string"
+ "type": "string",
+ "maxLength": 255
}
},
"verified": {
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 51e031aafdba..ee5237d90405 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -690,6 +690,28 @@ export class ApiClient {
}
},
+ createEventDefinition: async ({
+ projectId,
+ eventName,
+ data,
+ }: {
+ projectId: string
+ eventName: string
+ data?: {
+ description?: string
+ tags?: string[]
+ verified?: boolean
+ hidden?: boolean
+ }
+ }): Promise<Result<ApiEventDefinition>> => {
+ const createUrl = `${this.baseUrl}/api/projects/${projectId}/event_definitions/`
+
+ return this.fetchJson<ApiEventDefinition>(createUrl, {
+ method: 'POST',
+ body: JSON.stringify({ name: eventName, ...data }),
+ })
+ },
+
updateEventDefinition: async ({
projectId,
eventName,
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 5008d045810c..c3124e237437 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -418,10 +418,15 @@ export const OrganizationGetAllSchema = z.object({})
export const ProjectGetAllSchema = z.object({})
+const EventDefinitionTagSchema = z
+ .string()
+ .max(255)
+ .refine((tag) => tag.trim().toLowerCase().length <= 255, 'Tag must be at most 255 characters after normalization')
+
export const EventDefinitionUpdateInputSchema = z.object({
description: z.string().optional().describe('Description explaining when the event is triggered'),
tags: z
- .array(z.string())
+ .array(EventDefinitionTagSchema)
.optional()
.describe(
'Tags to organize events by product area (e.g. "checkout", "onboarding") or user journey stage (e.g. "acquisition", "activation", "monetization", "retention")'
@@ -441,6 +446,11 @@ export const EventDefinitionUpdateSchema = z.object({
data: EventDefinitionUpdateInputSchema.describe('The event definition data to update'),
})
+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'),
+})
+
export const PropertyDefinitionUpdateInputSchema = z.object({
description: z.string().optional().describe('Description explaining what the property represents'),
tags: z
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 5ceacf3072bb..7d04c68ba68a 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -43,6 +43,7 @@ import {
// PostHog connections (run this project's tools against a connected project in another org/region)
import { createConnectionCallTool } from './posthogConnections/call'
// Projects
+import createEventDefinition from './projects/createEventDefinition'
import getProjects from './projects/getProjects'
import setActiveProject from './projects/setActive'
import updateEventDefinition from './projects/updateEventDefinition'
@@ -79,6 +80,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
// Projects
'projects-get': getProjects,
'switch-project': setActiveProject,
+ 'event-definition-create': createEventDefinition,
'event-definition-update': updateEventDefinition,
'property-definition-update': updatePropertyDefinition,
diff --git a/services/mcp/src/tools/projects/createEventDefinition.ts b/services/mcp/src/tools/projects/createEventDefinition.ts
new file mode 100644
index 000000000000..ff30a7993050
--- /dev/null
+++ b/services/mcp/src/tools/projects/createEventDefinition.ts
@@ -0,0 +1,45 @@
+import type { z } from 'zod'
+
+import { wrapError } from '@/lib/errors'
+import type { ApiEventDefinition } from '@/schema/api'
+import { EventDefinitionCreateSchema } from '@/schema/tool-inputs'
+import type { Context, ToolBase } from '@/tools/types'
+
+const schema = EventDefinitionCreateSchema
+
+type Params = z.infer<typeof schema>
+
+type Result = ApiEventDefinition & { url: string }
+
+export const createEventDefinitionHandler: ToolBase<typeof schema, Result>['handler'] = async (
+ context: Context,
+ params: Params
+) => {
+ const projectId = await context.stateManager.getProjectId()
+
+ const result = await context.api.projects().createEventDefinition({
+ projectId,
+ eventName: params.eventName,
+ data: params.data,
+ })
+
+ if (!result.success) {
+ // Preserve the typed API error as `cause` so `handleToolError` can
+ // classify a recoverable failure (e.g. a duplicate-name validation
+ // error) instead of counting it as an internal fault.
+ throw wrapError(`Failed to create event definition: ${result.error.message}`, result.error)
+ }
+
+ return {
+ ...result.data,
+ url: `${context.api.getProjectBaseUrl(projectId)}/data-management/events/${encodeURIComponent(result.data.id)}`,
+ }
+}
+
+const tool = (): ToolBase<typeof schema, Result> => ({
+ name: 'event-definition-create',
+ schema,
+ handler: createEventDefinitionHandler,
+})
+
+export default tool
diff --git a/services/mcp/tests/tools/projects.integration.test.ts b/services/mcp/tests/tools/projects.integration.test.ts
index 1a85c8058c16..67e7f35c86be 100644
--- a/services/mcp/tests/tools/projects.integration.test.ts
+++ b/services/mcp/tests/tools/projects.integration.test.ts
@@ -12,6 +12,7 @@ import {
setActiveProjectAndOrg,
validateEnvironmentVariables,
} from '@/shared/test-utils'
+import createEventDefinitionTool from '@/tools/projects/createEventDefinition'
import getProjectsTool from '@/tools/projects/getProjects'
import setActiveProjectTool from '@/tools/projects/setActive'
import updateEventDefinitionTool from '@/tools/projects/updateEventDefinition'
@@ -79,6 +80,48 @@ describe('Projects', { concurrent: false }, () => {
})
})
+ describe('event-definition-create tool', () => {
+ const createTool = createEventDefinitionTool()
+ const createdEventDefinitionIds: string[] = []
+
+ afterEach(async () => {
+ for (const id of createdEventDefinitionIds) {
+ try {
+ await context.api.request({
+ method: 'DELETE',
+ path: `/api/projects/${TEST_PROJECT_ID}/event_definitions/${id}/`,
+ })
+ } catch (error) {
+ console.warn(`Failed to cleanup event definition ${id}:`, error)
+ }
+ }
+ createdEventDefinitionIds.length = 0
+ })
+
+ it('should create a definition for an event with no prior captured event', async () => {
+ const eventName = `mcp_test_event_${uuidv4()}`
+ const result = await createTool.handler(context, {
+ eventName,
+ data: { description: 'Defined before ingestion', tags: ['mcp-test'] },
+ })
+ const eventDef = parseToolResponse(result)
+ createdEventDefinitionIds.push(eventDef.id)
+
+ expect(eventDef.name).toBe(eventName)
+ expect(eventDef.description).toBe('Defined before ingestion')
+ expect(eventDef.tags).toContain('mcp-test')
+ expect(eventDef.url).toContain(`/data-management/events/${eventDef.id}`)
+ })
+
+ it('should throw error when the event definition already exists', async () => {
+ const eventName = `mcp_test_event_${uuidv4()}`
+ const first = await createTool.handler(context, { eventName })
+ createdEventDefinitionIds.push(parseToolResponse(first).id)
+
+ await expect(createTool.handler(context, { eventName })).rejects.toThrow()
+ })
+ })
+
describe('event-definition-update tool', () => {
const updateTool = updateEventDefinitionTool()
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
new file mode 100644
index 000000000000..2c008c6087a5
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/event-definition-create.json
@@ -0,0 +1,39 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "data": {
+ "description": "Optional metadata for the new event definition",
+ "properties": {
+ "description": {
+ "description": "Description explaining when the event is triggered",
+ "type": "string"
+ },
+ "hidden": {
+ "description": "Mark event as no longer used/captured. Hides it from UI while preserving historical data",
+ "type": "boolean"
+ },
+ "tags": {
+ "description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
+ "items": {
+ "maxLength": 255,
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "verified": {
+ "description": "Mark as verified to indicate the event is properly instrumented and tracking correctly",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "eventName": {
+ "description": "The name of the event to create (e.g. \"user_signed_up\")",
+ "maxLength": 400,
+ "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 bfb893c5cced..f414229566b0 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
@@ -15,6 +15,7 @@
"tags": {
"description": "Tags to organize events by product area (e.g. \"checkout\", \"onboarding\") or user journey stage (e.g. \"acquisition\", \"activation\", \"monetization\", \"retention\")",
"items": {
+ "maxLength": 255,
"type": "string"
},
"type": "array"
diff --git a/services/mcp/tests/unit/event-definition-tag-length.test.ts b/services/mcp/tests/unit/event-definition-tag-length.test.ts
new file mode 100644
index 000000000000..148ef14f64b3
--- /dev/null
+++ b/services/mcp/tests/unit/event-definition-tag-length.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest'
+
+import { EventDefinitionCreateSchema } from '@/schema/tool-inputs'
+
+describe('EventDefinitionCreateSchema tag validation', () => {
+ it('rejects tags that exceed the database limit after normalization', () => {
+ const expandingTag = 'İ'.repeat(200)
+
+ expect(expandingTag.length).toBeLessThanOrEqual(255)
+ expect(expandingTag.trim().toLowerCase().length).toBeGreaterThan(255)
+ expect(
+ EventDefinitionCreateSchema.safeParse({
+ eventName: 'test_event',
+ data: { tags: [expandingTag] },
+ }).success
+ ).toBe(false)
+ })
+})