: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
fix(mcp): accept PostHog UUIDT ids in external-data-sync-logs (#64935)
Daniel RCb7b38817b84e
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex 166cb7987fc1..b018a6a42dc1 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -12,6 +12,7 @@ from rest_framework.response import Responsefrom posthog.hogql.database.database import Database+from posthog.api.log_entries import LogEntryRequestSerializer, LogEntrySerializer, fetch_log_entriesfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.exceptions_capture import capture_exception@@ -1064,7 +1065,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"incremental_fields","delete_data",]- scope_object_read_actions = ["list", "retrieve"]+ scope_object_read_actions = ["list", "retrieve", "logs"]queryset = ExternalDataSchema.objects.all()serializer_class = ExternalDataSchemaSerializerfilter_backends = [filters.SearchFilter]@@ -1098,6 +1099,30 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return Response(status=status.HTTP_204_NO_CONTENT)+ @extend_schema(parameters=[LogEntryRequestSerializer])+ @action(methods=["GET"], detail=True, filter_backends=[])+ def logs(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ instance: ExternalDataSchema = self.get_object()+ param_serializer = LogEntryRequestSerializer(data=request.query_params)+ if not param_serializer.is_valid():+ raise ValidationError(param_serializer.errors)+ params = param_serializer.validated_data+ data = fetch_log_entries(+ team_id=self.team_id,+ log_source="external_data_jobs",+ log_source_id=str(instance.id),+ limit=params["limit"],+ instance_id=params.get("instance_id"),+ after=params.get("after"),+ before=params.get("before"),+ search=params.get("search"),+ level=params["level"].split(",") if params.get("level") else None,+ )+ page = self.paginate_queryset(data)+ if page is not None:+ return self.get_paginated_response(LogEntrySerializer(page, many=True).data)+ return Response(LogEntrySerializer(data, many=True).data)+@action(methods=["POST"], detail=True)def reload(self, request: Request, *args: Any, **kwargs: Any):instance: ExternalDataSchema = self.get_object()diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 86343b5c944c..4e69cc51d61f 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -4581,6 +4581,38 @@ export type ExternalDataSchemasListParams = {search?: string}+export type ExternalDataSchemasLogsRetrieveParams = {+ /**+ * Only return entries after this ISO 8601 timestamp.+ */+ after?: string+ /**+ * Only return entries before this ISO 8601 timestamp.+ */+ before?: string+ /**+ * Filter logs to a specific execution instance.+ * @minLength 1+ */+ instance_id?: string+ /**+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.+ * @minLength 1+ */+ level?: string+ /**+ * Maximum number of log entries to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Case-insensitive substring search across log messages.+ * @minLength 1+ */+ search?: string+}+export type ExternalDataSourcesListParams = {/*** Number of results to return per page.diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.tsindex ed185c233e92..7b04f32c4dc6 100644--- a/products/warehouse_sources/frontend/generated/api.ts+++ b/products/warehouse_sources/frontend/generated/api.ts@@ -12,6 +12,7 @@ import type {DatabaseSchemaRequestApi,ExternalDataSchemaApi,ExternalDataSchemasListParams,+ ExternalDataSchemasLogsRetrieveParams,ExternalDataSourceCreateApi,ExternalDataSourceSerializersApi,ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams,@@ -211,6 +212,38 @@ export const externalDataSchemasIncrementalFieldsCreate = async (})}+export const getExternalDataSchemasLogsRetrieveUrl = (+ projectId: string,+ id: string,+ params?: ExternalDataSchemasLogsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/external_data_schemas/${id}/logs/?${stringifiedParams}`+ : `/api/projects/${projectId}/external_data_schemas/${id}/logs/`+}++export const externalDataSchemasLogsRetrieve = async (+ projectId: string,+ id: string,+ params?: ExternalDataSchemasLogsRetrieveParams,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getExternalDataSchemasLogsRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getExternalDataSchemasReloadCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/external_data_schemas/${id}/reload/`}diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yamlindex 1c7e3d608cf6..2d42c250bcd0 100644--- a/products/warehouse_sources/mcp/tools.yaml+++ b/products/warehouse_sources/mcp/tools.yaml@@ -146,6 +146,9 @@ tools:List all table schemas across all data warehouse sources. Each schema represents one table being synced froman external source. Returns the schema name, sync status, sync frequency, incremental field configuration,and latest error. Use this to see which tables are actively syncing and their health.+ external-data-schemas-logs-retrieve:+ operation: external_data_schemas_logs_retrieve+ enabled: falseexternal-data-schemas-partial-update:operation: external_data_schemas_partial_updateenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 673abea7e254..c5355d3b10dc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -52091,6 +52091,38 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsExternalDataSchemasLogsRetrieveParams = {+ /**+ * Only return entries after this ISO 8601 timestamp.+ */+ after?: string;+ /**+ * Only return entries before this ISO 8601 timestamp.+ */+ before?: string;+ /**+ * Filter logs to a specific execution instance.+ * @minLength 1+ */+ instance_id?: string;+ /**+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.+ * @minLength 1+ */+ level?: string;+ /**+ * Maximum number of log entries to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Case-insensitive substring search across log messages.+ * @minLength 1+ */+ search?: string;+ };+export type EnvironmentsExternalDataSourcesListParams = {/*** Number of results to return per page.@@ -58077,6 +58109,38 @@ export namespace Schemas {search?: string;};+ export type ExternalDataSchemasLogsRetrieveParams = {+ /**+ * Only return entries after this ISO 8601 timestamp.+ */+ after?: string;+ /**+ * Only return entries before this ISO 8601 timestamp.+ */+ before?: string;+ /**+ * Filter logs to a specific execution instance.+ * @minLength 1+ */+ instance_id?: string;+ /**+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.+ * @minLength 1+ */+ level?: string;+ /**+ * Maximum number of log entries to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Case-insensitive substring search across log messages.+ * @minLength 1+ */+ search?: string;+ };+export type ExternalDataSourcesListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/tools/posthogAiTools/externalDataSyncLogs.ts b/services/mcp/src/tools/posthogAiTools/externalDataSyncLogs.tsindex fbdc149d3cb4..741478668a55 100644--- a/services/mcp/src/tools/posthogAiTools/externalDataSyncLogs.ts+++ b/services/mcp/src/tools/posthogAiTools/externalDataSyncLogs.ts@@ -2,12 +2,13 @@ import { z } from 'zod'import type { Context, ToolBase } from '@/tools/types'-import { invokeMcpTool } from './invokeTool'-+// PostHog ids are UUIDTs whose version/variant nibbles don't follow RFC 4122, so `z.uuid()`+// (which enforces those nibbles in Zod 4) rejects valid ids — e.g. a `0` version nibble. Use+// `z.guid()`, which accepts any 8-4-4-4-12 hex string.const schema = z.object({- schema_id: z.uuid().describe('UUID of the external data schema (table) to get sync logs for.'),+ schema_id: z.guid().describe('UUID of the external data schema (table) to get sync logs for.'),job_id: z- .uuid()+ .guid().optional().describe('Optional workflow_run_id to filter logs for a specific sync job. Get this from external-data-sources-jobs.'@@ -24,39 +25,31 @@ type Params = z.infer<typeof schema>const LEVEL_ORDER = ['DEBUG', 'INFO', 'WARNING', 'ERROR'] as const-const tool = (): ToolBase<typeof schema, string> => ({+const tool = (): ToolBase<typeof schema, unknown> => ({name: 'external-data-sync-logs',schema,handler: async (context: Context, params: Params) => {+ const projectId = await context.stateManager.getProjectId()+const minLevel = params.level ?? 'INFO'const minIndex = LEVEL_ORDER.indexOf(minLevel)- const includedLevels = LEVEL_ORDER.slice(minIndex).map((l) => `'${l.toLowerCase()}'`)-- let whereClause = `log_source = 'external_data_jobs' AND log_source_id = '${params.schema_id}'`- whereClause += ` AND lower(level) IN (${includedLevels.join(',')})`+ const includedLevels = LEVEL_ORDER.slice(minIndex).join(',')+ const searchParams = new URLSearchParams()+ searchParams.set('limit', String(params.limit ?? 100))+ searchParams.set('level', includedLevels)if (params.job_id) {- whereClause += ` AND instance_id = '${params.job_id}'`+ searchParams.set('instance_id', params.job_id)}-if (params.search) {- const escaped = params.search.replace(/'/g, "\\'")- whereClause += ` AND message ILIKE '%${escaped}%'`+ searchParams.set('search', params.search)}- const limit = params.limit ?? 100- const query = `SELECT instance_id, timestamp, level, message FROM log_entries WHERE ${whereClause} ORDER BY timestamp DESC LIMIT ${limit}`-- const result = await invokeMcpTool(context, 'execute_sql', {- query,- truncate: true,+ const basePath = `/api/environments/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(params.schema_id)}/logs/`+ return context.api.request<unknown>({+ method: 'GET',+ path: `${basePath}?${searchParams.toString()}`,})-- if (!result.success) {- throw new Error(result.content)- }-- return result.content},})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sync-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sync-logs.jsonindex e3ac09ebd9e3..26c134580146 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sync-logs.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sync-logs.json@@ -4,7 +4,7 @@"job_id": {"description": "Optional workflow_run_id to filter logs for a specific sync job. Get this from external-data-sources-jobs.","format": "uuid",- "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$","type": "string"},"level": {@@ -21,7 +21,7 @@"schema_id": {"description": "UUID of the external data schema (table) to get sync logs for.","format": "uuid",- "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$","type": "string"},"search": {