:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(endpoints): expose audit + materialisation tools via mcp (#60270)
Jovan Sakovic09d179807ff1
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.pyindex 57ecbeb2e660..0d3aac681b82 100644--- a/products/endpoints/backend/api.py+++ b/products/endpoints/backend/api.py@@ -398,6 +398,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, TaggedItemView"openapi_spec","materialization_preview","materialization_status",+ "get_endpoints_last_execution_times",]scope_object_write_actions: list[str] = ["create",diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex 1debae77d0fd..89d5fe129a28 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -929,6 +929,30 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):self.assertIsInstance(query_status["results"], list)self.assertEqual(len(query_status["results"]), 0, query_status)+ def test_get_last_execution_times_with_personal_api_key(self):+ """Personal API key access must be allowed — the MCP server calls this action via a personal API key."""+ create_endpoint_with_version(+ name="test_query_1",+ team=self.team,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ created_by=self.user,+ is_active=True,+ )++ # Drop session auth so the request is authenticated purely by the personal API key,+ # matching how the MCP server reaches this endpoint.+ self.client.logout()++ data = {"names": ["test_query_1"]}+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/last_execution_times/",+ data,+ format="json",+ headers={"authorization": f"Bearer {self.api_key}"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+@parameterized.expand([("valid_900s", 900, status.HTTP_201_CREATED, None),diff --git a/products/endpoints/mcp/tools.yaml b/products/endpoints/mcp/tools.yamlindex 44a2422d6807..26f1f8f5b47d 100644--- a/products/endpoints/mcp/tools.yaml+++ b/products/endpoints/mcp/tools.yaml@@ -149,7 +149,8 @@ tools:title: Get endpoint versionsdescription: >List all versions for an endpoint, in descending order (latest first). Each version contains the query- snapshot, description, data freshness, and materialization status at that point in time.+ snapshot, description, data freshness, last execution time, and materialization status at that point in+ time.endpoints-get-all:operation: endpoints_listenabled: true@@ -166,12 +167,41 @@ tools:Get all API endpoints in the current project. Endpoints expose saved HogQL or insight queries as callableAPI routes. Returns name, description, query, active status, current version, and materialization info foreach endpoint.- endpoints-last-execution-times-create:+ endpoints-last-execution-times:operation: endpoints_last_execution_times_create- enabled: false- endpoints-materialization-preview-create:+ enabled: true+ scopes:+ - endpoint:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get endpoints last execution times+ description: >+ Get the most recent execution time per endpoint (endpoint-level, personal API key calls only). Pass an array+ of endpoint names; returns rows shaped [name, last_executed_at]. Endpoints never called are omitted from the+ response. Use this for a quick endpoint-level recency check during an audit; for per-version usage or+ history, query the query_log table with execute-sql.+ include_params:+ - names+ endpoints-materialization-preview:operation: endpoints_materialization_preview_create- enabled: false+ enabled: true+ scopes:+ - endpoint:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ enrich_url: '{params.name}'+ title: Preview endpoint materialization+ description: >+ Preview the materialization transform for an endpoint before enabling it. Returns the transformed HogQL,+ detected range pairs, and aggregate re-aggregation info, plus a rejection reason if the query is not+ eligible. Supports an optional version body param. Read-only — does not enable materialization.+ include_params:+ - version+ - bucket_overridesendpoints-run-retrieve:operation: endpoints_run_retrieveenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex a56a42988a60..c62508fd1db9 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1474,7 +1474,7 @@}},"endpoint-versions": {- "description": "List all versions for an endpoint, in descending order (latest first). Each version contains the query snapshot, description, data freshness, and materialization status at that point in time.",+ "description": "List all versions for an endpoint, in descending order (latest first). Each version contains the query snapshot, description, data freshness, last execution time, and materialization status at that point in time.","category": "Endpoints","feature": "endpoints","summary": "Get endpoint versions",@@ -1501,6 +1501,34 @@"readOnlyHint": true}},+ "endpoints-last-execution-times": {+ "description": "Get the most recent execution time per endpoint (endpoint-level, personal API key calls only). Pass an array of endpoint names; returns rows shaped [name, last_executed_at]. Endpoints never called are omitted from the response. Use this for a quick endpoint-level recency check during an audit; for per-version usage or history, query the query_log table with execute-sql.",+ "category": "Endpoints",+ "feature": "endpoints",+ "summary": "Get endpoints last execution times",+ "title": "Get endpoints last execution times",+ "required_scopes": ["endpoint:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "endpoints-materialization-preview": {+ "description": "Preview the materialization transform for an endpoint before enabling it. Returns the transformed HogQL, detected range pairs, and aggregate re-aggregation info, plus a rejection reason if the query is not eligible. Supports an optional version body param. Read-only — does not enable materialization.",+ "category": "Endpoints",+ "feature": "endpoints",+ "summary": "Preview endpoint materialization",+ "title": "Preview endpoint materialization",+ "required_scopes": ["endpoint:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"error-tracking-assignment-rules-create": {"description": "Create an error tracking assignment rule for the current project. Provide `filters` to match incoming errors and an `assignee` with `type` (`user` or `role`) plus the matching user ID or role UUID.","category": "Error tracking",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex c520f8781e9d..9fd69b5dceb1 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1504,7 +1504,7 @@}},"endpoint-versions": {- "description": "List all versions for an endpoint, in descending order (latest first). Each version contains the query snapshot, description, data freshness, and materialization status at that point in time.",+ "description": "List all versions for an endpoint, in descending order (latest first). Each version contains the query snapshot, description, data freshness, last execution time, and materialization status at that point in time.","category": "Endpoints","feature": "endpoints","summary": "Get endpoint versions",@@ -1531,6 +1531,34 @@"readOnlyHint": true}},+ "endpoints-last-execution-times": {+ "description": "Get the most recent execution time per endpoint (endpoint-level, personal API key calls only). Pass an array of endpoint names; returns rows shaped [name, last_executed_at]. Endpoints never called are omitted from the response. Use this for a quick endpoint-level recency check during an audit; for per-version usage or history, query the query_log table with execute-sql.",+ "category": "Endpoints",+ "feature": "endpoints",+ "summary": "Get endpoints last execution times",+ "title": "Get endpoints last execution times",+ "required_scopes": ["endpoint:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "endpoints-materialization-preview": {+ "description": "Preview the materialization transform for an endpoint before enabling it. Returns the transformed HogQL, detected range pairs, and aggregate re-aggregation info, plus a rejection reason if the query is not eligible. Supports an optional version body param. Read-only — does not enable materialization.",+ "category": "Endpoints",+ "feature": "endpoints",+ "summary": "Preview endpoint materialization",+ "title": "Preview endpoint materialization",+ "required_scopes": ["endpoint:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"error-tracking-assignment-rules-create": {"description": "Create an error tracking assignment rule for the current project. Provide `filters` to match incoming errors and an `assignee` with `type` (`user` or `role`) plus the matching user ID or role UUID.","category": "Error tracking",diff --git a/services/mcp/src/generated/endpoints/api.ts b/services/mcp/src/generated/endpoints/api.tsindex 2bcbbd9c63a8..5406e4fa5dc6 100644--- a/services/mcp/src/generated/endpoints/api.ts+++ b/services/mcp/src/generated/endpoints/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 9 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -159,6 +159,26 @@ export const EndpointsDestroyParams = /* @__PURE__ */ zod.object({),})+/**+ * Preview the materialization transform for an endpoint. Shows what the query will look like after materialization, including range pair detection and bucket functions.+ */+export const EndpointsMaterializationPreviewCreateParams = /* @__PURE__ */ zod.object({+ name: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const EndpointsMaterializationPreviewCreateBody = /* @__PURE__ */ zod.object({+ version: zod.number().optional(),+ bucket_overrides: zod+ .record(zod.string(), zod.string())+ .nullish()+ .describe('Per-column bucket function overrides, e.g. {"timestamp": "hour"}'),+})+/*** Get materialization status for an endpoint. Supports ?version=N query param.*/@@ -1348,3 +1368,18 @@ export const EndpointsVersionsListQueryParams = /* @__PURE__ */ zod.object({limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),})++/**+ * Get the most recent execution time per endpoint (endpoint-level). Timestamps are recorded by the run path for personal-API-key calls. For per-version usage, query the query_log table directly.+ */+export const EndpointsLastExecutionTimesCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const EndpointsLastExecutionTimesCreateBody = /* @__PURE__ */ zod.object({+ names: zod.array(zod.string()),+})diff --git a/services/mcp/src/tools/generated/endpoints.ts b/services/mcp/src/tools/generated/endpoints.tsindex 7ec3839ca692..0d3dce40d4df 100644--- a/services/mcp/src/tools/generated/endpoints.ts+++ b/services/mcp/src/tools/generated/endpoints.ts@@ -5,7 +5,10 @@ import type { Schemas } from '@/api/generated'import {EndpointsCreateBody,EndpointsDestroyParams,+ EndpointsLastExecutionTimesCreateBody,EndpointsListQueryParams,+ EndpointsMaterializationPreviewCreateBody,+ EndpointsMaterializationPreviewCreateParams,EndpointsMaterializationStatusRetrieveParams,EndpointsOpenapiSpecRetrieveParams,EndpointsOpenapiSpecRetrieveQueryParams,@@ -276,6 +279,54 @@ const endpointsGetAll = (): ToolBase<},})+const EndpointsLastExecutionTimesSchema = EndpointsLastExecutionTimesCreateBody++const endpointsLastExecutionTimes = (): ToolBase<+ typeof EndpointsLastExecutionTimesSchema,+ Schemas.QueryStatusResponse+> => ({+ name: 'endpoints-last-execution-times',+ schema: EndpointsLastExecutionTimesSchema,+ handler: async (context: Context, params: z.infer<typeof EndpointsLastExecutionTimesSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.names !== undefined) {+ body['names'] = params.names+ }+ const result = await context.api.request<Schemas.QueryStatusResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/endpoints/last_execution_times/`,+ body,+ })+ return result+ },+})++const EndpointsMaterializationPreviewSchema = EndpointsMaterializationPreviewCreateParams.omit({+ project_id: true,+}).extend(EndpointsMaterializationPreviewCreateBody.shape)++const endpointsMaterializationPreview = (): ToolBase<typeof EndpointsMaterializationPreviewSchema, unknown> => ({+ name: 'endpoints-materialization-preview',+ schema: EndpointsMaterializationPreviewSchema,+ handler: async (context: Context, params: z.infer<typeof EndpointsMaterializationPreviewSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.version !== undefined) {+ body['version'] = params.version+ }+ if (params.bucket_overrides !== undefined) {+ body['bucket_overrides'] = params.bucket_overrides+ }+ const result = await context.api.request<unknown>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/endpoints/${encodeURIComponent(String(params.name))}/materialization_preview/`,+ body,+ })+ return await withPostHogUrl(context, result, `/endpoints/${params.name}`)+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'endpoint-create': endpointCreate,'endpoint-delete': endpointDelete,@@ -286,4 +337,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'endpoint-update': endpointUpdate,'endpoint-versions': endpointVersions,'endpoints-get-all': endpointsGetAll,+ 'endpoints-last-execution-times': endpointsLastExecutionTimes,+ 'endpoints-materialization-preview': endpointsMaterializationPreview,}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-last-execution-times-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-last-execution-times-create.jsonnew file mode 100644index 000000000000..bf98f4e00395--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-last-execution-times-create.json@@ -0,0 +1,13 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "names": {+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["names"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-last-execution-times.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-last-execution-times.jsonnew file mode 100644index 000000000000..1d131f5fbe83--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-last-execution-times.json@@ -0,0 +1,25 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "include_versions": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "When true, response rows are `[name, version, last_executed_at]` covering every version that has been executed. When false (default), rows are `[name, last_executed_at]` at endpoint granularity."+ },+ "names": {+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["names"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-materialization-preview-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-materialization-preview-create.jsonnew file mode 100644index 000000000000..3d8bf6c6ac68--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-materialization-preview-create.json@@ -0,0 +1,30 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "bucket_overrides": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Per-column bucket function overrides, e.g. {\"timestamp\": \"hour\"}"+ },+ "name": {+ "type": "string"+ },+ "version": {+ "type": "number"+ }+ },+ "required": ["name"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-materialization-preview.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-materialization-preview.jsonnew file mode 100644index 000000000000..3d8bf6c6ac68--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/endpoints-materialization-preview.json@@ -0,0 +1,30 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "bucket_overrides": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Per-column bucket function overrides, e.g. {\"timestamp\": \"hour\"}"+ },+ "name": {+ "type": "string"+ },+ "version": {+ "type": "number"+ }+ },+ "required": ["name"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoints-last-execution-times.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoints-last-execution-times.jsonnew file mode 100644index 000000000000..bf98f4e00395--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoints-last-execution-times.json@@ -0,0 +1,13 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "names": {+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["names"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoints-materialization-preview.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoints-materialization-preview.jsonnew file mode 100644index 000000000000..3d8bf6c6ac68--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoints-materialization-preview.json@@ -0,0 +1,30 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "bucket_overrides": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Per-column bucket function overrides, e.g. {\"timestamp\": \"hour\"}"+ },+ "name": {+ "type": "string"+ },+ "version": {+ "type": "number"+ }+ },+ "required": ["name"],+ "type": "object"+}