: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(warehouse-sources): set the sync method for many tables at once (#99509)
Daniel RC5832aee52c50
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsxindex f4666ca0d8cf..6aef9aae45e3 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx@@ -57,7 +57,7 @@ import {} from 'products/data_warehouse/frontend/utils'import { DirectQuerySchemasTab } from './DirectQuerySchemasTab'-import { sourceSettingsLogic } from './sourceSettingsLogic'+import { BulkSyncMethod, bulkSyncMethodDisabledReason, sourceSettingsLogic } from './sourceSettingsLogic'const frequencyRank = (frequency: DataWarehouseSyncInterval | null | undefined): number =>frequency ? SYNC_FREQUENCY_ORDER.indexOf(frequency) : -1@@ -657,6 +657,7 @@ function SchemaBulkActions({bulkEnable,bulkDisable,bulkSetFrequency,+ bulkSetSyncMethod,bulkSyncNow,bulkResync,bulkDeleteData,@@ -698,6 +699,22 @@ function SchemaBulkActions({})}+ const onSetSyncMethod = (syncType: BulkSyncMethod): void => {+ LemonDialog.open({+ title: `Set ${pluralize(count, 'table', 'tables')} to ${SyncTypeLabelMap[syncType]}?`,+ description:+ syncType === 'full_refresh'+ ? 'Every sync re-reads the whole table, and every row counts towards your bill. Best for tables that are small, or that have no unique primary key to sync incrementally on.'+ : 'New rows are added without matching them against what is already synced. Rows that change in the source arrive again as duplicates, so this suits tables that are only ever inserted into.',+ primaryButton: {+ children: 'Set sync method',+ type: 'primary',+ onClick: () => run(() => bulkSetSyncMethod(selected, syncType)),+ },+ secondaryButton: { children: 'Cancel', type: 'tertiary' },+ })+ }+const onDisable = (): void => {const hasDataLossType = selected.some((schema) => schema.sync_type === 'cdc' || schema.sync_type === 'webhook')if (!hasDataLossType) {@@ -735,6 +752,24 @@ function SchemaBulkActions({Set frequency</LemonButton></LemonMenu>+ <LemonMenu+ items={[+ {+ label: SyncTypeLabelMap.full_refresh,+ disabledReason: bulkSyncMethodDisabledReason(selected, 'full_refresh'),+ onClick: () => onSetSyncMethod('full_refresh'),+ },+ {+ label: SyncTypeLabelMap.append,+ disabledReason: bulkSyncMethodDisabledReason(selected, 'append'),+ onClick: () => onSetSyncMethod('append'),+ },+ ]}+ >+ <LemonButton type="secondary" size="small">+ Set sync method+ </LemonButton>+ </LemonMenu><LemonButton type="secondary" size="small" onClick={() => run(() => bulkSyncNow(selected))}>Sync now</LemonButton>diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.tsindex f403425ab9b1..26f0bc9786e6 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts@@ -195,6 +195,32 @@ describe('sourceSettingsLogic', () => {expect(logic.values.source?.schemas[0].enabled_columns).toEqual(['id', 'name'])})+ it('bulk sync method edit batches every selected table into one request', async () => {+ jest.spyOn(api.externalDataSources, 'get').mockResolvedValue(+ makeSource([+ makeSchema({ id: 'schema-1', sync_type: 'incremental', incremental_field: 'updated_at' }),+ makeSchema({ id: 'schema-2', sync_type: 'incremental', incremental_field: 'created_at' }),+ ])+ )+ const bulkUpdateSchemasSpy = jest+ .spyOn(api.externalDataSources, 'bulkUpdateSchemas')+ .mockImplementation(async (_id, schemas) => schemas.map((partial) => ({ ...makeSchema(), ...partial })))++ logic = sourceSettingsLogic({ id: 'source-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ jest.useFakeTimers()++ logic.actions.bulkSetSyncMethod(logic.values.source!.schemas, 'full_refresh')+ await jest.advanceTimersByTimeAsync(500)++ expect(bulkUpdateSchemasSpy).toHaveBeenCalledTimes(1)+ expect(bulkUpdateSchemasSpy).toHaveBeenLastCalledWith('source-1', [+ { id: 'schema-1', sync_type: 'full_refresh' },+ { id: 'schema-2', sync_type: 'full_refresh' },+ ])+ })+it('sends a changed writable field discovered by diff, not a fixed allowlist', async () => {// row_filters isn't in any hardcoded list — guards against regressing to an allowlist that drops it.jest.spyOn(api.externalDataSources, 'get').mockResolvedValue(diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.tsindex 44f17c0596f0..a89da30dedb4 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts@@ -5,6 +5,7 @@ import { clampSyncFrequency } from 'products/data_warehouse/frontend/utils'import {buildBulkEnablePayloads,+ bulkSyncMethodDisabledReason,clonePayloadPreservingFiles,effectiveLookbackDays,isSensitiveCredentialField,@@ -231,6 +232,27 @@ describe('schemasEligibleForSync', () => {})})+describe('bulkSyncMethodDisabledReason', () => {+ it.each([+ ['full_refresh' as const, [{ sync_type: 'incremental' }], undefined],+ ['append' as const, [{ sync_type: 'incremental', incremental_field: 'updated_at' }], undefined],+ [+ 'append' as const,+ [{ sync_type: 'incremental', incremental_field: 'updated_at' }, { sync_type: 'full_refresh' }],+ 'Append needs an incremental field, which some selected tables have not got',+ ],+ [+ 'full_refresh' as const,+ [{ sync_type: 'incremental' }, { sync_type: 'cdc' }],+ 'Deselect the CDC and webhook tables first',+ ],+ ['full_refresh' as const, [{ sync_type: 'webhook' }], 'Deselect the CDC and webhook tables first'],+ ])('%s over %j', (syncType, overrides, expected) => {+ const schemas = overrides.map((override) => makeSchema(override as Partial<ExternalDataSourceSchema>))+ expect(bulkSyncMethodDisabledReason(schemas, syncType)).toEqual(expected)+ })+})+describe('schemasNeedingLookbackResync', () => {it('keeps only enabled incremental tables so a raised lookback resyncs stats tables, not entity tables', () => {const source = {diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.tsindex dbb651c8c7c5..ab8c98f33b6f 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts@@ -37,7 +37,7 @@ import {} from '~/types'import { groupTablesBySchema } from 'products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils'-import { SYNC_FREQUENCY_ORDER, clampSyncFrequency } from 'products/data_warehouse/frontend/utils'+import { SYNC_FREQUENCY_ORDER, SyncTypeLabelMap, clampSyncFrequency } from 'products/data_warehouse/frontend/utils'import { sourcesDataLogic } from '../../../shared/logics/sourcesDataLogic'import { availableSourcesLogic } from '../../NewSourceScene/availableSourcesLogic'@@ -85,6 +85,25 @@ function nextJobsPollDelay(softFailureCount: number): number {// Read-only/derived fields to keep out of bulk-update payloads. A denylist (not an allowlist of// writable fields) so new editable fields are sent automatically — a stale allowlist silently// dropped edits like sync_frequency.+// Incremental is missing here on purpose: it merges on a primary key, which differs per table and+// so cannot come from one batch choice.+export type BulkSyncMethod = 'full_refresh' | 'append'++// CDC and webhook tables are held back because moving them off their sync method drops changes+// that only a full resync recovers.+export function bulkSyncMethodDisabledReason(+ schemas: readonly ExternalDataSourceSchema[],+ syncType: BulkSyncMethod+): string | undefined {+ if (schemas.some((schema) => schema.sync_type === 'cdc' || schema.sync_type === 'webhook')) {+ return 'Deselect the CDC and webhook tables first'+ }+ if (syncType === 'append' && schemas.some((schema) => !schema.incremental_field)) {+ return 'Append needs an incremental field, which some selected tables have not got'+ }+ return undefined+}+const NON_WRITABLE_SCHEMA_FIELDS = new Set<keyof ExternalDataSourceSchema>(['id','name',@@ -443,6 +462,13 @@ export interface sourceSettingsLogicActions {frequency: DataWarehouseSyncIntervalschemas: ExternalDataSourceSchema[]}+ bulkSetSyncMethod: (+ schemas: ExternalDataSourceSchema[],+ syncType: BulkSyncMethod+ ) => {+ schemas: ExternalDataSourceSchema[]+ syncType: BulkSyncMethod+ }bulkSyncNow: (schemas: ExternalDataSourceSchema[]) => {schemas: ExternalDataSourceSchema[]}@@ -705,6 +731,10 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([schemas,frequency,}),+ bulkSetSyncMethod: (schemas: ExternalDataSourceSchema[], syncType: BulkSyncMethod) => ({+ schemas,+ syncType,+ }),bulkSyncNow: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),bulkResync: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),bulkDeleteData: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),@@ -1590,6 +1620,13 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([const base = `Updated sync frequency for ${pluralize(schemas.length, 'schema', 'schemas')}`lemonToast.success(clamped > 0 ? `${base} (${clamped} kept at their 5 min minimum)` : base)},+ bulkSetSyncMethod: ({ schemas, syncType }) => {+ // Reuse the debounced single-schema update — these coalesce into one bulk PATCH.+ schemas.forEach((schema) => actions.updateSchema({ ...schema, sync_type: syncType }))+ lemonToast.success(+ `Set ${pluralize(schemas.length, 'schema', 'schemas')} to ${SyncTypeLabelMap[syncType]}`+ )+ },bulkSyncNow: async ({ schemas }) => {// Only schemas that are enabled with a sync method can sync.const eligible = schemasEligibleForSync(schemas)diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pyindex c888974762cd..7c9af17167c5 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py@@ -899,6 +899,16 @@ class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):help_text="Schema updates to apply in a single batch.",)+ # The endpoint is a PATCH, so the schema generator marks every field optional. The body is a+ # batch command that always needs `schemas`, and the generated types and MCP tool must say so.+ @property+ def partial(self) -> bool:+ return False++ @partial.setter+ def partial(self, _value: bool) -> None:+ pass+def _validation_error_message(error: ValidationError) -> str:# DRF normalizes ValidationError.detail to a list or dict (never a bare string).@@ -2071,6 +2081,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"destroy","reload","refresh_schemas",+ "bulk_update_schemas","database_schema","setup","store_credentials",@@ -5541,7 +5552,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixirequest=ExternalDataSourceBulkUpdateSchemasSerializer,responses={200: ExternalDataSchemaSerializer(many=True)},)- @action(methods=["PATCH"], detail=True)+ # The list-shaped response makes the generator add the viewset's search and paging params.+ @action(methods=["PATCH"], detail=True, pagination_class=None, filter_backends=[])def bulk_update_schemas(self, request: Request, *args: Any, **kwargs: Any) -> Response:source = self.get_object()serializer = ExternalDataSourceBulkUpdateSchemasSerializer(data=request.data)diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 45507c02e2e0..094c5137ae22 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -38,7 +38,9 @@ from posthog.schema import (from posthog.models import OrganizationMembership, Teamfrom posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_valuefrom posthog.models.project import Project+from posthog.models.utils import generate_random_token_personalfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.data_warehouse.backend.facade.api import DIRECT_POSTGRES_URL_PATTERN, DIRECT_TRINO_URL_PATTERN@@ -14125,3 +14127,43 @@ class TestRefreshSchemasErrorClassification(SimpleTestCase):assert message == DATABASE_HOST_NOT_ALLOWED_GUIDANCEassert is_expected is True+++class TestExternalDataSourceAPIKeyScopes(APIBaseTest):+ def _make_api_key(self, scopes: list[str]) -> str:+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(user=self.user, label="test", secure_value=hash_key_value(value), scopes=scopes)+ return value++ @parameterized.expand(+ [+ ("external_data_source:write", True),+ ("external_data_source:read", False),+ ]+ )+ def test_bulk_update_schemas_is_a_write_action(self, scope: str, should_have_access: bool) -> None:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type="Stripe",+ job_inputs={"stripe_secret_key": "123"},+ )+ schema = ExternalDataSchema.objects.create(+ name="BalanceTransaction",+ team=self.team,+ source=source,+ should_sync=True,+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ )+ self.client.force_authenticate(None)++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas/",+ {"schemas": [{"id": str(schema.id), "should_sync": False}]},+ format="json",+ headers={"authorization": f"Bearer {self._make_api_key([scope])}"},+ )++ if should_have_access:+ assert response.status_code != status.HTTP_403_FORBIDDEN, response.content+ else:+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.contentdiff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex f922f4e3472d..0786d7006a41 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -4915,9 +4915,9 @@ export interface ExternalDataSourceBulkUpdateSchemaApi {apply_sync_defaults?: boolean}-export interface PatchedExternalDataSourceBulkUpdateSchemasApi {+export interface ExternalDataSourceBulkUpdateSchemasApi {/** Schema updates to apply in a single batch. */- schemas?: ExternalDataSourceBulkUpdateSchemaApi[]+ schemas: ExternalDataSourceBulkUpdateSchemaApi[]}/**@@ -13375,21 +13375,6 @@ export type ExternalDataSourcesListParams = {search?: string}-export type ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams = {- /**- * Number of results to return per page.- */- limit?: number- /**- * The initial index from which to return the results.- */- offset?: number- /**- * A search term.- */- search?: string-}-export type ExternalDataSourcesRepairCdcCreate200 = {success?: booleanschemas_reset?: numberdiff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.tsindex 92e52fbd9d69..735d4c60d741 100644--- a/products/warehouse_sources/frontend/generated/api.ts+++ b/products/warehouse_sources/frontend/generated/api.ts@@ -19,11 +19,11 @@ import type {ExternalDataSchemasCancelCreate200,ExternalDataSchemasListParams,ExternalDataSchemasLogsRetrieveParams,+ ExternalDataSourceBulkUpdateSchemasApi,ExternalDataSourceConnectionOptionApi,ExternalDataSourceCreateApi,ExternalDataSourceCreateResponseApi,ExternalDataSourceSerializersApi,- ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams,ExternalDataSourcesCheckCdcPrerequisitesCreate200,ExternalDataSourcesConnectLinkRetrieveParams,ExternalDataSourcesListParams,@@ -40,7 +40,6 @@ import type {PatchedDestinationLinkApi,PatchedExternalDataDestinationApi,PatchedExternalDataSchemaApi,- PatchedExternalDataSourceBulkUpdateSchemasApi,PatchedExternalDataSourceSerializersApi,SchemaDestinationsApi,SourceConnectLinkApi,@@ -599,24 +598,8 @@ export const externalDataSourcesDestroy = async (})}-export const getExternalDataSourcesBulkUpdateSchemasPartialUpdateUrl = (- projectId: string,- id: string,- params?: ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams-) => {- 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_sources/${id}/bulk_update_schemas/?${stringifiedParams}`- : `/api/projects/${projectId}/external_data_sources/${id}/bulk_update_schemas/`+export const getExternalDataSourcesBulkUpdateSchemasPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/external_data_sources/${id}/bulk_update_schemas/`}/**@@ -625,19 +608,15 @@ export const getExternalDataSourcesBulkUpdateSchemasPartialUpdateUrl = (export const externalDataSourcesBulkUpdateSchemasPartialUpdate = async (projectId: string,id: string,- patchedExternalDataSourceBulkUpdateSchemasApi?: PatchedExternalDataSourceBulkUpdateSchemasApi,- params?: ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams,+ externalDataSourceBulkUpdateSchemasApi: ExternalDataSourceBulkUpdateSchemasApi,options?: RequestInit-): Promise<PaginatedExternalDataSchemaListApi> => {- return apiMutator<PaginatedExternalDataSchemaListApi>(- getExternalDataSourcesBulkUpdateSchemasPartialUpdateUrl(projectId, id, params),- {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedExternalDataSourceBulkUpdateSchemasApi),- }- )+): Promise<ExternalDataSchemaApi[]> => {+ return apiMutator<ExternalDataSchemaApi[]>(getExternalDataSourcesBulkUpdateSchemasPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(externalDataSourceBulkUpdateSchemasApi),+ })}export const getExternalDataSourcesCdcStatusRetrieveUrl = (projectId: string, id: string) => {diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.tsindex 1e71a1b911cd..cac69eb80ce6 100644--- a/products/warehouse_sources/frontend/generated/api.zod.ts+++ b/products/warehouse_sources/frontend/generated/api.zod.ts@@ -524,7 +524,6 @@ export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = /* @__PURE_),}))- .optional().describe('Schema updates to apply in a single batch.'),})diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yamlindex 67bab6d56fda..8cb409790443 100644--- a/products/warehouse_sources/mcp/tools.yaml+++ b/products/warehouse_sources/mcp/tools.yaml@@ -277,9 +277,24 @@ tools:external-data-schemas-update:operation: external_data_schemas_updateenabled: false- external-data-sources-bulk-update-schemas-partial-update:+ external-data-sources-bulk-update-schemas:operation: external_data_sources_bulk_update_schemas_partial_update- enabled: false+ enabled: true+ scopes:+ - external_data_source:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Update many table schemas in one request+ description: >+ Apply sync configuration to several of a source's table schemas at once: enable or disable syncing+ (should_sync), sync_type, sync frequency and UTC time of day, incremental field, and primary key columns.+ Each entry needs the schema id plus the fields to change. Prefer this over looping+ 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source,+ such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before+ anything is written, and a schema that fails is reported by name while the rest of the batch is saved.+ Changes take effect on the next sync, not retroactively.external-data-sources-cdc-status-retrieve:operation: external_data_sources_cdc_status_retrieveenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f2e6390e1312..c490e19047b2 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4964,6 +4964,20 @@"readOnlyHint": true}},+ "external-data-sources-bulk-update-schemas": {+ "description": "Apply sync configuration to several of a source's table schemas at once: enable or disable syncing (should_sync), sync_type, sync frequency and UTC time of day, incremental field, and primary key columns. Each entry needs the schema id plus the fields to change. Prefer this over looping 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source, such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before anything is written, and a schema that fails is reported by name while the rest of the batch is saved. Changes take effect on the next sync, not retroactively.",+ "category": "Warehouse sources",+ "feature": "warehouse_sources",+ "summary": "Update many table schemas in one request",+ "title": "Update many table schemas in one request",+ "required_scopes": ["external_data_source:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"external-data-sources-check-cdc-prerequisites-create": {"description": "Validate that a live Postgres database meets Change Data Capture prerequisites — logical replication enabled (wal_level=logical), replication slot available, publication present, and required permissions. Postgres-only. Returns {valid, errors[]}. Use this before configuring a schema with sync_type=cdc, or to diagnose why an existing CDC sync has started failing.","category": "Warehouse sources",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 4108c856fd67..5eaf94952eaa 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5063,6 +5063,20 @@"readOnlyHint": true}},+ "external-data-sources-bulk-update-schemas": {+ "description": "Apply sync configuration to several of a source's table schemas at once: enable or disable syncing (should_sync), sync_type, sync frequency and UTC time of day, incremental field, and primary key columns. Each entry needs the schema id plus the fields to change. Prefer this over looping 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source, such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before anything is written, and a schema that fails is reported by name while the rest of the batch is saved. Changes take effect on the next sync, not retroactively.",+ "category": "Warehouse sources",+ "feature": "warehouse_sources",+ "summary": "Update many table schemas in one request",+ "title": "Update many table schemas in one request",+ "required_scopes": ["external_data_source:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"external-data-sources-check-cdc-prerequisites-create": {"description": "Validate that a live Postgres database meets Change Data Capture prerequisites — logical replication enabled (wal_level=logical), replication slot available, publication present, and required permissions. Postgres-only. Returns {valid, errors[]}. Use this before configuring a schema with sync_type=cdc, or to diagnose why an existing CDC sync has started failing.","category": "Warehouse sources",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 51655e0d125c..14a8df71bfe7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -37845,6 +37845,11 @@ export namespace Schemas {apply_sync_defaults?: boolean;}+ export interface ExternalDataSourceBulkUpdateSchemas {+ /** Schema updates to apply in a single batch. */+ schemas: ExternalDataSourceBulkUpdateSchema[];+ }+export interface ExternalDataSourceConnectionOption {readonly id: string;/** @nullable */@@ -65771,11 +65776,6 @@ export namespace Schemas {readonly user_access_level?: string | null;}- export interface PatchedExternalDataSourceBulkUpdateSchemas {- /** Schema updates to apply in a single batch. */- schemas?: ExternalDataSourceBulkUpdateSchema[];- }-export type PatchedExternalDataSourceSerializersSchemasItem = { [key: string]: unknown };/**@@ -98877,21 +98877,6 @@ export namespace Schemas {search?: string;};- export type ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- /**- * A search term.- */- search?: string;- };-export type ExternalDataSourcesRepairCdcCreate200 = {success?: boolean;schemas_reset?: number;diff --git a/services/mcp/src/generated/warehouse_sources/api.ts b/services/mcp/src/generated/warehouse_sources/api.tsindex 12c2c0ed906c..ab1d92a92c49 100644--- a/services/mcp/src/generated/warehouse_sources/api.ts+++ b/services/mcp/src/generated/warehouse_sources/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 30 enabled ops+ * PostHog API - MCP 31 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -1853,6 +1853,88 @@ export const ExternalDataSourcesDestroyParams = () => zod.object({),})+/**+ * Create, Read, Update and Delete External data Sources.+ */+export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this external data source.'),+ 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 ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = () => zod.object({+ schemas: zod+ .array(+ zod.object({+ id: zod.string().describe('Schema identifier to update.'),+ should_sync: zod.boolean().optional().describe('Whether the schema should be queryable\/synced.'),+ sync_type: zod+ .union([+ zod+ .enum(['full_refresh', 'incremental', 'append', 'webhook', 'cdc', 'xmin'])+ .describe(+ '\* `full_refresh` - full_refresh\n\* `incremental` - incremental\n\* `append` - append\n\* `webhook` - webhook\n\* `cdc` - cdc\n\* `xmin` - xmin'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Requested sync mode for the schema (incremental, full_refresh, append, cdc, or xmin).\n\n\* `full_refresh` - full_refresh\n\* `incremental` - incremental\n\* `append` - append\n\* `webhook` - webhook\n\* `cdc` - cdc\n\* `xmin` - xmin'+ ),+ incremental_field: zod+ .string()+ .nullish()+ .describe('Incremental cursor field for incremental or append syncs.'),+ incremental_field_type: zod.string().nullish().describe('Type of the incremental cursor field.'),+ sync_frequency: zod.string().nullish().describe('Human-readable sync frequency value.'),+ sync_time_of_day: zod.iso.time({}).nullish().describe('UTC anchor time for scheduled syncs.'),+ primary_key_columns: zod+ .array(zod.string())+ .nullish()+ .describe('Column names for primary key deduplication.'),+ cdc_table_mode: zod+ .union([+ zod+ .enum(['consolidated', 'cdc_only', 'both'])+ .describe('\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'How CDC-backed tables should be exposed.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'+ ),+ enabled_columns: zod+ .array(zod.string())+ .nullish()+ .describe('Columns to sync. Null means sync all columns.'),+ row_filters: zod+ .array(+ zod.object({+ column: zod.string(),+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),+ value: zod+ .unknown()+ .describe(+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."+ ),+ })+ )+ .nullish()+ .describe('Row-filter predicates ANDed onto the source query. Null\/empty means sync all rows.'),+ apply_sync_defaults: zod+ .boolean()+ .optional()+ .describe(+ 'When true and the schema has no sync method configured yet (and this update does not set one), discover the table on the source and fill in default sync settings: incremental sync with an auto-selected tracking column where supported, otherwise append, otherwise full refresh. Ignored for schemas that already have a sync method.'+ ),+ })+ )+ .describe('Schema updates to apply in a single batch.'),+})+/*** Create, Read, Update and Delete External data Sources.*/diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.tsindex 2c0c29f2eedf..a773b27fa507 100644--- a/services/mcp/src/tools/generated/warehouse_sources.ts+++ b/services/mcp/src/tools/generated/warehouse_sources.ts@@ -422,6 +422,40 @@ const externalDataSchemasRetrieve = (): ToolBase<},})+const ExternalDataSourcesBulkUpdateSchemasSchema = () => {+ const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody =+ orvalSchemas.ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody()+ const ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams =+ orvalSchemas.ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams()+ return ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams.omit({ project_id: true }).extend(+ ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody.shape+ )+}++const externalDataSourcesBulkUpdateSchemas = (): ToolBase<+ ReturnType<typeof ExternalDataSourcesBulkUpdateSchemasSchema>,+ Schemas.ExternalDataSchema[]+> => ({+ name: 'external-data-sources-bulk-update-schemas',+ schema: ExternalDataSourcesBulkUpdateSchemasSchema(),+ handler: async (+ context: Context,+ params: z.infer<ReturnType<typeof ExternalDataSourcesBulkUpdateSchemasSchema>>+ ) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.schemas !== undefined) {+ body['schemas'] = params.schemas+ }+ const result = await context.api.request<Schemas.ExternalDataSchema[]>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/${encodeURIComponent(String(params.id))}/bulk_update_schemas/`,+ body,+ })+ return result+ },+})+const ExternalDataSourcesCheckCdcPrerequisitesCreateSchema = () =>z.object({}).extend({ source_type: ExternalDataSourceTypeSchema })@@ -1002,6 +1036,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'external-data-schemas-reload': externalDataSchemasReload,'external-data-schemas-resync': externalDataSchemasResync,'external-data-schemas-retrieve': externalDataSchemasRetrieve,+ 'external-data-sources-bulk-update-schemas': externalDataSourcesBulkUpdateSchemas,'external-data-sources-check-cdc-prerequisites-create': externalDataSourcesCheckCdcPrerequisitesCreate,'external-data-sources-connections-list': externalDataSourcesConnectionsList,'external-data-sources-create': externalDataSourcesCreate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-bulk-update-schemas.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-bulk-update-schemas.jsonnew file mode 100644index 000000000000..154eff7d8b2f--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-bulk-update-schemas.json@@ -0,0 +1,159 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this external data source.",+ "type": "string"+ },+ "schemas": {+ "description": "Schema updates to apply in a single batch.",+ "items": {+ "properties": {+ "apply_sync_defaults": {+ "description": "When true and the schema has no sync method configured yet (and this update does not set one), discover the table on the source and fill in default sync settings: incremental sync with an auto-selected tracking column where supported, otherwise append, otherwise full refresh. Ignored for schemas that already have a sync method.",+ "type": "boolean"+ },+ "cdc_table_mode": {+ "anyOf": [+ {+ "description": "* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both",+ "enum": ["consolidated", "cdc_only", "both"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "How CDC-backed tables should be exposed.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both"+ },+ "enabled_columns": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Columns to sync. Null means sync all columns."+ },+ "id": {+ "description": "Schema identifier to update.",+ "type": "string"+ },+ "incremental_field": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Incremental cursor field for incremental or append syncs."+ },+ "incremental_field_type": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Type of the incremental cursor field."+ },+ "primary_key_columns": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Column names for primary key deduplication."+ },+ "row_filters": {+ "anyOf": [+ {+ "items": {+ "properties": {+ "column": {+ "type": "string"+ },+ "operator": {+ "description": "One of: > >= < <= = != IN \"NOT IN\".",+ "type": "string"+ },+ "value": {+ "description": "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."+ }+ },+ "required": ["column", "operator", "value"],+ "type": "object"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Row-filter predicates ANDed onto the source query. Null/empty means sync all rows."+ },+ "should_sync": {+ "description": "Whether the schema should be queryable/synced.",+ "type": "boolean"+ },+ "sync_frequency": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Human-readable sync frequency value."+ },+ "sync_time_of_day": {+ "anyOf": [+ {+ "pattern": "^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "UTC anchor time for scheduled syncs."+ },+ "sync_type": {+ "anyOf": [+ {+ "description": "* `full_refresh` - full_refresh\n* `incremental` - incremental\n* `append` - append\n* `webhook` - webhook\n* `cdc` - cdc\n* `xmin` - xmin",+ "enum": ["full_refresh", "incremental", "append", "webhook", "cdc", "xmin"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Requested sync mode for the schema (incremental, full_refresh, append, cdc, or xmin).\n\n* `full_refresh` - full_refresh\n* `incremental` - incremental\n* `append` - append\n* `webhook` - webhook\n* `cdc` - cdc\n* `xmin` - xmin"+ }+ },+ "required": ["id"],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["id", "schemas"],+ "type": "object"+}