: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(data-warehouse): one-shot MCP source setup, connect-link, and import nudges (#62495)
Tom Owers5a97491dce09
diff --git a/.semgrep/rules/idor-team-scoped-models.py b/.semgrep/rules/idor-team-scoped-models.pyindex d39667a5ff20..7b40a86c196f 100644--- a/.semgrep/rules/idor-team-scoped-models.py+++ b/.semgrep/rules/idor-team-scoped-models.py@@ -53,6 +53,13 @@ def safe_filter_with_team(request, team):return Insight.objects.filter(pk=insight_id, team=team)+# ok: idor-taint-user-input-to-model-get+def safe_get_with_for_team(request, team_id):+ cohort_id = request.GET.get("cohort_id")+ # ok: idor-lookup-without-team+ return Cohort.objects.for_team(team_id).get(pk=cohort_id)++# ok: idor-taint-user-input-to-model-getdef not_user_input():# ruleid: idor-lookup-without-teamdiff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 0e9e673e4291..b391b980b2b5 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -182,6 +182,7 @@ rules:|Notebook|ObjectMediaPreview|ParserRecipe+ |PendingSourceCredential|PluginConfig|ProductTour|ProjectSecretAPIKey@@ -252,6 +253,8 @@ rules:- pattern: $M.objects. ... .$METHOD(..., effective_project_id=$T, ...)- pattern: $M.objects. ... .$METHOD(..., team=$T, ...)- pattern: $M.objects. ... .$METHOD(..., team_id=$T, ...)+ # for_team() is the team filter on fail-closed (TeamScopedManager) models+ - pattern: $M.objects.for_team(...). ... .$METHOD(...)# get_object_or_404- pattern: get_object_or_404($M, ..., team__project_id=$T, ...)- pattern: get_object_or_404($M, ..., effective_project_id=$T, ...)@@ -422,6 +425,7 @@ rules:|Notebook|ObjectMediaPreview|ParserRecipe+ |PendingSourceCredential|PluginConfig|ProductTour|ProjectSecretAPIKey@@ -491,6 +495,8 @@ rules:- pattern-not: $M.objects. ... .$METHOD2(..., effective_project_id=$T, ...)- pattern-not: $M.objects. ... .$METHOD2(..., team=$T, ...)- pattern-not: $M.objects. ... .$METHOD2(..., team_id=$T, ...)+ # for_team() is the team filter on fail-closed (TeamScopedManager) models+ - pattern-not: $M.objects.for_team(...). ... .$METHOD2(...)# get_object_or_404- pattern-not: get_object_or_404($M, ..., team__project_id=$T, ...)- pattern-not: get_object_or_404($M, ..., effective_project_id=$T, ...)diff --git a/ee/hogai/tools/execute_sql/import_suggestions.py b/ee/hogai/tools/execute_sql/import_suggestions.pynew file mode 100644index 000000000000..0aa253d3588a--- /dev/null+++ b/ee/hogai/tools/execute_sql/import_suggestions.py@@ -0,0 +1,98 @@+"""Map a missing HogQL table to a data-warehouse source the user could import.++When an ``execute_sql`` query references a table that doesn't exist, it's often a moment where the+user needs external business data (revenue, CRM, support tickets, …) that hasn't been imported yet.+This builds a short, additive hint pointing the agent at ``data-warehouse-source-setup`` so the+"missing table → import a source" path actually fires instead of dead-ending on the error.+"""++import re++# (table-name keywords, candidate source types, human label). First-match-wins per category, but a+# table can match multiple categories (e.g. "customers" is both revenue and CRM) — all are surfaced.+_SOURCE_KEYWORDS: list[tuple[tuple[str, ...], tuple[str, ...], str]] = [+ (+ ("charge", "subscription", "invoice", "payment", "payout", "refund", "revenue", "mrr", "transaction"),+ ("Stripe", "Chargebee"),+ "revenue and payments",+ ),+ (+ ("customer", "contact", "deal", "company", "lead", "opportunity", "crm"),+ ("Hubspot", "Salesforce"),+ "CRM and sales",+ ),+ (("ticket", "support", "helpdesk", "conversation"), ("Zendesk",), "support tickets"),+ (+ ("campaign", "adgroup", "ad_group", "impression", "spend", "ads", "marketing"),+ ("GoogleAds", "MetaAds"),+ "ads and marketing",+ ),+ (("order", "product", "cart", "checkout", "fulfillment", "shop"), ("Shopify", "BigCommerce"), "e-commerce"),+]++_UNKNOWN_TABLE_RE = re.compile(r"[Uu]nknown table `([^`]+)`")+++def extract_unknown_tables(error_message: str) -> list[str]:+ """Pull the table name(s) out of a HogQL ``Unknown table `x`.`` error message."""+ return list(dict.fromkeys(_UNKNOWN_TABLE_RE.findall(error_message)))+++def _strip_prefix(table: str) -> str:+ # Imported tables are usually prefixed (e.g. `stripe_charges`); match on the trailing part too.+ return table.split("_", 1)[1] if "_" in table else table+++def suggest_sources_for_table(table: str) -> list[tuple[tuple[str, ...], str]]:+ """Return (candidate_source_types, label) tuples whose keywords match the table name."""+ name = table.lower()+ bare = _strip_prefix(name)+ matches: list[tuple[tuple[str, ...], str]] = []+ for keywords, sources, label in _SOURCE_KEYWORDS:+ if any(kw in name or kw in bare for kw in keywords):+ matches.append((sources, label))+ return matches+++def build_import_suggestion(missing_tables: list[str], existing_source_types: set[str]) -> str | None:+ """Build an additive hint suggesting a warehouse source for unimported tables.++ ``existing_source_types`` lets us avoid suggesting a source the team already connected (the data+ may simply be under a different prefix). Returns ``None`` when nothing useful can be suggested.+ """+ if not missing_tables:+ return None++ suggested: list[str] = []+ seen: set[str] = set()+ for table in missing_tables:+ for sources, label in suggest_sources_for_table(table):+ fresh = [s for s in sources if s not in existing_source_types]+ key = f"{label}:{','.join(sources)}"+ if not fresh or key in seen:+ continue+ seen.add(key)+ suggested.append(f"- {label}: connect {' or '.join(fresh)}")++ lines = [+ "<data_import_suggestion>",+ "One or more referenced tables don't exist yet. If you're after external business data that "+ "hasn't been imported, set up a data warehouse source with the 'data-warehouse-source-setup' "+ "tool (it validates credentials, discovers tables, and creates the source in one step). For "+ "credentialed sources, prefer the secure connect-link handoff over pasting secrets.",+ ]+ if suggested:+ lines.append("Likely matches for the missing table(s):")+ lines.extend(suggested)+ else:+ lines.append(+ "If this is data from your own database, connect a Postgres, MySQL, BigQuery, or Snowflake source."+ )+ if existing_source_types:+ lines.append(+ "Note: the team already has these source types connected — the data may be under a "+ f"different table prefix: {', '.join(sorted(existing_source_types))}. "+ "Check 'external-data-sources-list' before importing again."+ )+ lines.append("</data_import_suggestion>")+ return "\n".join(lines)diff --git a/ee/hogai/tools/execute_sql/mcp_tool.py b/ee/hogai/tools/execute_sql/mcp_tool.pyindex b28b78596ee6..35a9a656c484 100644--- a/ee/hogai/tools/execute_sql/mcp_tool.py+++ b/ee/hogai/tools/execute_sql/mcp_tool.py@@ -10,11 +10,14 @@ from posthog.hogql.taxonomy_validation import validate_taxonomy_referencesfrom posthog.sync import database_sync_to_async+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from ee.hogai.chat_agent.schema_generator.parsers import PydanticOutputParserExceptionfrom ee.hogai.chat_agent.sql.mixins import HogQLOutputParserMixinfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.mcp_tool import MCPTool, mcp_tool_registryfrom ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tools.execute_sql.import_suggestions import build_import_suggestion, extract_unknown_tablesclass ExecuteSQLMCPToolArgs(BaseModel):@@ -61,7 +64,11 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):try:query = await self._validate_hogql_query(args.query)except PydanticOutputParserException as e:- raise MaxToolRetryableError(f"Query validation failed: {e.validation_message}")+ message = f"Query validation failed: {e.validation_message}"+ suggestion = await self._maybe_import_suggestion(e.validation_message)+ if suggestion:+ message = f"{message}\n\n{suggestion}"+ raise MaxToolRetryableError(message)# Warn (non-fatally) when the query references events/properties absent from the project# taxonomy — the most common silent-wrong-answer surface for agents (e.g. `event = 'purchase'`@@ -81,6 +88,22 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):return _prepend_taxonomy_warnings(results, taxonomy_warnings)+ async def _maybe_import_suggestion(self, validation_message: str) -> str | None:+ """When a query fails on an unknown table, suggest importing a matching warehouse source."""+ missing_tables = extract_unknown_tables(validation_message)+ if not missing_tables:+ return None+ existing_source_types = await self._existing_source_types()+ return build_import_suggestion(missing_tables, existing_source_types)++ @database_sync_to_async(thread_sensitive=False)+ def _existing_source_types(self) -> set[str]:+ return set(+ ExternalDataSource.objects.filter(team_id=self._team.pk, deleted=False).values_list(+ "source_type", flat=True+ )+ )+@database_sync_to_async(thread_sensitive=False)def _get_taxonomy_warnings(self, query: str) -> list[HogQLNotice]:# Re-parse the already-validated query string — cheap (microseconds vs. the ClickHousediff --git a/ee/hogai/tools/execute_sql/test/test_import_suggestions.py b/ee/hogai/tools/execute_sql/test/test_import_suggestions.pynew file mode 100644index 000000000000..f0b7bf868a49--- /dev/null+++ b/ee/hogai/tools/execute_sql/test/test_import_suggestions.py@@ -0,0 +1,71 @@+from parameterized import parameterized++from ee.hogai.tools.execute_sql.import_suggestions import (+ build_import_suggestion,+ extract_unknown_tables,+ suggest_sources_for_table,+)+++class TestExtractUnknownTables:+ @parameterized.expand(+ [+ ("none", "Some other error", []),+ ("single", "Unknown table `charges`.", ["charges"]),+ ("with_suggestion_suffix", "Unknown table `charge`. Did you mean: charges?", ["charge"]),+ (+ "multiple_dedup",+ "Unknown table `charges`. Unknown table `charges`. Unknown table `deals`.",+ ["charges", "deals"],+ ),+ ("lowercase_unknown", "unknown table `orders`.", ["orders"]),+ ]+ )+ def test_extract(self, _name: str, message: str, expected: list[str]) -> None:+ assert extract_unknown_tables(message) == expected+++class TestSuggestSourcesForTable:+ @parameterized.expand(+ [+ ("charges", "Stripe"),+ ("subscriptions", "Stripe"),+ ("stripe_charges", "Stripe"),+ ("deals", "Hubspot"),+ ("tickets", "Zendesk"),+ ("campaigns", "GoogleAds"),+ ("orders", "Shopify"),+ ]+ )+ def test_known_tables_match(self, table: str, expected_source: str) -> None:+ matched_sources = {s for sources, _ in suggest_sources_for_table(table) for s in sources}+ assert expected_source in matched_sources++ def test_unknown_table_has_no_match(self) -> None:+ assert suggest_sources_for_table("widgets_xyz") == []+++class TestBuildImportSuggestion:+ def test_none_when_no_tables(self) -> None:+ assert build_import_suggestion([], set()) is None++ def test_suggests_stripe_for_revenue_table(self) -> None:+ result = build_import_suggestion(["charges"], set())+ assert result is not None+ assert "data-warehouse-source-setup" in result+ assert "Stripe" in result+ assert "<data_import_suggestion>" in result++ def test_generic_fallback_for_unknown_table(self) -> None:+ result = build_import_suggestion(["widgets_xyz"], set())+ assert result is not None+ assert "Postgres" in result++ def test_does_not_resuggest_existing_source_type(self) -> None:+ # Stripe already connected: don't push Stripe again, but flag the existing prefix note.+ result = build_import_suggestion(["charges"], {"Stripe"})+ assert result is not None+ assert "already has these source types" in result+ assert "Stripe" in result+ # Chargebee is still a fresh suggestion for revenue.+ assert "Chargebee" in resultdiff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 40d20727b967..18220e4fc532 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -97,6 +97,8 @@ export const productScenes: Record<string, () => Promise<any>> = {Sources: () => import('../../products/data_warehouse/frontend/scenes/SourcesScene/SourcesScene'),DataWarehouseSource: () => import('../../products/data_warehouse/frontend/scenes/SourceScene/SourceScene'),DataWarehouseSourceNew: () => import('../../products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene'),+ DataWarehouseSourceConnect: () =>+ import('../../products/data_warehouse/frontend/scenes/SourceConnectScene/SourceConnectScene'),DataWarehouseSourceSchema: () => import('../../products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene'),EarlyAccessFeatures: () => import('../../products/early_access_features/frontend/EarlyAccessFeatures'),EarlyAccessFeature: () => import('../../products/early_access_features/frontend/EarlyAccessFeature'),@@ -220,6 +222,7 @@ export const productRoutes: Record<string, [string, string]> = {],'/data-management/sources/:id/:tab': ['DataWarehouseSource', 'dataWarehouseSource'],'/data-warehouse/new-source': ['DataWarehouseSourceNew', 'dataWarehouseSourceNew'],+ '/data-warehouse/connect': ['DataWarehouseSourceConnect', 'dataWarehouseSourceConnect'],'/early_access_features': ['EarlyAccessFeatures', 'earlyAccessFeatures'],'/early_access_features/:id': ['EarlyAccessFeature', 'earlyAccessFeature'],'/endpoints': ['EndpointsScene', 'endpoints'],@@ -596,6 +599,7 @@ export const productConfiguration: Record<string, any> = {},DataWarehouseSource: { projectBased: true, name: 'Data warehouse source' },DataWarehouseSourceNew: { projectBased: true, name: 'New data warehouse source' },+ DataWarehouseSourceConnect: { projectBased: true, name: 'Connect data warehouse source' },DataWarehouseSourceSchema: { projectBased: true, name: 'Data warehouse schema' },EarlyAccessFeatures: {name: 'Early access features',@@ -930,6 +934,8 @@ export const productUrls = {const queryString = params.toString()return `/data-warehouse/new-source${queryString ? `?${queryString}` : ''}`},+ dataWarehouseSourceConnect: (kind?: string): string =>+ `/data-warehouse/connect${kind ? `?kind=${encodeURIComponent(kind)}` : ''}`,earlyAccessFeatures: (): string => '/early_access_features',earlyAccessFeature: (id: string): string => `/early_access_features/${id}`,endpoints: (): string => '/endpoints',@@ -1599,6 +1605,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['Sources','DataWarehouseSource','DataWarehouseSourceNew',+ 'DataWarehouseSourceConnect','DataWarehouseSourceSchema',],},@@ -2238,6 +2245,7 @@ export const getTreeItemsMetadata = (): FileSystemImport[] => ['Sources','DataWarehouseSource','DataWarehouseSourceNew',+ 'DataWarehouseSourceConnect','DataWarehouseSourceSchema',],},diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 7bb98a72c121..e8674f00ba10 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -39,6 +39,7 @@ export enum Scene {DataOps = 'DataOps',DataWarehouseRedirect = 'DataWarehouseRedirect',DataWarehouseSource = 'DataWarehouseSource',+ DataWarehouseSourceConnect = 'DataWarehouseSourceConnect',DataWarehouseSourceNew = 'DataWarehouseSourceNew',DataWarehouseSourceSchema = 'DataWarehouseSourceSchema',DeadLetterQueue = 'DeadLetterQueue',diff --git a/posthog/temporal/data_imports/sources/common/schema.py b/posthog/temporal/data_imports/sources/common/schema.pyindex 59aa9d17cf73..465573b887c6 100644--- a/posthog/temporal/data_imports/sources/common/schema.py+++ b/posthog/temporal/data_imports/sources/common/schema.py@@ -2,6 +2,22 @@ from dataclasses import dataclass, fieldfrom products.data_warehouse.backend.types import IncrementalField+# Preference order (lowercased) for auto-selecting an incremental field. Columns that+# advance on every write (`updated_at`) catch late-arriving updates that creation-only+# columns (`created_at`) miss, so they rank first. Falls back to the first candidate.+_INCREMENTAL_FIELD_PREFERENCE = [+ "updated_at",+ "updatedat",+ "modified_at",+ "modifiedat",+ "last_modified",+ "updated",+ "modified",+ "created_at",+ "createdat",+ "created",+]+@dataclassclass SourceSchema:@@ -25,3 +41,50 @@ class SourceSchema:label: str | None = Nonedetected_primary_keys: list[str] | None = Nonerls_warning: str | None = None+++def _select_incremental_field(incremental_fields: list[IncrementalField]) -> IncrementalField | None:+ """Pick the best incremental field for a table, preferring update-tracking columns."""+ candidates = [f for f in incremental_fields if f.get("field")]+ if not candidates:+ return None+ by_name = {f["field"].lower(): f for f in candidates}+ for name in _INCREMENTAL_FIELD_PREFERENCE:+ if name in by_name:+ return by_name[name]+ return candidates[0]+++def build_default_schemas(source_schemas: list[SourceSchema]) -> list[dict]:+ """Build a default ``schemas`` payload for one-shot source creation.++ Enables every discovered table and picks a sync type per table: ``incremental`` when the+ source supports it and a tracking column exists (cheapest ongoing sync), else ``append``+ when supported, else ``full_refresh``. Never defaults to ``cdc`` — that needs Postgres+ prerequisites and explicit opt-in. Webhook-only tables start disabled because webhook+ registration needs the created source; the setup flow attempts it right after creation+ and, on success, switches webhook-capable tables to the webhook sync method. These+ polling defaults are also the fallback when that registration fails.+ """+ schemas: list[dict] = []+ for source_schema in source_schemas:+ if source_schema.webhook_only:+ schemas.append({"name": source_schema.name, "should_sync": False})+ continue++ chosen = _select_incremental_field(source_schema.incremental_fields)+ if source_schema.supports_incremental and chosen is not None:+ sync_type = "incremental"+ elif source_schema.supports_append and chosen is not None:+ sync_type = "append"+ else:+ sync_type = "full_refresh"++ entry: dict = {"name": source_schema.name, "should_sync": True, "sync_type": sync_type}+ if sync_type in ("incremental", "append") and chosen is not None:+ entry["incremental_field"] = chosen["field"]+ entry["incremental_field_type"] = str(chosen.get("field_type") or chosen.get("type"))+ if source_schema.detected_primary_keys:+ entry["primary_key_columns"] = source_schema.detected_primary_keys+ schemas.append(entry)+ return schemasdiff --git a/posthog/temporal/data_imports/sources/common/test_source_schema.py b/posthog/temporal/data_imports/sources/common/test_source_schema.pynew file mode 100644index 000000000000..e9533a3bad3f--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/test_source_schema.py@@ -0,0 +1,134 @@+from parameterized import parameterized++from posthog.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ _select_incremental_field,+ build_default_schemas,+)++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++def _field(name: str, field_type: IncrementalFieldType = IncrementalFieldType.DateTime) -> IncrementalField:+ return {"label": name, "type": field_type, "field": name, "field_type": field_type, "nullable": False}+++class TestSelectIncrementalField:+ @parameterized.expand(+ [+ ("empty", [], None),+ ("single", ["created_at"], "created_at"),+ ("prefers_updated_at", ["created_at", "updated_at", "id"], "updated_at"),+ ("prefers_modified_over_created", ["created_at", "modified_at"], "modified_at"),+ ("updated_beats_modified", ["modified_at", "updated_at"], "updated_at"),+ ("falls_back_to_first_when_no_known", ["id", "seq"], "id"),+ ("case_insensitive", ["CreatedAt", "UpdatedAt"], "UpdatedAt"),+ ]+ )+ def test_selection(self, _name: str, field_names: list[str], expected: str | None) -> None:+ chosen = _select_incremental_field([_field(n) for n in field_names])+ assert (chosen["field"] if chosen else None) == expected+++class TestBuildDefaultSchemas:+ def test_incremental_when_supported_with_field(self) -> None:+ schemas = build_default_schemas(+ [+ SourceSchema(+ name="orders",+ supports_incremental=True,+ supports_append=True,+ incremental_fields=[_field("created_at"), _field("updated_at")],+ detected_primary_keys=["id"],+ )+ ]+ )+ assert schemas == [+ {+ "name": "orders",+ "should_sync": True,+ "sync_type": "incremental",+ "incremental_field": "updated_at",+ "incremental_field_type": "datetime",+ "primary_key_columns": ["id"],+ }+ ]++ def test_append_when_only_append_supported(self) -> None:+ schemas = build_default_schemas(+ [+ SourceSchema(+ name="events",+ supports_incremental=False,+ supports_append=True,+ incremental_fields=[_field("created_at")],+ )+ ]+ )+ assert schemas[0]["sync_type"] == "append"+ assert schemas[0]["incremental_field"] == "created_at"+ assert "primary_key_columns" not in schemas[0]++ @parameterized.expand(+ [+ ("no_incremental_support", False, False, []),+ ("incremental_support_but_no_field", True, True, []),+ ]+ )+ def test_full_refresh_fallback(+ self, _name: str, supports_incremental: bool, supports_append: bool, fields: list+ ) -> None:+ schemas = build_default_schemas(+ [+ SourceSchema(+ name="dim_table",+ supports_incremental=supports_incremental,+ supports_append=supports_append,+ incremental_fields=fields,+ )+ ]+ )+ assert schemas[0] == {"name": "dim_table", "should_sync": True, "sync_type": "full_refresh"}++ def test_webhook_only_table_left_disabled(self) -> None:+ schemas = build_default_schemas(+ [+ SourceSchema(+ name="discounts",+ supports_incremental=False,+ supports_append=False,+ supports_webhooks=True,+ webhook_only=True,+ )+ ]+ )+ assert schemas == [{"name": "discounts", "should_sync": False}]++ def test_never_defaults_to_cdc(self) -> None:+ schemas = build_default_schemas(+ [+ SourceSchema(+ name="orders",+ supports_incremental=True,+ supports_append=True,+ supports_cdc=True,+ incremental_fields=[_field("updated_at")],+ detected_primary_keys=["id"],+ )+ ]+ )+ assert schemas[0]["sync_type"] == "incremental"++ def test_enables_all_discovered_tables(self) -> None:+ source_schemas = [+ SourceSchema(+ name="a", supports_incremental=True, supports_append=True, incremental_fields=[_field("updated_at")]+ ),+ SourceSchema(name="b", supports_incremental=False, supports_append=False),+ SourceSchema(+ name="c", supports_incremental=False, supports_append=True, incremental_fields=[_field("created_at")]+ ),+ ]+ schemas = build_default_schemas(source_schemas)+ assert [s["name"] for s in schemas] == ["a", "b", "c"]+ assert all(s["should_sync"] for s in schemas)diff --git a/posthog/temporal/data_imports/sources/customer_io/source.py b/posthog/temporal/data_imports/sources/customer_io/source.pyindex 6322de4c635a..84ad13e82ce8 100644--- a/posthog/temporal/data_imports/sources/customer_io/source.py+++ b/posthog/temporal/data_imports/sources/customer_io/source.py@@ -198,6 +198,7 @@ class CustomerIOSource(supports_incremental=False,supports_append=False,supports_webhooks=True,+ webhook_only=True,incremental_fields=[],)for name in CIO_WEBHOOK_SCHEMA_NAMESdiff --git a/posthog/temporal/data_imports/sources/customer_io/tests/test_customer_io_source.py b/posthog/temporal/data_imports/sources/customer_io/tests/test_customer_io_source.pyindex cfb85fa1c052..b7b6fe1ff01e 100644--- a/posthog/temporal/data_imports/sources/customer_io/tests/test_customer_io_source.py+++ b/posthog/temporal/data_imports/sources/customer_io/tests/test_customer_io_source.py@@ -86,6 +86,10 @@ class TestCustomerIOSourceGetSchemas:webhook_supported = {s.name for s in schemas if s.supports_webhooks}assert webhook_supported == set(CIO_WEBHOOK_SCHEMA_NAMES)+ # Webhook tables have no polling endpoint, so webhook must be the only offered method —+ # this is what keeps one-shot setup from enabling them as broken full-refresh syncs.+ webhook_only = {s.name for s in schemas if s.webhook_only}+ assert webhook_only == set(CIO_WEBHOOK_SCHEMA_NAMES)class TestCustomerIOSourceCreateWebhook:diff --git a/posthog/temporal/data_imports/sources/slack/source.py b/posthog/temporal/data_imports/sources/slack/source.pyindex 1477facd074f..cf89ec53dcf2 100644--- a/posthog/temporal/data_imports/sources/slack/source.py+++ b/posthog/temporal/data_imports/sources/slack/source.py@@ -199,6 +199,7 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhooksupports_incremental=False,supports_append=False,supports_webhooks=True,+ webhook_only=True,incremental_fields=[],))diff --git a/posthog/temporal/data_imports/sources/slack/test_slack.py b/posthog/temporal/data_imports/sources/slack/test_slack.pyindex 10d1f0796fbc..4ea500c91fd6 100644--- a/posthog/temporal/data_imports/sources/slack/test_slack.py+++ b/posthog/temporal/data_imports/sources/slack/test_slack.py@@ -408,6 +408,7 @@ class TestSlackSourceGetSchemasForceRefresh:# Webhook is the only valid sync method: full-refresh would wipe the table and# reload nothing, incremental/append have no polling endpoint to read from.assert channel.supports_webhooks is True+ assert channel.webhook_only is Trueassert channel.supports_incremental is Falseassert channel.supports_append is Falseassert channel.incremental_fields == []diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 84ae2c7641fb..c16b482b074a 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -5,9 +5,13 @@ import dataclassesfrom collections.abc import Callablefrom datetime import UTC, datetime, timedeltafrom typing import Any, cast+from urllib.parse import quote+from django.conf import settings+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import transactionfrom django.db.models import Prefetch, Q+from django.utils import timezoneimport structlogimport temporalio@@ -40,7 +44,7 @@ from posthog.temporal.data_imports.cdc.adapters import CDCSourceAdapter, get_cdcfrom posthog.temporal.data_imports.sources import SourceRegistryfrom posthog.temporal.data_imports.sources.common.base import AnySource, ExternalWebhookInfo, FieldType, WebhookSourcefrom posthog.temporal.data_imports.sources.common.config import Config-from posthog.temporal.data_imports.sources.common.schema import SourceSchema+from posthog.temporal.data_imports.sources.common.schema import SourceSchema, build_default_schemasfrom posthog.temporal.data_imports.sources.common.sql import filter_dwh_columns_by_enabled_columns, sql_schema_metadatafrom posthog.temporal.data_imports.sources.common.sql.base import SQLSourcefrom posthog.temporal.data_imports.sources.custom.source import MAX_CUSTOM_SOURCES_PER_TEAM, manifest_request_hosts@@ -68,6 +72,7 @@ from products.data_warehouse.backend.data_load.service import (is_cdc_enabled_for_team,sync_cdc_extraction_schedule,sync_discover_schemas_schedule,+ sync_external_data_job_workflow,trigger_external_data_source_workflow,)from products.data_warehouse.backend.direct_postgres import upsert_direct_postgres_table@@ -97,6 +102,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (sync_old_schemas_with_new_schemas,)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.pending_source_credential import PendingSourceCredentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.models.util import postgres_columns_to_dwh_columns, validate_source_prefix@@ -986,6 +992,136 @@ class ExternalDataSourceCreateSerializer(serializers.Serializer):)+class SourceSetupSerializer(serializers.Serializer):+ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ help_text="The source type to set up (e.g. 'Stripe', 'Postgres', 'Hubspot').",+ )+ payload = serializers.DictField(+ required=False,+ help_text=(+ "Connection details as flat keys for the source_type (discover required fields with the wizard "+ "tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key "+ "(e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} "+ "referencing credentials the user stored via the connect-link page (discover ids with the "+ "stored_credentials endpoint) — they are merged in server-side and deleted once consumed. "+ "A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible "+ "sync defaults."+ ),+ )+ prefix = serializers.CharField(+ max_length=100,+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Table name prefix in HogQL, e.g. 'stripe' produces stripe_charges. Defaults to the source type.",+ )+ description = serializers.CharField(+ max_length=400, required=False, allow_null=True, allow_blank=True, help_text="Human-readable description."+ )+++class SourceSetupWebhookSerializer(serializers.Serializer):+ success = serializers.BooleanField(+ help_text=(+ "Whether the webhook was registered with the external service. When true, webhook-capable tables "+ "(including webhook-only ones) sync via real-time webhooks; when false, tables fall back to the "+ "polling sync defaults and webhook-only tables stay disabled."+ )+ )+ webhook_url = serializers.CharField(+ allow_null=True, help_text="The PostHog endpoint the external service delivers events to."+ )+ error = serializers.CharField(+ allow_null=True, help_text="Why webhook registration failed (e.g. the credentials lack webhook permissions)."+ )+ pending_inputs = serializers.ListField(+ child=serializers.CharField(),+ help_text=(+ "Webhook input names the user still needs to provide (e.g. a signing secret the external API did not "+ "return on create). Submit them via the update_webhook_inputs endpoint."+ ),+ )+++class SourceSetupResponseSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="ID of the created external data source.")+ webhook = SourceSetupWebhookSerializer(+ required=False,+ help_text=(+ "Outcome of automatic webhook registration. Only present for sources that support webhooks "+ "(e.g. Stripe) and have webhook-capable tables."+ ),+ )+++class SourceConnectLinkSerializer(serializers.Serializer):+ source_type = serializers.CharField(help_text="The source type the link is for.")+ auth_method = serializers.ChoiceField(+ choices=["oauth", "credentials"],+ help_text=(+ "'oauth' = the user authorizes in their browser; 'credentials' = the user enters credentials in the "+ "PostHog UI. Either way secrets never pass through the agent."+ ),+ )+ connect_url = serializers.CharField(+ help_text=(+ "Full URL to share with the user. They open it in a browser to authorize or enter credentials directly "+ "in PostHog — credentials never pass through the agent or the chat."+ )+ )+ integration_field = serializers.CharField(+ allow_null=True,+ help_text=(+ "The payload key to pass to data-warehouse-source-setup: for OAuth sources, the source's integration "+ "id key (e.g. 'hubspot_integration_id'); for credential sources, 'credential_id' referencing the "+ "credentials the user stored via the connect page."+ ),+ )+ instructions = serializers.CharField(help_text="Next steps for the agent to relay to the user.")+++class SourceCredentialCreateSerializer(serializers.Serializer):+ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ help_text="The source type these credentials are for (e.g. 'Stripe', 'Postgres').",+ )+ payload = serializers.DictField(+ help_text=(+ "Connection details as flat keys for the source_type — the same fields the create flow accepts "+ "(host, port, password, API key, …). Checked against a live connection before being stored."+ ),+ )+++class SourceCredentialSerializer(serializers.Serializer):+ credential_id = serializers.UUIDField(+ help_text="Stored credential id. Pass to the setup endpoint as {'credential_id': <id>} to create the source."+ )+ source_type = serializers.CharField(help_text="The source type the stored credentials are for.")+ created_at = serializers.DateTimeField(help_text="When the credentials were stored.")+ expires_at = serializers.DateTimeField(+ help_text="When the stored credentials expire. Unconsumed credentials are unusable past this time."+ )+++def _find_oauth_field(config: object) -> dict | None:+ """Recursively find an OAuth field ({type: 'oauth', kind, name, ...}) in a source config dump."""+ if isinstance(config, dict):+ if config.get("type") == "oauth" and config.get("kind"):+ return config+ for value in config.values():+ found = _find_oauth_field(value)+ if found is not None:+ return found+ elif isinstance(config, list):+ for item in config:+ found = _find_oauth_field(item)+ if found is not None:+ return found+ return None++class DatabaseSchemaRequestSerializer(serializers.Serializer):"""Validate credentials and preview available tables from a remote database.@@ -1028,6 +1164,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"reload","refresh_schemas","database_schema",+ "setup",+ "store_credentials","source_prefix","revenue_analytics_config","create_webhook",@@ -1039,7 +1177,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"disable_cdc","update_cdc_settings",]- scope_object_read_actions = ["list", "retrieve", "jobs", "wizard", "webhook_info", "connections", "cdc_status"]+ scope_object_read_actions = [+ "list",+ "retrieve",+ "jobs",+ "wizard",+ "connect_link",+ "stored_credentials",+ "webhook_info",+ "connections",+ "cdc_status",+ ]queryset = ExternalDataSource.objects.all()serializer_class = ExternalDataSourceSerializersfilter_backends = [filters.SearchFilter]@@ -1097,12 +1245,32 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiserializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)- prefix = serializer.validated_data.get("prefix")- description = serializer.validated_data.get("description")- source_type = serializer.validated_data["source_type"]- access_method = serializer.validated_data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)- created_via = serializer.validated_data.get("created_via", ExternalDataSource.CreatedVia.API)+ return self._create_external_data_source(+ request,+ source_type=serializer.validated_data["source_type"],+ payload=serializer.validated_data["payload"],+ prefix=serializer.validated_data.get("prefix"),+ description=serializer.validated_data.get("description"),+ access_method=serializer.validated_data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE),+ created_via=serializer.validated_data.get("created_via", ExternalDataSource.CreatedVia.API),+ )+ def _create_external_data_source(+ self,+ request: Request,+ *,+ source_type: str,+ payload: dict,+ prefix: str | None,+ description: str | None,+ access_method: str,+ created_via: str,+ skip_credential_validation: bool = False,+ ) -> Response:+ # `skip_credential_validation` is set only by the `setup` action, which has already run the+ # full config + credential gate (including the SSRF host check) before discovering schemas.+ # It avoids a second live credential round-trip — and the confusing failure mode where the+ # first check passes but a transient blip fails the second, leaving nothing created.is_direct_postgres = (access_method == ExternalDataSource.AccessMethod.DIRECT and source_type == ExternalDataSourceType.POSTGRES)@@ -1143,7 +1311,6 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi)# Strip leading and trailing whitespace- payload = serializer.validated_data["payload"]if payload is not None:for key, value in payload.items():if isinstance(value, str):@@ -1158,25 +1325,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidata={"message": CUSTOM_SOURCE_LIMIT_MESSAGE},)source = SourceRegistry.get_source(source_type_model)- is_valid, errors = source.validate_config(payload)- if not is_valid:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Invalid source config: {', '.join(errors)}"},- )- source_config: Config = source.parse_config(payload)-- if source_type_model == ExternalDataSourceType.POSTGRES and isinstance(source, PostgresSource):- credentials_valid, credentials_error = source.validate_credentials_for_access_method(- cast(Any, source_config), self.team_id, access_method- )+ if skip_credential_validation:+ source_config: Config = source.parse_config(payload)else:- credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)- if not credentials_valid:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": credentials_error or "Invalid credentials"},+ error_response, validated_config = self._validate_source_config_and_credentials(+ source, source_type_model, payload, access_method=access_method)+ if error_response is not None or validated_config is None:+ return error_response or Response(status=status.HTTP_400_BAD_REQUEST)+ source_config = validated_confignew_source_model = ExternalDataSource.objects.create(source_id=str(uuid.uuid4()),@@ -1917,6 +2074,299 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi]return Response(status=status.HTTP_200_OK, data=data)+ @extend_schema(request=SourceSetupSerializer, responses={201: SourceSetupResponseSerializer})+ @action(methods=["POST"], detail=False)+ def setup(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """One-shot data warehouse source setup.++ Validate credentials, discover available tables, enable them all with sensible sync defaults+ (incremental where supported, else append, else full refresh), and create the source in a single+ call — the caller never has to assemble a `schemas` array. For sources that support webhooks+ (e.g. Stripe), a webhook is auto-registered after creation: on success webhook-capable tables+ switch to real-time webhook sync (unlocking webhook-only tables); on failure the polling+ defaults stay in place. For fine-grained table/sync control, use the lower-level+ `database_schema` + `create` flow instead.+ """+ # No database context needed here (unlike the read serializer), and skipping it avoids building+ # the HogQL Database on this hot path.+ serializer = SourceSetupSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ source_type = serializer.validated_data["source_type"]+ payload = dict(serializer.validated_data.get("payload") or {})++ credential: PendingSourceCredential | None = None+ credential_id = payload.pop("credential_id", None)+ if credential_id is not None:+ try:+ credential = PendingSourceCredential.objects.for_team(self.team_id).get(+ id=credential_id, expires_at__gt=timezone.now()+ )+ except (PendingSourceCredential.DoesNotExist, ValueError, TypeError, DjangoValidationError):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Stored credential '{credential_id}' not found or expired"},+ )+ if credential.source_type != source_type:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Stored credential '{credential_id}' is for "+ f"'{credential.source_type}', not '{source_type}'"+ },+ )+ # Stored credentials win over inline keys so an agent can't override what the user entered.+ payload = {**payload, **credential.payload}++ source_type_model = ExternalDataSourceType(source_type)+ source = SourceRegistry.get_source(source_type_model)++ error_response, source_config = self._validate_source_config_and_credentials(source, source_type_model, payload)+ if error_response is not None or source_config is None:+ return error_response or Response(status=status.HTTP_400_BAD_REQUEST)++ try:+ source_schemas = source.get_schemas(source_config, self.team_id)+ except Exception as e:+ capture_exception(e, {"source_type": source_type, "team_id": self.team_id})+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})++ if not source_schemas:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "No tables found for this source. Check the credentials and permissions."},+ )++ # Build the schemas array server-side so the caller never has to. We've already validated+ # config + credentials above, so `_create_external_data_source` skips that second gate+ # (`skip_credential_validation`) to avoid a duplicate live credential round-trip.+ payload["schemas"] = build_default_schemas(source_schemas)++ response = self._create_external_data_source(+ request,+ source_type=source_type,+ payload=payload,+ prefix=serializer.validated_data.get("prefix"),+ description=serializer.validated_data.get("description"),+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,+ created_via=ExternalDataSource.CreatedVia.MCP,+ skip_credential_validation=True,+ )+ # Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.+ if credential is not None and response.status_code == status.HTTP_201_CREATED:+ credential.delete()++ if response.status_code == status.HTTP_201_CREATED and isinstance(source, WebhookSource):+ webhook_result = self._auto_register_webhook(+ source, source_config, str(response.data["id"]), source_schemas+ )+ if webhook_result is not None:+ response.data["webhook"] = webhook_result+ return response++ def _auto_register_webhook(+ self,+ source: WebhookSource,+ source_config: Config,+ source_id: str,+ source_schemas: list[SourceSchema],+ ) -> dict | None:+ """Best-effort webhook auto-registration for one-shot setup.++ The source was just created with polling sync defaults (webhook-only tables disabled). If the+ source supports webhook auto-creation and the credentials allow it, register the webhook and+ switch every webhook-capable table to the webhook sync method — unlocking webhook-only tables.+ Failure never breaks setup: the polling defaults stay in place and webhook-only tables remain+ disabled, exactly as if the source didn't support webhooks.+ """+ webhook_capable = {s.name for s in source_schemas if s.supports_webhooks}+ if not webhook_capable or source.webhook_template is None:+ return None++ instance = ExternalDataSource.objects.get(pk=source_id, team_id=self.team_id)+ eligible_schemas = list(+ ExternalDataSchema.objects.filter(source=instance, team_id=self.team_id, name__in=webhook_capable).exclude(+ deleted=True+ )+ )+ if not eligible_schemas:+ return None++ def failure(error: str | None) -> dict:+ return {"success": False, "webhook_url": None, "error": error, "pending_inputs": []}++ try:+ hog_fn_result = get_or_create_webhook_hog_function(+ team=self.team,+ source=source,+ source_id=str(instance.pk),+ eligible_schemas=eligible_schemas,+ )+ if hog_fn_result.error or hog_fn_result.hog_function is None:+ return failure(hog_fn_result.error)++ registration = create_and_register_webhook(source, source_config, hog_fn_result, self.team_id)+ except Exception as e:+ capture_exception(e, {"source_id": source_id, "team_id": self.team_id})+ return failure(str(e))++ if not registration.success:+ # The external registration failed (e.g. credentials can't create webhooks), so the+ # handler would never receive events — remove it and keep the polling defaults.+ hog_function = hog_fn_result.hog_function+ hog_function.deleted = True+ hog_function.enabled = False+ hog_function.save(update_fields=["deleted", "enabled"])+ return failure(registration.error)++ for schema in eligible_schemas:+ newly_enabled = not schema.should_sync+ schema.sync_type = ExternalDataSchema.SyncType.WEBHOOK+ schema.should_sync = True+ schema.save(update_fields=["sync_type", "should_sync"])+ if newly_enabled:+ # Webhook-only tables were created disabled, so no sync schedule exists yet. The+ # schedule still matters for webhook schemas: it ingests the buffered webhook events.+ try:+ sync_external_data_job_workflow(schema, create=True)+ except Exception as e:+ logger.exception(+ "Could not create sync schedule for webhook schema", exc_info=e, schema_id=str(schema.id)+ )++ return {+ "success": True,+ "webhook_url": registration.webhook_url,+ "error": None,+ "pending_inputs": list(registration.pending_inputs),+ }++ def _validate_source_config_and_credentials(+ self,+ source: AnySource,+ source_type_model: ExternalDataSourceType,+ payload: dict,+ access_method: str = ExternalDataSource.AccessMethod.WAREHOUSE,+ ) -> tuple[Response | None, Config | None]:+ """Run the config + live credential gate (including the SSRF host check) for a source payload."""+ is_valid, errors = source.validate_config(payload)+ if not is_valid:+ return (+ Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid source config: {', '.join(errors)}"},+ ),+ None,+ )+ source_config: Config = source.parse_config(payload)++ if source_type_model == ExternalDataSourceType.POSTGRES and isinstance(source, PostgresSource):+ credentials_valid, credentials_error = source.validate_credentials_for_access_method(+ cast(Any, source_config), self.team_id, access_method+ )+ else:+ credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)+ if not credentials_valid:+ return (+ Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": credentials_error or "Invalid credentials"},+ ),+ None,+ )+ return None, source_config++ @extend_schema(request=SourceCredentialCreateSerializer, responses={201: SourceCredentialSerializer})+ @action(methods=["POST"], detail=False)+ def store_credentials(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Validate and store credentials for a data warehouse source without creating the source.++ Backs the source connect page: the user enters credentials directly in PostHog, they are+ checked against a live connection, then stashed encrypted in a temporary store. The returned+ credential id can be passed to `setup` as {'credential_id': <id>} to create the source — so+ secrets never travel through an agent conversation. The stash is single-use: it is deleted+ as soon as `setup` consumes it, and expires after 24 hours if never consumed.+ """+ serializer = SourceCredentialCreateSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ source_type = serializer.validated_data["source_type"]+ payload = dict(serializer.validated_data["payload"])++ for key, value in payload.items():+ if isinstance(value, str):+ payload[key] = value.strip()++ source_type_model = ExternalDataSourceType(source_type)+ source = SourceRegistry.get_source(source_type_model)++ error_response, _ = self._validate_source_config_and_credentials(source, source_type_model, payload)+ if error_response is not None:+ return error_response++ # Opportunistically purge expired stashes — there is no separate cleanup job.+ PendingSourceCredential.objects.for_team(self.team_id).filter(expires_at__lte=timezone.now()).delete()++ credential = PendingSourceCredential.objects.create(+ team_id=self.team_id,+ source_type=source_type,+ payload=payload,+ created_by=cast(User, request.user),+ )++ return Response(+ status=status.HTTP_201_CREATED,+ data=SourceCredentialSerializer(+ {+ "credential_id": credential.id,+ "source_type": source_type,+ "created_at": credential.created_at,+ "expires_at": credential.expires_at,+ }+ ).data,+ )++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="source_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres').",+ )+ ],+ responses=SourceCredentialSerializer(many=True),+ )+ @action(methods=["GET"], detail=False, pagination_class=None)+ def stored_credentials(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """List credentials stored via the source connect page that haven't been consumed yet.++ Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored+ credentials are temporary: they disappear once consumed by `setup` or when they expire.+ Newest first, so after a user confirms they've finished the connect page, the first entry+ for the source type is the one to pass to `setup`.+ """+ queryset = (+ PendingSourceCredential.objects.for_team(self.team_id)+ .filter(expires_at__gt=timezone.now())+ .order_by("-created_at")+ )+ source_type = request.query_params.get("source_type")+ if source_type:+ queryset = queryset.filter(source_type=source_type)++ data = [+ {+ "credential_id": credential.id,+ "source_type": credential.source_type,+ "created_at": credential.created_at,+ "expires_at": credential.expires_at,+ }+ for credential in queryset+ ]+ return Response(status=status.HTTP_200_OK, data=SourceCredentialSerializer(data, many=True).data)+@extend_schema(request=None,responses={@@ -2453,6 +2903,82 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixireturn Response(status=status.HTTP_200_OK, data=results)+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="source_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=True,+ description="The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').",+ )+ ],+ responses=SourceConnectLinkSerializer,+ )+ @action(methods=["GET"], detail=False)+ def connect_link(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Return a secure browser link for connecting a data warehouse source.++ For OAuth sources the link starts the OAuth authorize flow; for credential sources it opens a minimal+ connect page where the user enters only their credentials — no table selection, no source creation.+ Either way the user authenticates in their browser, credentials never pass through the agent, and the+ agent finishes setup afterwards by passing the resulting reference (integration id or credential id)+ to data-warehouse-source-setup.+ """+ source_type = request.query_params.get("source_type")+ if not source_type:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Missing required parameter: source_type"},+ )+ try:+ source_type_model = ExternalDataSourceType(source_type)+ except ValueError:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Unknown source_type '{source_type}'"},+ )++ source = SourceRegistry.get_source(source_type_model)+ oauth_field = _find_oauth_field(source.get_source_config.model_dump())++ # Minimal connect page: credentials only — no table selection, no source creation in the UI.+ ui_path = f"/project/{self.team_id}/data-warehouse/connect?kind={quote(str(source_type))}"++ if oauth_field is not None:+ connect_url = (+ f"{settings.SITE_URL}/api/integrations/authorize"+ f"?kind={quote(oauth_field['kind'])}&next={quote(ui_path, safe='')}"+ )+ data = {+ "source_type": source_type,+ "auth_method": "oauth",+ "connect_url": connect_url,+ "integration_field": oauth_field["name"],+ "instructions": (+ f"Share this link with the user to authorize {source_type} in their browser. Once they confirm "+ f"they're done, find the new integration id via integrations-list (kind='{oauth_field['kind']}') "+ f'and call data-warehouse-source-setup with {{"{oauth_field["name"]}": <integration id>}}. '+ "Never ask the user to paste OAuth tokens into the chat."+ ),+ }+ else:+ data = {+ "source_type": source_type,+ "auth_method": "credentials",+ "connect_url": f"{settings.SITE_URL}{ui_path}",+ "integration_field": "credential_id",+ "instructions": (+ f"Share this link with the user. They enter their {source_type} credentials directly in PostHog "+ "(over TLS) — never ask them to paste credentials into the chat. The page only stores the "+ "credentials; it does not create the source. Once the user confirms they're done, find the "+ f"stored credential id via data-warehouse-stored-credentials-list (source_type='{source_type}', "+ 'newest first) and call data-warehouse-source-setup with {"credential_id": <id>} in the payload. '+ "Stored credentials are single-use and expire after 24 hours."+ ),+ }+ return Response(status=status.HTTP_200_OK, data=SourceConnectLinkSerializer(data).data)+@extend_schema(responses=ExternalDataSourceConnectionOptionSerializer(many=True))@action(methods=["GET"], detail=False)def connections(self, request: Request, *args: Any, **kwargs: Any) -> Response:diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex effc9d4950e1..25194a5d0039 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -1,6 +1,7 @@import jsonimport uuidimport typing as t+from datetime import timedeltafrom typing import castfrom freezegun import freeze_time@@ -9,6 +10,7 @@ from unittest.mock import MagicMock, Mock, PropertyMock, patchfrom django.conf import settingsfrom django.test import override_settings+from django.utils import timezoneimport psycopgfrom parameterized import parameterized@@ -29,7 +31,7 @@ from posthog.models import Teamfrom posthog.models.project import Projectfrom posthog.temporal.data_imports.sources import SourceRegistryfrom posthog.temporal.data_imports.sources.bigquery.bigquery import BigQuerySourceConfig-from posthog.temporal.data_imports.sources.common.base import FieldType+from posthog.temporal.data_imports.sources.common.base import FieldType, WebhookCreationResultfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.custom.source import MAX_CUSTOM_SOURCES_PER_TEAMfrom posthog.temporal.data_imports.sources.postgres.postgres import PostgresDiscoveredSchema@@ -69,6 +71,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (sync_frequency_interval_to_sync_frequency,)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.pending_source_credential import PendingSourceCredentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -8414,3 +8417,418 @@ class TestCDCStatus(APIBaseTest):response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/cdc_status/")assert response.status_code == 400assert "Could not connect to source" in response.json()["message"]+++class TestExternalDataSourceConnectLink(APIBaseTest):+ def _connect_link(self, source_type: str):+ return self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/connect_link?source_type={source_type}"+ )++ def test_connect_link_oauth_source(self):+ response = self._connect_link("Hubspot")+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["auth_method"] == "oauth"+ assert data["integration_field"] == "hubspot_integration_id"+ assert "/api/integrations/authorize?kind=hubspot" in data["connect_url"]+ # The post-auth return path lands on the minimal connect page, not the full wizard.+ assert "data-warehouse%2Fconnect" in data["connect_url"]++ def test_connect_link_credentials_source(self):+ response = self._connect_link("Postgres")+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["auth_method"] == "credentials"+ assert data["integration_field"] == "credential_id"+ assert f"/project/{self.team.pk}/data-warehouse/connect?kind=Postgres" in data["connect_url"]++ def test_connect_link_missing_source_type(self):+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connect_link")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_connect_link_unknown_source_type(self):+ response = self._connect_link("NotARealSource")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+++class TestExternalDataSourceSetup(APIBaseTest):+ # Stripe enables revenue analytics, whose post-create view sync builds the HogQL Database — patched+ # out here so the test exercises setup's own logic rather than that unrelated side effect.+ @patch("products.data_warehouse.backend.api.external_data_source.ensure_person_join")+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_setup_creates_source_with_all_tables_and_mcp_created_via(+ self, _mock_validate, _mock_sync_views, _mock_person_join+ ):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={+ "source_type": "Stripe",+ "prefix": "stripe_setup_test",+ "payload": {"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"}},+ },+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ source = ExternalDataSource.objects.get(pk=response.json()["id"])+ assert source.created_via == ExternalDataSource.CreatedVia.MCP+ assert source.prefix == "stripe_setup_test"++ schemas = ExternalDataSchema.objects.filter(source=source)+ # Every discovered Stripe endpoint becomes a schema...+ assert schemas.count() == len(STRIPE_ENDPOINTS)+ # ...and the syncable ones are enabled with a sync type (incremental for Stripe's created-based tables).+ synced = schemas.filter(should_sync=True)+ assert synced.exists()+ assert all(s.sync_type in ("incremental", "append", "full_refresh") for s in synced)++ def _create_stripe_webhook_template(self):+ from products.cdp.backend.models.hog_function_template import HogFunctionTemplate++ return HogFunctionTemplate.objects.create(+ template_id="template-warehouse-source-stripe",+ name="Stripe warehouse source webhook",+ description="Receive Stripe webhook events for data warehouse ingestion",+ code="// test code",+ code_language="hog",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ },+ {"type": "json", "key": "schema_mapping", "label": "Schema mapping", "required": True, "hidden": True},+ {"type": "string", "key": "source_id", "label": "Source ID", "required": True, "hidden": True},+ ],+ type="warehouse_source_webhook",+ status="alpha",+ category=[],+ )++ def _setup_stripe(self):+ return self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={+ "source_type": "Stripe",+ "prefix": "stripe_webhook_test",+ "payload": {"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"}},+ },+ )++ @patch("products.data_warehouse.backend.api.external_data_source.ensure_person_join")+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook",+ return_value=WebhookCreationResult(success=True, extra_inputs={"signing_secret": "whsec_123"}),+ )+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_setup_auto_registers_webhook_and_switches_capable_tables(+ self, _mock_validate, _mock_create_webhook, _mock_sync_views, _mock_person_join+ ):+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction++ self._create_stripe_webhook_template()+ response = self._setup_stripe()+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ data = response.json()+ assert data["webhook"]["success"] is True+ assert "/public/webhooks/dwh/" in data["webhook"]["webhook_url"]+ assert data["webhook"]["error"] is None+ assert data["webhook"]["pending_inputs"] == []++ schemas = ExternalDataSchema.objects.filter(source_id=data["id"])+ # Webhook-only tables (no list API) are unlocked by the registered webhook...+ webhook_only = schemas.get(name=STRIPE_DISCOUNT_RESOURCE_NAME)+ assert webhook_only.should_sync is True+ assert webhook_only.sync_type == ExternalDataSchema.SyncType.WEBHOOK+ # ...and dual-capability tables switch from polling to real-time webhook sync.+ customer = schemas.get(name=STRIPE_CUSTOMER_RESOURCE_NAME)+ assert customer.should_sync is True+ assert customer.sync_type == ExternalDataSchema.SyncType.WEBHOOK++ hog_function = HogFunction.objects.get(team=self.team, type="warehouse_source_webhook", deleted=False)+ assert hog_function.enabled is True+ assert hog_function.inputs is not None+ assert hog_function.inputs["source_id"]["value"] == data["id"]++ @patch("products.data_warehouse.backend.api.external_data_source.ensure_person_join")+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook",+ return_value=WebhookCreationResult(success=False, error="This API key lacks webhook permissions"),+ )+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_setup_falls_back_to_polling_when_webhook_registration_fails(+ self, _mock_validate, _mock_create_webhook, _mock_sync_views, _mock_person_join+ ):+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction++ self._create_stripe_webhook_template()+ response = self._setup_stripe()+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ data = response.json()+ assert data["webhook"]["success"] is False+ assert "lacks webhook permissions" in data["webhook"]["error"]++ schemas = ExternalDataSchema.objects.filter(source_id=data["id"])+ # Webhook-only tables have no polling fallback, so they stay disabled...+ webhook_only = schemas.get(name=STRIPE_DISCOUNT_RESOURCE_NAME)+ assert webhook_only.should_sync is False+ # ...while dual-capability tables keep their polling sync defaults.+ customer = schemas.get(name=STRIPE_CUSTOMER_RESOURCE_NAME)+ assert customer.should_sync is True+ assert customer.sync_type in ("incremental", "append", "full_refresh")+ # The orphaned handler is removed so nothing dangles.+ assert not HogFunction.objects.filter(team=self.team, type="warehouse_source_webhook", deleted=False).exists()++ @patch("products.data_warehouse.backend.api.external_data_source.ensure_person_join")+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")+ @patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_setup_keeps_polling_defaults_when_webhook_template_missing(+ self, _mock_validate, mock_create_webhook, _mock_sync_views, _mock_person_join+ ):+ response = self._setup_stripe()+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ data = response.json()+ assert data["webhook"]["success"] is False+ assert "sync_hog_function_templates" in data["webhook"]["error"]+ mock_create_webhook.assert_not_called()++ schemas = ExternalDataSchema.objects.filter(source_id=data["id"])+ assert schemas.get(name=STRIPE_DISCOUNT_RESOURCE_NAME).should_sync is False+ customer = schemas.get(name=STRIPE_CUSTOMER_RESOURCE_NAME)+ assert customer.sync_type in ("incremental", "append", "full_refresh")++ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(False, "Missing Stripe API key"),+ )+ def test_setup_returns_credential_error(self, _mock_validate):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={"source_type": "Stripe", "payload": {"auth_method": {"selection": "api_key"}}},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Missing Stripe API key" in response.json()["message"]+ assert not ExternalDataSource.objects.exists()++ def _store_stripe_credential(self, team=None, **kwargs) -> PendingSourceCredential:+ team = team or self.team+ return PendingSourceCredential.objects.for_team(team.pk).create(+ team=team,+ source_type="Stripe",+ payload={"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_stored"}},+ **kwargs,+ )++ @patch("products.data_warehouse.backend.api.external_data_source.ensure_person_join")+ @patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_setup_with_credential_id_merges_stored_payload(self, mock_validate, _mock_sync_views, _mock_person_join):+ credential = self._store_stripe_credential()+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={"source_type": "Stripe", "payload": {"credential_id": str(credential.pk)}},+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ source = ExternalDataSource.objects.get(pk=response.json()["id"])+ assert source.created_via == ExternalDataSource.CreatedVia.MCP+ # The stored secret was merged in server-side and used for validation.+ validated_config = mock_validate.call_args.args[0]+ assert validated_config.auth_method.stripe_secret_key == "sk_test_stored"+ # Stored credentials are single-use — consumed on successful setup.+ assert not PendingSourceCredential.objects.for_team(self.team.pk).exists()++ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(False, "Invalid Stripe API key"),+ )+ def test_setup_failure_keeps_stored_credential(self, _mock_validate):+ credential = self._store_stripe_credential()+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={"source_type": "Stripe", "payload": {"credential_id": str(credential.pk)}},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert PendingSourceCredential.objects.for_team(self.team.pk).filter(pk=credential.pk).exists()++ @parameterized.expand(+ [+ ("missing", "ba07775f-8eaf-4d09-aa6f-50e37f17f243"),+ ("not_a_uuid", "abc"),+ ("not_a_string", 999999),+ ]+ )+ def test_setup_with_unknown_credential_id_returns_400(self, _name, credential_id):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={"source_type": "Stripe", "payload": {"credential_id": credential_id}},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "not found" in response.json()["message"]+ assert not ExternalDataSource.objects.exists()++ def test_setup_with_expired_credential_returns_400(self):+ credential = self._store_stripe_credential(expires_at=timezone.now() - timedelta(minutes=1))+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={"source_type": "Stripe", "payload": {"credential_id": str(credential.pk)}},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "not found or expired" in response.json()["message"]+ assert not ExternalDataSource.objects.exists()++ def test_setup_with_other_teams_credential_returns_400(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ credential = self._store_stripe_credential(team=other_team)+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={"source_type": "Stripe", "payload": {"credential_id": str(credential.pk)}},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "not found" in response.json()["message"]++ def test_setup_with_credential_for_other_source_type_returns_400(self):+ credential = self._store_stripe_credential()+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/setup/",+ data={"source_type": "Postgres", "payload": {"credential_id": str(credential.pk)}},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "is for 'Stripe'" in response.json()["message"]+++class TestExternalDataSourceStoreCredentials(APIBaseTest):+ def _store(self, source_type: str = "Stripe", payload: dict | None = None):+ return self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/store_credentials/",+ data={+ "source_type": source_type,+ "payload": payload+ if payload is not None+ else {"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"}},+ },+ )++ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_store_credentials_creates_pending_credential_without_source(self, _mock_validate):+ response = self._store()+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ data = response.json()+ assert data["source_type"] == "Stripe"++ credential = PendingSourceCredential.objects.for_team(self.team.pk).get(pk=data["credential_id"])+ assert credential.team_id == self.team.pk+ assert credential.source_type == "Stripe"+ assert credential.payload["auth_method"]["stripe_secret_key"] == "sk_test_123"+ assert credential.created_by == self.user+ assert credential.expires_at > timezone.now()+ # Storing credentials must not create a source.+ assert not ExternalDataSource.objects.exists()++ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_store_credentials_purges_expired_credentials(self, _mock_validate):+ expired = PendingSourceCredential.objects.for_team(self.team.pk).create(+ team=self.team,+ source_type="Stripe",+ payload={"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_old"}},+ expires_at=timezone.now() - timedelta(minutes=1),+ )+ response = self._store()+ assert response.status_code == status.HTTP_201_CREATED+ assert not PendingSourceCredential.objects.for_team(self.team.pk).filter(pk=expired.pk).exists()++ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(False, "Invalid Stripe API key"),+ )+ def test_store_credentials_rejects_invalid_credentials(self, _mock_validate):+ response = self._store()+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Invalid Stripe API key" in response.json()["message"]+ assert not PendingSourceCredential.objects.for_team(self.team.pk).exists()++ def test_store_credentials_rejects_invalid_config(self):+ response = self._store(source_type="Postgres", payload={"host": "localhost"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Invalid source config" in response.json()["message"]+ assert not PendingSourceCredential.objects.for_team(self.team.pk).exists()++ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_stored_credentials_list_returns_metadata_only(self, _mock_validate):+ response = self._store()+ assert response.status_code == status.HTTP_201_CREATED++ list_response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/stored_credentials/")+ assert list_response.status_code == status.HTTP_200_OK+ results = list_response.json()+ assert len(results) == 1+ assert results[0]["credential_id"] == response.json()["credential_id"]+ assert results[0]["source_type"] == "Stripe"+ assert "sk_test_123" not in json.dumps(list_response.json())++ def test_stored_credentials_list_filters_by_source_type_and_hides_expired_and_other_teams(self):+ def _create(team, source_type, **kwargs):+ return PendingSourceCredential.objects.for_team(team.pk).create(+ team=team, source_type=source_type, payload={"key": "secret"}, **kwargs+ )++ stripe_credential = _create(self.team, "Stripe")+ _create(self.team, "Postgres")+ _create(self.team, "Stripe", expires_at=timezone.now() - timedelta(minutes=1))+ other_team = Team.objects.create(organization=self.organization, name="other")+ _create(other_team, "Stripe")++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/stored_credentials/?source_type=Stripe"+ )+ assert response.status_code == status.HTTP_200_OK+ results = response.json()+ assert [result["credential_id"] for result in results] == [str(stripe_credential.pk)]++ def test_stored_credentials_list_orders_newest_first(self):+ older = PendingSourceCredential.objects.for_team(self.team.pk).create(+ team=self.team, source_type="Stripe", payload={"key": "secret"}+ )+ newer = PendingSourceCredential.objects.for_team(self.team.pk).create(+ team=self.team, source_type="Stripe", payload={"key": "secret"}+ )+ PendingSourceCredential.objects.for_team(self.team.pk).filter(pk=older.pk).update(+ created_at=timezone.now() - timedelta(hours=1)+ )++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/stored_credentials/")+ assert response.status_code == status.HTTP_200_OK+ assert [result["credential_id"] for result in response.json()] == [str(newer.pk), str(older.pk)]diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 556ac1910f5f..c1889c639e7e 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -1343,6 +1343,36 @@ export interface PatchedExternalDataSourceBulkUpdateSchemasApi {schemas?: ExternalDataSourceBulkUpdateSchemaApi[]}+/**+ * * `oauth` - oauth+ * * `credentials` - credentials+ */+export type AuthMethodEnumApi = (typeof AuthMethodEnumApi)[keyof typeof AuthMethodEnumApi]++export const AuthMethodEnumApi = {+ Oauth: 'oauth',+ Credentials: 'credentials',+} as const++export interface SourceConnectLinkApi {+ /** The source type the link is for. */+ source_type: string+ /** 'oauth' = the user authorizes in their browser; 'credentials' = the user enters credentials in the PostHog UI. Either way secrets never pass through the agent.+ *+ * * `oauth` - oauth+ * * `credentials` - credentials */+ auth_method: AuthMethodEnumApi+ /** Full URL to share with the user. They open it in a browser to authorize or enter credentials directly in PostHog — credentials never pass through the agent or the chat. */+ connect_url: string+ /**+ * The payload key to pass to data-warehouse-source-setup: for OAuth sources, the source's integration id key (e.g. 'hubspot_integration_id'); for credential sources, 'credential_id' referencing the credentials the user stored via the connect page.+ * @nullable+ */+ integration_field: string | null+ /** Next steps for the agent to relay to the user. */+ instructions: string+}+export interface ExternalDataSourceConnectionOptionApi {readonly id: string/** @nullable */@@ -1354,24 +1384,538 @@ export interface ExternalDataSourceConnectionOptionApi {readonly engine: EngineEnumApi | null}-export interface PaginatedExternalDataSourceConnectionOptionListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: ExternalDataSourceConnectionOptionApi[]+export interface PaginatedExternalDataSourceConnectionOptionListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ExternalDataSourceConnectionOptionApi[]+}++/**+ * Validate credentials and preview available tables from a remote database.+ *+ * The request body contains source_type plus flat source-specific credential fields+ * (e.g. host, port, database, user, password, schema for Postgres). The credential+ * fields vary per source_type and are validated dynamically by the source registry.+ */+export interface DatabaseSchemaRequestApi {+ /** The source type to validate against.+ *+ * * `Ashby` - Ashby+ * * `Supabase` - Supabase+ * * `CustomerIO` - CustomerIO+ * * `Github` - Github+ * * `Stripe` - Stripe+ * * `Hubspot` - Hubspot+ * * `Postgres` - Postgres+ * * `Zendesk` - Zendesk+ * * `Snowflake` - Snowflake+ * * `Salesforce` - Salesforce+ * * `MySQL` - MySQL+ * * `MongoDB` - MongoDB+ * * `MSSQL` - MSSQL+ * * `Vitally` - Vitally+ * * `BigQuery` - BigQuery+ * * `Chargebee` - Chargebee+ * * `Clerk` - Clerk+ * * `GoogleAds` - GoogleAds+ * * `GoogleSearchConsole` - GoogleSearchConsole+ * * `TemporalIO` - TemporalIO+ * * `DoIt` - DoIt+ * * `GoogleSheets` - GoogleSheets+ * * `MetaAds` - MetaAds+ * * `Klaviyo` - Klaviyo+ * * `Mailchimp` - Mailchimp+ * * `Braze` - Braze+ * * `Mailjet` - Mailjet+ * * `Redshift` - Redshift+ * * `Polar` - Polar+ * * `RevenueCat` - RevenueCat+ * * `LinkedinAds` - LinkedinAds+ * * `RedditAds` - RedditAds+ * * `TikTokAds` - TikTokAds+ * * `BingAds` - BingAds+ * * `Shopify` - Shopify+ * * `Attio` - Attio+ * * `SnapchatAds` - SnapchatAds+ * * `Linear` - Linear+ * * `Intercom` - Intercom+ * * `Amplitude` - Amplitude+ * * `Mixpanel` - Mixpanel+ * * `Jira` - Jira+ * * `ActiveCampaign` - ActiveCampaign+ * * `Marketo` - Marketo+ * * `Adjust` - Adjust+ * * `AppsFlyer` - AppsFlyer+ * * `Freshdesk` - Freshdesk+ * * `GoogleAnalytics` - GoogleAnalytics+ * * `Pipedrive` - Pipedrive+ * * `SendGrid` - SendGrid+ * * `Slack` - Slack+ * * `PagerDuty` - PagerDuty+ * * `Asana` - Asana+ * * `Notion` - Notion+ * * `Airtable` - Airtable+ * * `Greenhouse` - Greenhouse+ * * `BambooHR` - BambooHR+ * * `Lever` - Lever+ * * `GitLab` - GitLab+ * * `Datadog` - Datadog+ * * `Sentry` - Sentry+ * * `Pendo` - Pendo+ * * `FullStory` - FullStory+ * * `AmazonAds` - AmazonAds+ * * `PinterestAds` - PinterestAds+ * * `AppleSearchAds` - AppleSearchAds+ * * `QuickBooks` - QuickBooks+ * * `Xero` - Xero+ * * `NetSuite` - NetSuite+ * * `WooCommerce` - WooCommerce+ * * `BigCommerce` - BigCommerce+ * * `PayPal` - PayPal+ * * `Square` - Square+ * * `Zoom` - Zoom+ * * `Trello` - Trello+ * * `Monday` - Monday+ * * `ClickUp` - ClickUp+ * * `Confluence` - Confluence+ * * `Recurly` - Recurly+ * * `SalesLoft` - SalesLoft+ * * `Outreach` - Outreach+ * * `Gong` - Gong+ * * `Calendly` - Calendly+ * * `Typeform` - Typeform+ * * `Iterable` - Iterable+ * * `ZohoCRM` - ZohoCRM+ * * `Close` - Close+ * * `Oracle` - Oracle+ * * `DynamoDB` - DynamoDB+ * * `Elasticsearch` - Elasticsearch+ * * `Kafka` - Kafka+ * * `LaunchDarkly` - LaunchDarkly+ * * `Braintree` - Braintree+ * * `Recharge` - Recharge+ * * `HelpScout` - HelpScout+ * * `Gorgias` - Gorgias+ * * `Instagram` - Instagram+ * * `YouTubeAnalytics` - YouTubeAnalytics+ * * `FacebookPages` - FacebookPages+ * * `TwitterAds` - TwitterAds+ * * `Workday` - Workday+ * * `ServiceNow` - ServiceNow+ * * `Pardot` - Pardot+ * * `Copper` - Copper+ * * `Front` - Front+ * * `ChartMogul` - ChartMogul+ * * `Zuora` - Zuora+ * * `Paddle` - Paddle+ * * `CircleCI` - CircleCI+ * * `CockroachDB` - CockroachDB+ * * `Firebase` - Firebase+ * * `AzureBlob` - AzureBlob+ * * `GoogleDrive` - GoogleDrive+ * * `OneDrive` - OneDrive+ * * `SharePoint` - SharePoint+ * * `Box` - Box+ * * `SFTP` - SFTP+ * * `MicrosoftTeams` - MicrosoftTeams+ * * `Aircall` - Aircall+ * * `Webflow` - Webflow+ * * `Okta` - Okta+ * * `Auth0` - Auth0+ * * `Productboard` - Productboard+ * * `Smartsheet` - Smartsheet+ * * `Wrike` - Wrike+ * * `Plaid` - Plaid+ * * `SurveyMonkey` - SurveyMonkey+ * * `Eventbrite` - Eventbrite+ * * `RingCentral` - RingCentral+ * * `Twilio` - Twilio+ * * `Freshsales` - Freshsales+ * * `Shortcut` - Shortcut+ * * `ConvertKit` - ConvertKit+ * * `Drip` - Drip+ * * `CampaignMonitor` - CampaignMonitor+ * * `MailerLite` - MailerLite+ * * `Omnisend` - Omnisend+ * * `Brevo` - Brevo+ * * `Postmark` - Postmark+ * * `Granola` - Granola+ * * `BuildBetter` - BuildBetter+ * * `Convex` - Convex+ * * `ClickHouse` - ClickHouse+ * * `Plain` - Plain+ * * `Resend` - Resend+ * * `PgAnalyze` - PgAnalyze+ * * `WorkOS` - WorkOS+ * * `AmazonS3` - AmazonS3+ * * `GoogleCloudStorage` - GoogleCloudStorage+ * * `Databricks` - Databricks+ * * `Dynamics365` - Dynamics365+ * * `SalesforceMarketingCloud` - SalesforceMarketingCloud+ * * `Db2` - Db2+ * * `Heap` - Heap+ * * `AdobeAnalytics` - AdobeAnalytics+ * * `Matomo` - Matomo+ * * `Optimizely` - Optimizely+ * * `Adyen` - Adyen+ * * `GoCardless` - GoCardless+ * * `Mollie` - Mollie+ * * `CheckoutCom` - CheckoutCom+ * * `Branch` - Branch+ * * `Criteo` - Criteo+ * * `Outbrain` - Outbrain+ * * `Taboola` - Taboola+ * * `AdRoll` - AdRoll+ * * `DisplayVideo360` - DisplayVideo360+ * * `GoogleAdManager` - GoogleAdManager+ * * `CampaignManager360` - CampaignManager360+ * * `SearchAds360` - SearchAds360+ * * `AdobeCommerce` - AdobeCommerce+ * * `AmazonSellingPartner` - AmazonSellingPartner+ * * `Ebay` - Ebay+ * * `Commercetools` - Commercetools+ * * `LightspeedRetail` - LightspeedRetail+ * * `ShipStation` - ShipStation+ * * `ConstantContact` - ConstantContact+ * * `Mailgun` - Mailgun+ * * `Eloqua` - Eloqua+ * * `Sailthru` - Sailthru+ * * `Ortto` - Ortto+ * * `Attentive` - Attentive+ * * `Kustomer` - Kustomer+ * * `Dixa` - Dixa+ * * `Gladly` - Gladly+ * * `Qualtrics` - Qualtrics+ * * `Delighted` - Delighted+ * * `AzureDevOps` - AzureDevOps+ * * `Rollbar` - Rollbar+ * * `Opsgenie` - Opsgenie+ * * `IncidentIo` - IncidentIo+ * * `Pingdom` - Pingdom+ * * `Cloudflare` - Cloudflare+ * * `CosmosDB` - CosmosDB+ * * `PlanetScale` - PlanetScale+ * * `SapHana` - SapHana+ * * `Rippling` - Rippling+ * * `HiBob` - HiBob+ * * `Personio` - Personio+ * * `Deel` - Deel+ * * `AdpWorkforceNow` - AdpWorkforceNow+ * * `Paylocity` - Paylocity+ * * `Gusto` - Gusto+ * * `CultureAmp` - CultureAmp+ * * `Lattice` - Lattice+ * * `SageIntacct` - SageIntacct+ * * `FreshBooks` - FreshBooks+ * * `Expensify` - Expensify+ * * `Ramp` - Ramp+ * * `Brex` - Brex+ * * `Coupa` - Coupa+ * * `SapConcur` - SapConcur+ * * `Apollo` - Apollo+ * * `Crunchbase` - Crunchbase+ * * `ZoomInfo` - ZoomInfo+ * * `Clari` - Clari+ * * `Chorus` - Chorus+ * * `Coda` - Coda+ * * `Guru` - Guru+ * * `Dropbox` - Dropbox+ * * `Docusign` - Docusign+ * * `PandaDoc` - PandaDoc+ * * `SapErp` - SapErp+ * * `SapSuccessFactors` - SapSuccessFactors+ * * `OracleEbs` - OracleEbs+ * * `OracleFusion` - OracleFusion+ * * `Custom` - Custom */+ source_type: ExternalDataSourceTypeEnumApi+}++/**+ * Connection details as flat keys for the source_type (discover required fields with the wizard tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} referencing credentials the user stored via the connect-link page (discover ids with the stored_credentials endpoint) — they are merged in server-side and deleted once consumed. A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible sync defaults.+ */+export type SourceSetupApiPayload = { [key: string]: unknown }++export interface SourceSetupApi {+ /** The source type to set up (e.g. 'Stripe', 'Postgres', 'Hubspot').+ *+ * * `Ashby` - Ashby+ * * `Supabase` - Supabase+ * * `CustomerIO` - CustomerIO+ * * `Github` - Github+ * * `Stripe` - Stripe+ * * `Hubspot` - Hubspot+ * * `Postgres` - Postgres+ * * `Zendesk` - Zendesk+ * * `Snowflake` - Snowflake+ * * `Salesforce` - Salesforce+ * * `MySQL` - MySQL+ * * `MongoDB` - MongoDB+ * * `MSSQL` - MSSQL+ * * `Vitally` - Vitally+ * * `BigQuery` - BigQuery+ * * `Chargebee` - Chargebee+ * * `Clerk` - Clerk+ * * `GoogleAds` - GoogleAds+ * * `GoogleSearchConsole` - GoogleSearchConsole+ * * `TemporalIO` - TemporalIO+ * * `DoIt` - DoIt+ * * `GoogleSheets` - GoogleSheets+ * * `MetaAds` - MetaAds+ * * `Klaviyo` - Klaviyo+ * * `Mailchimp` - Mailchimp+ * * `Braze` - Braze+ * * `Mailjet` - Mailjet+ * * `Redshift` - Redshift+ * * `Polar` - Polar+ * * `RevenueCat` - RevenueCat+ * * `LinkedinAds` - LinkedinAds+ * * `RedditAds` - RedditAds+ * * `TikTokAds` - TikTokAds+ * * `BingAds` - BingAds+ * * `Shopify` - Shopify+ * * `Attio` - Attio+ * * `SnapchatAds` - SnapchatAds+ * * `Linear` - Linear+ * * `Intercom` - Intercom+ * * `Amplitude` - Amplitude+ * * `Mixpanel` - Mixpanel+ * * `Jira` - Jira+ * * `ActiveCampaign` - ActiveCampaign+ * * `Marketo` - Marketo+ * * `Adjust` - Adjust+ * * `AppsFlyer` - AppsFlyer+ * * `Freshdesk` - Freshdesk+ * * `GoogleAnalytics` - GoogleAnalytics+ * * `Pipedrive` - Pipedrive+ * * `SendGrid` - SendGrid+ * * `Slack` - Slack+ * * `PagerDuty` - PagerDuty+ * * `Asana` - Asana+ * * `Notion` - Notion+ * * `Airtable` - Airtable+ * * `Greenhouse` - Greenhouse+ * * `BambooHR` - BambooHR+ * * `Lever` - Lever+ * * `GitLab` - GitLab+ * * `Datadog` - Datadog+ * * `Sentry` - Sentry+ * * `Pendo` - Pendo+ * * `FullStory` - FullStory+ * * `AmazonAds` - AmazonAds+ * * `PinterestAds` - PinterestAds+ * * `AppleSearchAds` - AppleSearchAds+ * * `QuickBooks` - QuickBooks+ * * `Xero` - Xero+ * * `NetSuite` - NetSuite+ * * `WooCommerce` - WooCommerce+ * * `BigCommerce` - BigCommerce+ * * `PayPal` - PayPal+ * * `Square` - Square+ * * `Zoom` - Zoom+ * * `Trello` - Trello+ * * `Monday` - Monday+ * * `ClickUp` - ClickUp+ * * `Confluence` - Confluence+ * * `Recurly` - Recurly+ * * `SalesLoft` - SalesLoft+ * * `Outreach` - Outreach+ * * `Gong` - Gong+ * * `Calendly` - Calendly+ * * `Typeform` - Typeform+ * * `Iterable` - Iterable+ * * `ZohoCRM` - ZohoCRM+ * * `Close` - Close+ * * `Oracle` - Oracle+ * * `DynamoDB` - DynamoDB+ * * `Elasticsearch` - Elasticsearch+ * * `Kafka` - Kafka+ * * `LaunchDarkly` - LaunchDarkly+ * * `Braintree` - Braintree+ * * `Recharge` - Recharge+ * * `HelpScout` - HelpScout+ * * `Gorgias` - Gorgias+ * * `Instagram` - Instagram+ * * `YouTubeAnalytics` - YouTubeAnalytics+ * * `FacebookPages` - FacebookPages+ * * `TwitterAds` - TwitterAds+ * * `Workday` - Workday+ * * `ServiceNow` - ServiceNow+ * * `Pardot` - Pardot+ * * `Copper` - Copper+ * * `Front` - Front+ * * `ChartMogul` - ChartMogul+ * * `Zuora` - Zuora+ * * `Paddle` - Paddle+ * * `CircleCI` - CircleCI+ * * `CockroachDB` - CockroachDB+ * * `Firebase` - Firebase+ * * `AzureBlob` - AzureBlob+ * * `GoogleDrive` - GoogleDrive+ * * `OneDrive` - OneDrive+ * * `SharePoint` - SharePoint+ * * `Box` - Box+ * * `SFTP` - SFTP+ * * `MicrosoftTeams` - MicrosoftTeams+ * * `Aircall` - Aircall+ * * `Webflow` - Webflow+ * * `Okta` - Okta+ * * `Auth0` - Auth0+ * * `Productboard` - Productboard+ * * `Smartsheet` - Smartsheet+ * * `Wrike` - Wrike+ * * `Plaid` - Plaid+ * * `SurveyMonkey` - SurveyMonkey+ * * `Eventbrite` - Eventbrite+ * * `RingCentral` - RingCentral+ * * `Twilio` - Twilio+ * * `Freshsales` - Freshsales+ * * `Shortcut` - Shortcut+ * * `ConvertKit` - ConvertKit+ * * `Drip` - Drip+ * * `CampaignMonitor` - CampaignMonitor+ * * `MailerLite` - MailerLite+ * * `Omnisend` - Omnisend+ * * `Brevo` - Brevo+ * * `Postmark` - Postmark+ * * `Granola` - Granola+ * * `BuildBetter` - BuildBetter+ * * `Convex` - Convex+ * * `ClickHouse` - ClickHouse+ * * `Plain` - Plain+ * * `Resend` - Resend+ * * `PgAnalyze` - PgAnalyze+ * * `WorkOS` - WorkOS+ * * `AmazonS3` - AmazonS3+ * * `GoogleCloudStorage` - GoogleCloudStorage+ * * `Databricks` - Databricks+ * * `Dynamics365` - Dynamics365+ * * `SalesforceMarketingCloud` - SalesforceMarketingCloud+ * * `Db2` - Db2+ * * `Heap` - Heap+ * * `AdobeAnalytics` - AdobeAnalytics+ * * `Matomo` - Matomo+ * * `Optimizely` - Optimizely+ * * `Adyen` - Adyen+ * * `GoCardless` - GoCardless+ * * `Mollie` - Mollie+ * * `CheckoutCom` - CheckoutCom+ * * `Branch` - Branch+ * * `Criteo` - Criteo+ * * `Outbrain` - Outbrain+ * * `Taboola` - Taboola+ * * `AdRoll` - AdRoll+ * * `DisplayVideo360` - DisplayVideo360+ * * `GoogleAdManager` - GoogleAdManager+ * * `CampaignManager360` - CampaignManager360+ * * `SearchAds360` - SearchAds360+ * * `AdobeCommerce` - AdobeCommerce+ * * `AmazonSellingPartner` - AmazonSellingPartner+ * * `Ebay` - Ebay+ * * `Commercetools` - Commercetools+ * * `LightspeedRetail` - LightspeedRetail+ * * `ShipStation` - ShipStation+ * * `ConstantContact` - ConstantContact+ * * `Mailgun` - Mailgun+ * * `Eloqua` - Eloqua+ * * `Sailthru` - Sailthru+ * * `Ortto` - Ortto+ * * `Attentive` - Attentive+ * * `Kustomer` - Kustomer+ * * `Dixa` - Dixa+ * * `Gladly` - Gladly+ * * `Qualtrics` - Qualtrics+ * * `Delighted` - Delighted+ * * `AzureDevOps` - AzureDevOps+ * * `Rollbar` - Rollbar+ * * `Opsgenie` - Opsgenie+ * * `IncidentIo` - IncidentIo+ * * `Pingdom` - Pingdom+ * * `Cloudflare` - Cloudflare+ * * `CosmosDB` - CosmosDB+ * * `PlanetScale` - PlanetScale+ * * `SapHana` - SapHana+ * * `Rippling` - Rippling+ * * `HiBob` - HiBob+ * * `Personio` - Personio+ * * `Deel` - Deel+ * * `AdpWorkforceNow` - AdpWorkforceNow+ * * `Paylocity` - Paylocity+ * * `Gusto` - Gusto+ * * `CultureAmp` - CultureAmp+ * * `Lattice` - Lattice+ * * `SageIntacct` - SageIntacct+ * * `FreshBooks` - FreshBooks+ * * `Expensify` - Expensify+ * * `Ramp` - Ramp+ * * `Brex` - Brex+ * * `Coupa` - Coupa+ * * `SapConcur` - SapConcur+ * * `Apollo` - Apollo+ * * `Crunchbase` - Crunchbase+ * * `ZoomInfo` - ZoomInfo+ * * `Clari` - Clari+ * * `Chorus` - Chorus+ * * `Coda` - Coda+ * * `Guru` - Guru+ * * `Dropbox` - Dropbox+ * * `Docusign` - Docusign+ * * `PandaDoc` - PandaDoc+ * * `SapErp` - SapErp+ * * `SapSuccessFactors` - SapSuccessFactors+ * * `OracleEbs` - OracleEbs+ * * `OracleFusion` - OracleFusion+ * * `Custom` - Custom */+ source_type: ExternalDataSourceTypeEnumApi+ /** Connection details as flat keys for the source_type (discover required fields with the wizard tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} referencing credentials the user stored via the connect-link page (discover ids with the stored_credentials endpoint) — they are merged in server-side and deleted once consumed. A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible sync defaults. */+ payload?: SourceSetupApiPayload+ /**+ * Table name prefix in HogQL, e.g. 'stripe' produces stripe_charges. Defaults to the source type.+ * @maxLength 100+ * @nullable+ */+ prefix?: string | null+ /**+ * Human-readable description.+ * @maxLength 400+ * @nullable+ */+ description?: string | null+}++export interface SourceSetupWebhookApi {+ /** Whether the webhook was registered with the external service. When true, webhook-capable tables (including webhook-only ones) sync via real-time webhooks; when false, tables fall back to the polling sync defaults and webhook-only tables stay disabled. */+ success: boolean+ /**+ * The PostHog endpoint the external service delivers events to.+ * @nullable+ */+ webhook_url: string | null+ /**+ * Why webhook registration failed (e.g. the credentials lack webhook permissions).+ * @nullable+ */+ error: string | null+ /** Webhook input names the user still needs to provide (e.g. a signing secret the external API did not return on create). Submit them via the update_webhook_inputs endpoint. */+ pending_inputs: string[]+}++export interface SourceSetupResponseApi {+ /** ID of the created external data source. */+ id: string+ /** Outcome of automatic webhook registration. Only present for sources that support webhooks (e.g. Stripe) and have webhook-capable tables. */+ webhook?: SourceSetupWebhookApi}/**- * Validate credentials and preview available tables from a remote database.- *- * The request body contains source_type plus flat source-specific credential fields- * (e.g. host, port, database, user, password, schema for Postgres). The credential- * fields vary per source_type and are validated dynamically by the source registry.+ * Connection details as flat keys for the source_type — the same fields the create flow accepts (host, port, password, API key, …). Checked against a live connection before being stored.*/-export interface DatabaseSchemaRequestApi {- /** The source type to validate against.+export type SourceCredentialCreateApiPayload = { [key: string]: unknown }++export interface SourceCredentialCreateApi {+ /** The source type these credentials are for (e.g. 'Stripe', 'Postgres').** * `Ashby` - Ashby* * `Supabase` - Supabase@@ -1601,6 +2145,19 @@ export interface DatabaseSchemaRequestApi {* * `OracleFusion` - OracleFusion* * `Custom` - Custom */source_type: ExternalDataSourceTypeEnumApi+ /** Connection details as flat keys for the source_type — the same fields the create flow accepts (host, port, password, API key, …). Checked against a live connection before being stored. */+ payload: SourceCredentialCreateApiPayload+}++export interface SourceCredentialApi {+ /** Stored credential id. Pass to the setup endpoint as {'credential_id': <id>} to create the source. */+ credential_id: string+ /** The source type the stored credentials are for. */+ source_type: string+ /** When the credentials were stored. */+ created_at: string+ /** When the stored credentials expire. Unconsumed credentials are unusable past this time. */+ expires_at: string}/**@@ -2436,6 +2993,13 @@ export type ExternalDataSourcesCheckCdcPrerequisitesCreate200 = {errors?: string[]}+export type ExternalDataSourcesConnectLinkRetrieveParams = {+ /**+ * The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').+ */+ source_type: string+}+export type ExternalDataSourcesConnectionsListParams = {/*** Number of results to return per page.@@ -2451,6 +3015,17 @@ export type ExternalDataSourcesConnectionsListParams = {search?: string}+export type ExternalDataSourcesStoredCredentialsListParams = {+ /**+ * A search term.+ */+ search?: string+ /**+ * Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres').+ */+ source_type?: string+}+export type FixHogqlListParams = {/*** Number of results to return per page.diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex a80ea9e7ca53..00c823cbf298 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -25,8 +25,10 @@ import type {ExternalDataSourceSerializersApi,ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams,ExternalDataSourcesCheckCdcPrerequisitesCreate200,+ ExternalDataSourcesConnectLinkRetrieveParams,ExternalDataSourcesConnectionsListParams,ExternalDataSourcesListParams,+ ExternalDataSourcesStoredCredentialsListParams,FixHogqlListParams,InsightVariableApi,InsightVariablesListParams,@@ -56,6 +58,11 @@ import type {QueryTabStateApi,QueryTabStateListParams,ResetPasswordResponseApi,+ SourceConnectLinkApi,+ SourceCredentialApi,+ SourceCredentialCreateApi,+ SourceSetupApi,+ SourceSetupResponseApi,TableApi,ViewLinkApi,ViewLinkValidationApi,@@ -1073,6 +1080,45 @@ export const externalDataSourcesCheckCdcPrerequisitesCreate = async ()}+export const getExternalDataSourcesConnectLinkRetrieveUrl = (+ projectId: string,+ params: ExternalDataSourcesConnectLinkRetrieveParams+) => {+ 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/connect_link/?${stringifiedParams}`+ : `/api/projects/${projectId}/external_data_sources/connect_link/`+}++/**+ * Return a secure browser link for connecting a data warehouse source.+ *+ * For OAuth sources the link starts the OAuth authorize flow; for credential sources it opens a minimal+ * connect page where the user enters only their credentials — no table selection, no source creation.+ * Either way the user authenticates in their browser, credentials never pass through the agent, and the+ * agent finishes setup afterwards by passing the resulting reference (integration id or credential id)+ * to data-warehouse-source-setup.+ */+export const externalDataSourcesConnectLinkRetrieve = async (+ projectId: string,+ params: ExternalDataSourcesConnectLinkRetrieveParams,+ options?: RequestInit+): Promise<SourceConnectLinkApi> => {+ return apiMutator<SourceConnectLinkApi>(getExternalDataSourcesConnectLinkRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getExternalDataSourcesConnectionsListUrl = (projectId: string,params?: ExternalDataSourcesConnectionsListParams@@ -1129,6 +1175,34 @@ export const externalDataSourcesDatabaseSchemaCreate = async (})}+export const getExternalDataSourcesSetupCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/external_data_sources/setup/`+}++/**+ * One-shot data warehouse source setup.+ *+ * Validate credentials, discover available tables, enable them all with sensible sync defaults+ * (incremental where supported, else append, else full refresh), and create the source in a single+ * call — the caller never has to assemble a `schemas` array. For sources that support webhooks+ * (e.g. Stripe), a webhook is auto-registered after creation: on success webhook-capable tables+ * switch to real-time webhook sync (unlocking webhook-only tables); on failure the polling+ * defaults stay in place. For fine-grained table/sync control, use the lower-level+ * `database_schema` + `create` flow instead.+ */+export const externalDataSourcesSetupCreate = async (+ projectId: string,+ sourceSetupApi: SourceSetupApi,+ options?: RequestInit+): Promise<SourceSetupResponseApi> => {+ return apiMutator<SourceSetupResponseApi>(getExternalDataSourcesSetupCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(sourceSetupApi),+ })+}+export const getExternalDataSourcesSourcePrefixCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/external_data_sources/source_prefix/`}@@ -1149,6 +1223,70 @@ export const externalDataSourcesSourcePrefixCreate = async (})}+export const getExternalDataSourcesStoreCredentialsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/external_data_sources/store_credentials/`+}++/**+ * Validate and store credentials for a data warehouse source without creating the source.+ *+ * Backs the source connect page: the user enters credentials directly in PostHog, they are+ * checked against a live connection, then stashed encrypted in a temporary store. The returned+ * credential id can be passed to `setup` as {'credential_id': <id>} to create the source — so+ * secrets never travel through an agent conversation. The stash is single-use: it is deleted+ * as soon as `setup` consumes it, and expires after 24 hours if never consumed.+ */+export const externalDataSourcesStoreCredentialsCreate = async (+ projectId: string,+ sourceCredentialCreateApi: SourceCredentialCreateApi,+ options?: RequestInit+): Promise<SourceCredentialApi> => {+ return apiMutator<SourceCredentialApi>(getExternalDataSourcesStoreCredentialsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(sourceCredentialCreateApi),+ })+}++export const getExternalDataSourcesStoredCredentialsListUrl = (+ projectId: string,+ params?: ExternalDataSourcesStoredCredentialsListParams+) => {+ 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/stored_credentials/?${stringifiedParams}`+ : `/api/projects/${projectId}/external_data_sources/stored_credentials/`+}++/**+ * List credentials stored via the source connect page that haven't been consumed yet.+ *+ * Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored+ * credentials are temporary: they disappear once consumed by `setup` or when they expire.+ * Newest first, so after a user confirms they've finished the connect page, the first entry+ * for the source type is the one to pass to `setup`.+ */+export const externalDataSourcesStoredCredentialsList = async (+ projectId: string,+ params?: ExternalDataSourcesStoredCredentialsListParams,+ options?: RequestInit+): Promise<SourceCredentialApi[]> => {+ return apiMutator<SourceCredentialApi[]>(getExternalDataSourcesStoredCredentialsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getExternalDataSourcesWizardRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/external_data_sources/wizard/`}diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex cbb9109dbdaf..e7a19067ab6b 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -1457,6 +1457,276 @@ export const ExternalDataSourcesDatabaseSchemaCreateBody = /* @__PURE__ */ zod'Validate credentials and preview available tables from a remote database.\n\nThe request body contains source_type plus flat source-specific credential fields\n(e.g. host, port, database, user, password, schema for Postgres). The credential\nfields vary per source_type and are validated dynamically by the source registry.')+/**+ * One-shot data warehouse source setup.+ *+ * Validate credentials, discover available tables, enable them all with sensible sync defaults+ * (incremental where supported, else append, else full refresh), and create the source in a single+ * call — the caller never has to assemble a `schemas` array. For sources that support webhooks+ * (e.g. Stripe), a webhook is auto-registered after creation: on success webhook-capable tables+ * switch to real-time webhook sync (unlocking webhook-only tables); on failure the polling+ * defaults stay in place. For fine-grained table/sync control, use the lower-level+ * `database_schema` + `create` flow instead.+ */+export const externalDataSourcesSetupCreateBodyPrefixMax = 100++export const externalDataSourcesSetupCreateBodyDescriptionMax = 400++export const ExternalDataSourcesSetupCreateBody = /* @__PURE__ */ zod.object({+ source_type: zod+ .enum([+ 'Ashby',+ 'Supabase',+ 'CustomerIO',+ 'Github',+ 'Stripe',+ 'Hubspot',+ 'Postgres',+ 'Zendesk',+ 'Snowflake',+ 'Salesforce',+ 'MySQL',+ 'MongoDB',+ 'MSSQL',+ 'Vitally',+ 'BigQuery',+ 'Chargebee',+ 'Clerk',+ 'GoogleAds',+ 'GoogleSearchConsole',+ 'TemporalIO',+ 'DoIt',+ 'GoogleSheets',+ 'MetaAds',+ 'Klaviyo',+ 'Mailchimp',+ 'Braze',+ 'Mailjet',+ 'Redshift',+ 'Polar',+ 'RevenueCat',+ 'LinkedinAds',+ 'RedditAds',+ 'TikTokAds',+ 'BingAds',+ 'Shopify',+ 'Attio',+ 'SnapchatAds',+ 'Linear',+ 'Intercom',+ 'Amplitude',+ 'Mixpanel',+ 'Jira',+ 'ActiveCampaign',+ 'Marketo',+ 'Adjust',+ 'AppsFlyer',+ 'Freshdesk',+ 'GoogleAnalytics',+ 'Pipedrive',+ 'SendGrid',+ 'Slack',+ 'PagerDuty',+ 'Asana',+ 'Notion',+ 'Airtable',+ 'Greenhouse',+ 'BambooHR',+ 'Lever',+ 'GitLab',+ 'Datadog',+ 'Sentry',+ 'Pendo',+ 'FullStory',+ 'AmazonAds',+ 'PinterestAds',+ 'AppleSearchAds',+ 'QuickBooks',+ 'Xero',+ 'NetSuite',+ 'WooCommerce',+ 'BigCommerce',+ 'PayPal',+ 'Square',+ 'Zoom',+ 'Trello',+ 'Monday',+ 'ClickUp',+ 'Confluence',+ 'Recurly',+ 'SalesLoft',+ 'Outreach',+ 'Gong',+ 'Calendly',+ 'Typeform',+ 'Iterable',+ 'ZohoCRM',+ 'Close',+ 'Oracle',+ 'DynamoDB',+ 'Elasticsearch',+ 'Kafka',+ 'LaunchDarkly',+ 'Braintree',+ 'Recharge',+ 'HelpScout',+ 'Gorgias',+ 'Instagram',+ 'YouTubeAnalytics',+ 'FacebookPages',+ 'TwitterAds',+ 'Workday',+ 'ServiceNow',+ 'Pardot',+ 'Copper',+ 'Front',+ 'ChartMogul',+ 'Zuora',+ 'Paddle',+ 'CircleCI',+ 'CockroachDB',+ 'Firebase',+ 'AzureBlob',+ 'GoogleDrive',+ 'OneDrive',+ 'SharePoint',+ 'Box',+ 'SFTP',+ 'MicrosoftTeams',+ 'Aircall',+ 'Webflow',+ 'Okta',+ 'Auth0',+ 'Productboard',+ 'Smartsheet',+ 'Wrike',+ 'Plaid',+ 'SurveyMonkey',+ 'Eventbrite',+ 'RingCentral',+ 'Twilio',+ 'Freshsales',+ 'Shortcut',+ 'ConvertKit',+ 'Drip',+ 'CampaignMonitor',+ 'MailerLite',+ 'Omnisend',+ 'Brevo',+ 'Postmark',+ 'Granola',+ 'BuildBetter',+ 'Convex',+ 'ClickHouse',+ 'Plain',+ 'Resend',+ 'PgAnalyze',+ 'WorkOS',+ 'AmazonS3',+ 'GoogleCloudStorage',+ 'Databricks',+ 'Dynamics365',+ 'SalesforceMarketingCloud',+ 'Db2',+ 'Heap',+ 'AdobeAnalytics',+ 'Matomo',+ 'Optimizely',+ 'Adyen',+ 'GoCardless',+ 'Mollie',+ 'CheckoutCom',+ 'Branch',+ 'Criteo',+ 'Outbrain',+ 'Taboola',+ 'AdRoll',+ 'DisplayVideo360',+ 'GoogleAdManager',+ 'CampaignManager360',+ 'SearchAds360',+ 'AdobeCommerce',+ 'AmazonSellingPartner',+ 'Ebay',+ 'Commercetools',+ 'LightspeedRetail',+ 'ShipStation',+ 'ConstantContact',+ 'Mailgun',+ 'Eloqua',+ 'Sailthru',+ 'Ortto',+ 'Attentive',+ 'Kustomer',+ 'Dixa',+ 'Gladly',+ 'Qualtrics',+ 'Delighted',+ 'AzureDevOps',+ 'Rollbar',+ 'Opsgenie',+ 'IncidentIo',+ 'Pingdom',+ 'Cloudflare',+ 'CosmosDB',+ 'PlanetScale',+ 'SapHana',+ 'Rippling',+ 'HiBob',+ 'Personio',+ 'Deel',+ 'AdpWorkforceNow',+ 'Paylocity',+ 'Gusto',+ 'CultureAmp',+ 'Lattice',+ 'SageIntacct',+ 'FreshBooks',+ 'Expensify',+ 'Ramp',+ 'Brex',+ 'Coupa',+ 'SapConcur',+ 'Apollo',+ 'Crunchbase',+ 'ZoomInfo',+ 'Clari',+ 'Chorus',+ 'Coda',+ 'Guru',+ 'Dropbox',+ 'Docusign',+ 'PandaDoc',+ 'SapErp',+ 'SapSuccessFactors',+ 'OracleEbs',+ 'OracleFusion',+ 'Custom',+ ])+ .describe(+ '\* `Ashby` - Ashby\n\* `Supabase` - Supabase\n\* `CustomerIO` - CustomerIO\n\* `Github` - Github\n\* `Stripe` - Stripe\n\* `Hubspot` - Hubspot\n\* `Postgres` - Postgres\n\* `Zendesk` - Zendesk\n\* `Snowflake` - Snowflake\n\* `Salesforce` - Salesforce\n\* `MySQL` - MySQL\n\* `MongoDB` - MongoDB\n\* `MSSQL` - MSSQL\n\* `Vitally` - Vitally\n\* `BigQuery` - BigQuery\n\* `Chargebee` - Chargebee\n\* `Clerk` - Clerk\n\* `GoogleAds` - GoogleAds\n\* `GoogleSearchConsole` - GoogleSearchConsole\n\* `TemporalIO` - TemporalIO\n\* `DoIt` - DoIt\n\* `GoogleSheets` - GoogleSheets\n\* `MetaAds` - MetaAds\n\* `Klaviyo` - Klaviyo\n\* `Mailchimp` - Mailchimp\n\* `Braze` - Braze\n\* `Mailjet` - Mailjet\n\* `Redshift` - Redshift\n\* `Polar` - Polar\n\* `RevenueCat` - RevenueCat\n\* `LinkedinAds` - LinkedinAds\n\* `RedditAds` - RedditAds\n\* `TikTokAds` - TikTokAds\n\* `BingAds` - BingAds\n\* `Shopify` - Shopify\n\* `Attio` - Attio\n\* `SnapchatAds` - SnapchatAds\n\* `Linear` - Linear\n\* `Intercom` - Intercom\n\* `Amplitude` - Amplitude\n\* `Mixpanel` - Mixpanel\n\* `Jira` - Jira\n\* `ActiveCampaign` - ActiveCampaign\n\* `Marketo` - Marketo\n\* `Adjust` - Adjust\n\* `AppsFlyer` - AppsFlyer\n\* `Freshdesk` - Freshdesk\n\* `GoogleAnalytics` - GoogleAnalytics\n\* `Pipedrive` - Pipedrive\n\* `SendGrid` - SendGrid\n\* `Slack` - Slack\n\* `PagerDuty` - PagerDuty\n\* `Asana` - Asana\n\* `Notion` - Notion\n\* `Airtable` - Airtable\n\* `Greenhouse` - Greenhouse\n\* `BambooHR` - BambooHR\n\* `Lever` - Lever\n\* `GitLab` - GitLab\n\* `Datadog` - Datadog\n\* `Sentry` - Sentry\n\* `Pendo` - Pendo\n\* `FullStory` - FullStory\n\* `AmazonAds` - AmazonAds\n\* `PinterestAds` - PinterestAds\n\* `AppleSearchAds` - AppleSearchAds\n\* `QuickBooks` - QuickBooks\n\* `Xero` - Xero\n\* `NetSuite` - NetSuite\n\* `WooCommerce` - WooCommerce\n\* `BigCommerce` - BigCommerce\n\* `PayPal` - PayPal\n\* `Square` - Square\n\* `Zoom` - Zoom\n\* `Trello` - Trello\n\* `Monday` - Monday\n\* `ClickUp` - ClickUp\n\* `Confluence` - Confluence\n\* `Recurly` - Recurly\n\* `SalesLoft` - SalesLoft\n\* `Outreach` - Outreach\n\* `Gong` - Gong\n\* `Calendly` - Calendly\n\* `Typeform` - Typeform\n\* `Iterable` - Iterable\n\* `ZohoCRM` - ZohoCRM\n\* `Close` - Close\n\* `Oracle` - Oracle\n\* `DynamoDB` - DynamoDB\n\* `Elasticsearch` - Elasticsearch\n\* `Kafka` - Kafka\n\* `LaunchDarkly` - LaunchDarkly\n\* `Braintree` - Braintree\n\* `Recharge` - Recharge\n\* `HelpScout` - HelpScout\n\* `Gorgias` - Gorgias\n\* `Instagram` - Instagram\n\* `YouTubeAnalytics` - YouTubeAnalytics\n\* `FacebookPages` - FacebookPages\n\* `TwitterAds` - TwitterAds\n\* `Workday` - Workday\n\* `ServiceNow` - ServiceNow\n\* `Pardot` - Pardot\n\* `Copper` - Copper\n\* `Front` - Front\n\* `ChartMogul` - ChartMogul\n\* `Zuora` - Zuora\n\* `Paddle` - Paddle\n\* `CircleCI` - CircleCI\n\* `CockroachDB` - CockroachDB\n\* `Firebase` - Firebase\n\* `AzureBlob` - AzureBlob\n\* `GoogleDrive` - GoogleDrive\n\* `OneDrive` - OneDrive\n\* `SharePoint` - SharePoint\n\* `Box` - Box\n\* `SFTP` - SFTP\n\* `MicrosoftTeams` - MicrosoftTeams\n\* `Aircall` - Aircall\n\* `Webflow` - Webflow\n\* `Okta` - Okta\n\* `Auth0` - Auth0\n\* `Productboard` - Productboard\n\* `Smartsheet` - Smartsheet\n\* `Wrike` - Wrike\n\* `Plaid` - Plaid\n\* `SurveyMonkey` - SurveyMonkey\n\* `Eventbrite` - Eventbrite\n\* `RingCentral` - RingCentral\n\* `Twilio` - Twilio\n\* `Freshsales` - Freshsales\n\* `Shortcut` - Shortcut\n\* `ConvertKit` - ConvertKit\n\* `Drip` - Drip\n\* `CampaignMonitor` - CampaignMonitor\n\* `MailerLite` - MailerLite\n\* `Omnisend` - Omnisend\n\* `Brevo` - Brevo\n\* `Postmark` - Postmark\n\* `Granola` - Granola\n\* `BuildBetter` - BuildBetter\n\* `Convex` - Convex\n\* `ClickHouse` - ClickHouse\n\* `Plain` - Plain\n\* `Resend` - Resend\n\* `PgAnalyze` - PgAnalyze\n\* `WorkOS` - WorkOS\n\* `AmazonS3` - AmazonS3\n\* `GoogleCloudStorage` - GoogleCloudStorage\n\* `Databricks` - Databricks\n\* `Dynamics365` - Dynamics365\n\* `SalesforceMarketingCloud` - SalesforceMarketingCloud\n\* `Db2` - Db2\n\* `Heap` - Heap\n\* `AdobeAnalytics` - AdobeAnalytics\n\* `Matomo` - Matomo\n\* `Optimizely` - Optimizely\n\* `Adyen` - Adyen\n\* `GoCardless` - GoCardless\n\* `Mollie` - Mollie\n\* `CheckoutCom` - CheckoutCom\n\* `Branch` - Branch\n\* `Criteo` - Criteo\n\* `Outbrain` - Outbrain\n\* `Taboola` - Taboola\n\* `AdRoll` - AdRoll\n\* `DisplayVideo360` - DisplayVideo360\n\* `GoogleAdManager` - GoogleAdManager\n\* `CampaignManager360` - CampaignManager360\n\* `SearchAds360` - SearchAds360\n\* `AdobeCommerce` - AdobeCommerce\n\* `AmazonSellingPartner` - AmazonSellingPartner\n\* `Ebay` - Ebay\n\* `Commercetools` - Commercetools\n\* `LightspeedRetail` - LightspeedRetail\n\* `ShipStation` - ShipStation\n\* `ConstantContact` - ConstantContact\n\* `Mailgun` - Mailgun\n\* `Eloqua` - Eloqua\n\* `Sailthru` - Sailthru\n\* `Ortto` - Ortto\n\* `Attentive` - Attentive\n\* `Kustomer` - Kustomer\n\* `Dixa` - Dixa\n\* `Gladly` - Gladly\n\* `Qualtrics` - Qualtrics\n\* `Delighted` - Delighted\n\* `AzureDevOps` - AzureDevOps\n\* `Rollbar` - Rollbar\n\* `Opsgenie` - Opsgenie\n\* `IncidentIo` - IncidentIo\n\* `Pingdom` - Pingdom\n\* `Cloudflare` - Cloudflare\n\* `CosmosDB` - CosmosDB\n\* `PlanetScale` - PlanetScale\n\* `SapHana` - SapHana\n\* `Rippling` - Rippling\n\* `HiBob` - HiBob\n\* `Personio` - Personio\n\* `Deel` - Deel\n\* `AdpWorkforceNow` - AdpWorkforceNow\n\* `Paylocity` - Paylocity\n\* `Gusto` - Gusto\n\* `CultureAmp` - CultureAmp\n\* `Lattice` - Lattice\n\* `SageIntacct` - SageIntacct\n\* `FreshBooks` - FreshBooks\n\* `Expensify` - Expensify\n\* `Ramp` - Ramp\n\* `Brex` - Brex\n\* `Coupa` - Coupa\n\* `SapConcur` - SapConcur\n\* `Apollo` - Apollo\n\* `Crunchbase` - Crunchbase\n\* `ZoomInfo` - ZoomInfo\n\* `Clari` - Clari\n\* `Chorus` - Chorus\n\* `Coda` - Coda\n\* `Guru` - Guru\n\* `Dropbox` - Dropbox\n\* `Docusign` - Docusign\n\* `PandaDoc` - PandaDoc\n\* `SapErp` - SapErp\n\* `SapSuccessFactors` - SapSuccessFactors\n\* `OracleEbs` - OracleEbs\n\* `OracleFusion` - OracleFusion\n\* `Custom` - Custom'+ )+ .describe(+ "The source type to set up (e.g. 'Stripe', 'Postgres', 'Hubspot').\n\n\* `Ashby` - Ashby\n\* `Supabase` - Supabase\n\* `CustomerIO` - CustomerIO\n\* `Github` - Github\n\* `Stripe` - Stripe\n\* `Hubspot` - Hubspot\n\* `Postgres` - Postgres\n\* `Zendesk` - Zendesk\n\* `Snowflake` - Snowflake\n\* `Salesforce` - Salesforce\n\* `MySQL` - MySQL\n\* `MongoDB` - MongoDB\n\* `MSSQL` - MSSQL\n\* `Vitally` - Vitally\n\* `BigQuery` - BigQuery\n\* `Chargebee` - Chargebee\n\* `Clerk` - Clerk\n\* `GoogleAds` - GoogleAds\n\* `GoogleSearchConsole` - GoogleSearchConsole\n\* `TemporalIO` - TemporalIO\n\* `DoIt` - DoIt\n\* `GoogleSheets` - GoogleSheets\n\* `MetaAds` - MetaAds\n\* `Klaviyo` - Klaviyo\n\* `Mailchimp` - Mailchimp\n\* `Braze` - Braze\n\* `Mailjet` - Mailjet\n\* `Redshift` - Redshift\n\* `Polar` - Polar\n\* `RevenueCat` - RevenueCat\n\* `LinkedinAds` - LinkedinAds\n\* `RedditAds` - RedditAds\n\* `TikTokAds` - TikTokAds\n\* `BingAds` - BingAds\n\* `Shopify` - Shopify\n\* `Attio` - Attio\n\* `SnapchatAds` - SnapchatAds\n\* `Linear` - Linear\n\* `Intercom` - Intercom\n\* `Amplitude` - Amplitude\n\* `Mixpanel` - Mixpanel\n\* `Jira` - Jira\n\* `ActiveCampaign` - ActiveCampaign\n\* `Marketo` - Marketo\n\* `Adjust` - Adjust\n\* `AppsFlyer` - AppsFlyer\n\* `Freshdesk` - Freshdesk\n\* `GoogleAnalytics` - GoogleAnalytics\n\* `Pipedrive` - Pipedrive\n\* `SendGrid` - SendGrid\n\* `Slack` - Slack\n\* `PagerDuty` - PagerDuty\n\* `Asana` - Asana\n\* `Notion` - Notion\n\* `Airtable` - Airtable\n\* `Greenhouse` - Greenhouse\n\* `BambooHR` - BambooHR\n\* `Lever` - Lever\n\* `GitLab` - GitLab\n\* `Datadog` - Datadog\n\* `Sentry` - Sentry\n\* `Pendo` - Pendo\n\* `FullStory` - FullStory\n\* `AmazonAds` - AmazonAds\n\* `PinterestAds` - PinterestAds\n\* `AppleSearchAds` - AppleSearchAds\n\* `QuickBooks` - QuickBooks\n\* `Xero` - Xero\n\* `NetSuite` - NetSuite\n\* `WooCommerce` - WooCommerce\n\* `BigCommerce` - BigCommerce\n\* `PayPal` - PayPal\n\* `Square` - Square\n\* `Zoom` - Zoom\n\* `Trello` - Trello\n\* `Monday` - Monday\n\* `ClickUp` - ClickUp\n\* `Confluence` - Confluence\n\* `Recurly` - Recurly\n\* `SalesLoft` - SalesLoft\n\* `Outreach` - Outreach\n\* `Gong` - Gong\n\* `Calendly` - Calendly\n\* `Typeform` - Typeform\n\* `Iterable` - Iterable\n\* `ZohoCRM` - ZohoCRM\n\* `Close` - Close\n\* `Oracle` - Oracle\n\* `DynamoDB` - DynamoDB\n\* `Elasticsearch` - Elasticsearch\n\* `Kafka` - Kafka\n\* `LaunchDarkly` - LaunchDarkly\n\* `Braintree` - Braintree\n\* `Recharge` - Recharge\n\* `HelpScout` - HelpScout\n\* `Gorgias` - Gorgias\n\* `Instagram` - Instagram\n\* `YouTubeAnalytics` - YouTubeAnalytics\n\* `FacebookPages` - FacebookPages\n\* `TwitterAds` - TwitterAds\n\* `Workday` - Workday\n\* `ServiceNow` - ServiceNow\n\* `Pardot` - Pardot\n\* `Copper` - Copper\n\* `Front` - Front\n\* `ChartMogul` - ChartMogul\n\* `Zuora` - Zuora\n\* `Paddle` - Paddle\n\* `CircleCI` - CircleCI\n\* `CockroachDB` - CockroachDB\n\* `Firebase` - Firebase\n\* `AzureBlob` - AzureBlob\n\* `GoogleDrive` - GoogleDrive\n\* `OneDrive` - OneDrive\n\* `SharePoint` - SharePoint\n\* `Box` - Box\n\* `SFTP` - SFTP\n\* `MicrosoftTeams` - MicrosoftTeams\n\* `Aircall` - Aircall\n\* `Webflow` - Webflow\n\* `Okta` - Okta\n\* `Auth0` - Auth0\n\* `Productboard` - Productboard\n\* `Smartsheet` - Smartsheet\n\* `Wrike` - Wrike\n\* `Plaid` - Plaid\n\* `SurveyMonkey` - SurveyMonkey\n\* `Eventbrite` - Eventbrite\n\* `RingCentral` - RingCentral\n\* `Twilio` - Twilio\n\* `Freshsales` - Freshsales\n\* `Shortcut` - Shortcut\n\* `ConvertKit` - ConvertKit\n\* `Drip` - Drip\n\* `CampaignMonitor` - CampaignMonitor\n\* `MailerLite` - MailerLite\n\* `Omnisend` - Omnisend\n\* `Brevo` - Brevo\n\* `Postmark` - Postmark\n\* `Granola` - Granola\n\* `BuildBetter` - BuildBetter\n\* `Convex` - Convex\n\* `ClickHouse` - ClickHouse\n\* `Plain` - Plain\n\* `Resend` - Resend\n\* `PgAnalyze` - PgAnalyze\n\* `WorkOS` - WorkOS\n\* `AmazonS3` - AmazonS3\n\* `GoogleCloudStorage` - GoogleCloudStorage\n\* `Databricks` - Databricks\n\* `Dynamics365` - Dynamics365\n\* `SalesforceMarketingCloud` - SalesforceMarketingCloud\n\* `Db2` - Db2\n\* `Heap` - Heap\n\* `AdobeAnalytics` - AdobeAnalytics\n\* `Matomo` - Matomo\n\* `Optimizely` - Optimizely\n\* `Adyen` - Adyen\n\* `GoCardless` - GoCardless\n\* `Mollie` - Mollie\n\* `CheckoutCom` - CheckoutCom\n\* `Branch` - Branch\n\* `Criteo` - Criteo\n\* `Outbrain` - Outbrain\n\* `Taboola` - Taboola\n\* `AdRoll` - AdRoll\n\* `DisplayVideo360` - DisplayVideo360\n\* `GoogleAdManager` - GoogleAdManager\n\* `CampaignManager360` - CampaignManager360\n\* `SearchAds360` - SearchAds360\n\* `AdobeCommerce` - AdobeCommerce\n\* `AmazonSellingPartner` - AmazonSellingPartner\n\* `Ebay` - Ebay\n\* `Commercetools` - Commercetools\n\* `LightspeedRetail` - LightspeedRetail\n\* `ShipStation` - ShipStation\n\* `ConstantContact` - ConstantContact\n\* `Mailgun` - Mailgun\n\* `Eloqua` - Eloqua\n\* `Sailthru` - Sailthru\n\* `Ortto` - Ortto\n\* `Attentive` - Attentive\n\* `Kustomer` - Kustomer\n\* `Dixa` - Dixa\n\* `Gladly` - Gladly\n\* `Qualtrics` - Qualtrics\n\* `Delighted` - Delighted\n\* `AzureDevOps` - AzureDevOps\n\* `Rollbar` - Rollbar\n\* `Opsgenie` - Opsgenie\n\* `IncidentIo` - IncidentIo\n\* `Pingdom` - Pingdom\n\* `Cloudflare` - Cloudflare\n\* `CosmosDB` - CosmosDB\n\* `PlanetScale` - PlanetScale\n\* `SapHana` - SapHana\n\* `Rippling` - Rippling\n\* `HiBob` - HiBob\n\* `Personio` - Personio\n\* `Deel` - Deel\n\* `AdpWorkforceNow` - AdpWorkforceNow\n\* `Paylocity` - Paylocity\n\* `Gusto` - Gusto\n\* `CultureAmp` - CultureAmp\n\* `Lattice` - Lattice\n\* `SageIntacct` - SageIntacct\n\* `FreshBooks` - FreshBooks\n\* `Expensify` - Expensify\n\* `Ramp` - Ramp\n\* `Brex` - Brex\n\* `Coupa` - Coupa\n\* `SapConcur` - SapConcur\n\* `Apollo` - Apollo\n\* `Crunchbase` - Crunchbase\n\* `ZoomInfo` - ZoomInfo\n\* `Clari` - Clari\n\* `Chorus` - Chorus\n\* `Coda` - Coda\n\* `Guru` - Guru\n\* `Dropbox` - Dropbox\n\* `Docusign` - Docusign\n\* `PandaDoc` - PandaDoc\n\* `SapErp` - SapErp\n\* `SapSuccessFactors` - SapSuccessFactors\n\* `OracleEbs` - OracleEbs\n\* `OracleFusion` - OracleFusion\n\* `Custom` - Custom"+ ),+ payload: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ "Connection details as flat keys for the source_type (discover required fields with the wizard tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} referencing credentials the user stored via the connect-link page (discover ids with the stored_credentials endpoint) — they are merged in server-side and deleted once consumed. A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible sync defaults."+ ),+ prefix: zod+ .string()+ .max(externalDataSourcesSetupCreateBodyPrefixMax)+ .nullish()+ .describe("Table name prefix in HogQL, e.g. 'stripe' produces stripe_charges. Defaults to the source type."),+ description: zod+ .string()+ .max(externalDataSourcesSetupCreateBodyDescriptionMax)+ .nullish()+ .describe('Human-readable description.'),+})+/*** Create, Read, Update and Delete External data Sources.*/@@ -1483,6 +1753,259 @@ export const ExternalDataSourcesSourcePrefixCreateBody = /* @__PURE__ */ zod}).describe('Mixin for serializers to add user access control fields')+/**+ * Validate and store credentials for a data warehouse source without creating the source.+ *+ * Backs the source connect page: the user enters credentials directly in PostHog, they are+ * checked against a live connection, then stashed encrypted in a temporary store. The returned+ * credential id can be passed to `setup` as {'credential_id': <id>} to create the source — so+ * secrets never travel through an agent conversation. The stash is single-use: it is deleted+ * as soon as `setup` consumes it, and expires after 24 hours if never consumed.+ */+export const ExternalDataSourcesStoreCredentialsCreateBody = /* @__PURE__ */ zod.object({+ source_type: zod+ .enum([+ 'Ashby',+ 'Supabase',+ 'CustomerIO',+ 'Github',+ 'Stripe',+ 'Hubspot',+ 'Postgres',+ 'Zendesk',+ 'Snowflake',+ 'Salesforce',+ 'MySQL',+ 'MongoDB',+ 'MSSQL',+ 'Vitally',+ 'BigQuery',+ 'Chargebee',+ 'Clerk',+ 'GoogleAds',+ 'GoogleSearchConsole',+ 'TemporalIO',+ 'DoIt',+ 'GoogleSheets',+ 'MetaAds',+ 'Klaviyo',+ 'Mailchimp',+ 'Braze',+ 'Mailjet',+ 'Redshift',+ 'Polar',+ 'RevenueCat',+ 'LinkedinAds',+ 'RedditAds',+ 'TikTokAds',+ 'BingAds',+ 'Shopify',+ 'Attio',+ 'SnapchatAds',+ 'Linear',+ 'Intercom',+ 'Amplitude',+ 'Mixpanel',+ 'Jira',+ 'ActiveCampaign',+ 'Marketo',+ 'Adjust',+ 'AppsFlyer',+ 'Freshdesk',+ 'GoogleAnalytics',+ 'Pipedrive',+ 'SendGrid',+ 'Slack',+ 'PagerDuty',+ 'Asana',+ 'Notion',+ 'Airtable',+ 'Greenhouse',+ 'BambooHR',+ 'Lever',+ 'GitLab',+ 'Datadog',+ 'Sentry',+ 'Pendo',+ 'FullStory',+ 'AmazonAds',+ 'PinterestAds',+ 'AppleSearchAds',+ 'QuickBooks',+ 'Xero',+ 'NetSuite',+ 'WooCommerce',+ 'BigCommerce',+ 'PayPal',+ 'Square',+ 'Zoom',+ 'Trello',+ 'Monday',+ 'ClickUp',+ 'Confluence',+ 'Recurly',+ 'SalesLoft',+ 'Outreach',+ 'Gong',+ 'Calendly',+ 'Typeform',+ 'Iterable',+ 'ZohoCRM',+ 'Close',+ 'Oracle',+ 'DynamoDB',+ 'Elasticsearch',+ 'Kafka',+ 'LaunchDarkly',+ 'Braintree',+ 'Recharge',+ 'HelpScout',+ 'Gorgias',+ 'Instagram',+ 'YouTubeAnalytics',+ 'FacebookPages',+ 'TwitterAds',+ 'Workday',+ 'ServiceNow',+ 'Pardot',+ 'Copper',+ 'Front',+ 'ChartMogul',+ 'Zuora',+ 'Paddle',+ 'CircleCI',+ 'CockroachDB',+ 'Firebase',+ 'AzureBlob',+ 'GoogleDrive',+ 'OneDrive',+ 'SharePoint',+ 'Box',+ 'SFTP',+ 'MicrosoftTeams',+ 'Aircall',+ 'Webflow',+ 'Okta',+ 'Auth0',+ 'Productboard',+ 'Smartsheet',+ 'Wrike',+ 'Plaid',+ 'SurveyMonkey',+ 'Eventbrite',+ 'RingCentral',+ 'Twilio',+ 'Freshsales',+ 'Shortcut',+ 'ConvertKit',+ 'Drip',+ 'CampaignMonitor',+ 'MailerLite',+ 'Omnisend',+ 'Brevo',+ 'Postmark',+ 'Granola',+ 'BuildBetter',+ 'Convex',+ 'ClickHouse',+ 'Plain',+ 'Resend',+ 'PgAnalyze',+ 'WorkOS',+ 'AmazonS3',+ 'GoogleCloudStorage',+ 'Databricks',+ 'Dynamics365',+ 'SalesforceMarketingCloud',+ 'Db2',+ 'Heap',+ 'AdobeAnalytics',+ 'Matomo',+ 'Optimizely',+ 'Adyen',+ 'GoCardless',+ 'Mollie',+ 'CheckoutCom',+ 'Branch',+ 'Criteo',+ 'Outbrain',+ 'Taboola',+ 'AdRoll',+ 'DisplayVideo360',+ 'GoogleAdManager',+ 'CampaignManager360',+ 'SearchAds360',+ 'AdobeCommerce',+ 'AmazonSellingPartner',+ 'Ebay',+ 'Commercetools',+ 'LightspeedRetail',+ 'ShipStation',+ 'ConstantContact',+ 'Mailgun',+ 'Eloqua',+ 'Sailthru',+ 'Ortto',+ 'Attentive',+ 'Kustomer',+ 'Dixa',+ 'Gladly',+ 'Qualtrics',+ 'Delighted',+ 'AzureDevOps',+ 'Rollbar',+ 'Opsgenie',+ 'IncidentIo',+ 'Pingdom',+ 'Cloudflare',+ 'CosmosDB',+ 'PlanetScale',+ 'SapHana',+ 'Rippling',+ 'HiBob',+ 'Personio',+ 'Deel',+ 'AdpWorkforceNow',+ 'Paylocity',+ 'Gusto',+ 'CultureAmp',+ 'Lattice',+ 'SageIntacct',+ 'FreshBooks',+ 'Expensify',+ 'Ramp',+ 'Brex',+ 'Coupa',+ 'SapConcur',+ 'Apollo',+ 'Crunchbase',+ 'ZoomInfo',+ 'Clari',+ 'Chorus',+ 'Coda',+ 'Guru',+ 'Dropbox',+ 'Docusign',+ 'PandaDoc',+ 'SapErp',+ 'SapSuccessFactors',+ 'OracleEbs',+ 'OracleFusion',+ 'Custom',+ ])+ .describe(+ '\* `Ashby` - Ashby\n\* `Supabase` - Supabase\n\* `CustomerIO` - CustomerIO\n\* `Github` - Github\n\* `Stripe` - Stripe\n\* `Hubspot` - Hubspot\n\* `Postgres` - Postgres\n\* `Zendesk` - Zendesk\n\* `Snowflake` - Snowflake\n\* `Salesforce` - Salesforce\n\* `MySQL` - MySQL\n\* `MongoDB` - MongoDB\n\* `MSSQL` - MSSQL\n\* `Vitally` - Vitally\n\* `BigQuery` - BigQuery\n\* `Chargebee` - Chargebee\n\* `Clerk` - Clerk\n\* `GoogleAds` - GoogleAds\n\* `GoogleSearchConsole` - GoogleSearchConsole\n\* `TemporalIO` - TemporalIO\n\* `DoIt` - DoIt\n\* `GoogleSheets` - GoogleSheets\n\* `MetaAds` - MetaAds\n\* `Klaviyo` - Klaviyo\n\* `Mailchimp` - Mailchimp\n\* `Braze` - Braze\n\* `Mailjet` - Mailjet\n\* `Redshift` - Redshift\n\* `Polar` - Polar\n\* `RevenueCat` - RevenueCat\n\* `LinkedinAds` - LinkedinAds\n\* `RedditAds` - RedditAds\n\* `TikTokAds` - TikTokAds\n\* `BingAds` - BingAds\n\* `Shopify` - Shopify\n\* `Attio` - Attio\n\* `SnapchatAds` - SnapchatAds\n\* `Linear` - Linear\n\* `Intercom` - Intercom\n\* `Amplitude` - Amplitude\n\* `Mixpanel` - Mixpanel\n\* `Jira` - Jira\n\* `ActiveCampaign` - ActiveCampaign\n\* `Marketo` - Marketo\n\* `Adjust` - Adjust\n\* `AppsFlyer` - AppsFlyer\n\* `Freshdesk` - Freshdesk\n\* `GoogleAnalytics` - GoogleAnalytics\n\* `Pipedrive` - Pipedrive\n\* `SendGrid` - SendGrid\n\* `Slack` - Slack\n\* `PagerDuty` - PagerDuty\n\* `Asana` - Asana\n\* `Notion` - Notion\n\* `Airtable` - Airtable\n\* `Greenhouse` - Greenhouse\n\* `BambooHR` - BambooHR\n\* `Lever` - Lever\n\* `GitLab` - GitLab\n\* `Datadog` - Datadog\n\* `Sentry` - Sentry\n\* `Pendo` - Pendo\n\* `FullStory` - FullStory\n\* `AmazonAds` - AmazonAds\n\* `PinterestAds` - PinterestAds\n\* `AppleSearchAds` - AppleSearchAds\n\* `QuickBooks` - QuickBooks\n\* `Xero` - Xero\n\* `NetSuite` - NetSuite\n\* `WooCommerce` - WooCommerce\n\* `BigCommerce` - BigCommerce\n\* `PayPal` - PayPal\n\* `Square` - Square\n\* `Zoom` - Zoom\n\* `Trello` - Trello\n\* `Monday` - Monday\n\* `ClickUp` - ClickUp\n\* `Confluence` - Confluence\n\* `Recurly` - Recurly\n\* `SalesLoft` - SalesLoft\n\* `Outreach` - Outreach\n\* `Gong` - Gong\n\* `Calendly` - Calendly\n\* `Typeform` - Typeform\n\* `Iterable` - Iterable\n\* `ZohoCRM` - ZohoCRM\n\* `Close` - Close\n\* `Oracle` - Oracle\n\* `DynamoDB` - DynamoDB\n\* `Elasticsearch` - Elasticsearch\n\* `Kafka` - Kafka\n\* `LaunchDarkly` - LaunchDarkly\n\* `Braintree` - Braintree\n\* `Recharge` - Recharge\n\* `HelpScout` - HelpScout\n\* `Gorgias` - Gorgias\n\* `Instagram` - Instagram\n\* `YouTubeAnalytics` - YouTubeAnalytics\n\* `FacebookPages` - FacebookPages\n\* `TwitterAds` - TwitterAds\n\* `Workday` - Workday\n\* `ServiceNow` - ServiceNow\n\* `Pardot` - Pardot\n\* `Copper` - Copper\n\* `Front` - Front\n\* `ChartMogul` - ChartMogul\n\* `Zuora` - Zuora\n\* `Paddle` - Paddle\n\* `CircleCI` - CircleCI\n\* `CockroachDB` - CockroachDB\n\* `Firebase` - Firebase\n\* `AzureBlob` - AzureBlob\n\* `GoogleDrive` - GoogleDrive\n\* `OneDrive` - OneDrive\n\* `SharePoint` - SharePoint\n\* `Box` - Box\n\* `SFTP` - SFTP\n\* `MicrosoftTeams` - MicrosoftTeams\n\* `Aircall` - Aircall\n\* `Webflow` - Webflow\n\* `Okta` - Okta\n\* `Auth0` - Auth0\n\* `Productboard` - Productboard\n\* `Smartsheet` - Smartsheet\n\* `Wrike` - Wrike\n\* `Plaid` - Plaid\n\* `SurveyMonkey` - SurveyMonkey\n\* `Eventbrite` - Eventbrite\n\* `RingCentral` - RingCentral\n\* `Twilio` - Twilio\n\* `Freshsales` - Freshsales\n\* `Shortcut` - Shortcut\n\* `ConvertKit` - ConvertKit\n\* `Drip` - Drip\n\* `CampaignMonitor` - CampaignMonitor\n\* `MailerLite` - MailerLite\n\* `Omnisend` - Omnisend\n\* `Brevo` - Brevo\n\* `Postmark` - Postmark\n\* `Granola` - Granola\n\* `BuildBetter` - BuildBetter\n\* `Convex` - Convex\n\* `ClickHouse` - ClickHouse\n\* `Plain` - Plain\n\* `Resend` - Resend\n\* `PgAnalyze` - PgAnalyze\n\* `WorkOS` - WorkOS\n\* `AmazonS3` - AmazonS3\n\* `GoogleCloudStorage` - GoogleCloudStorage\n\* `Databricks` - Databricks\n\* `Dynamics365` - Dynamics365\n\* `SalesforceMarketingCloud` - SalesforceMarketingCloud\n\* `Db2` - Db2\n\* `Heap` - Heap\n\* `AdobeAnalytics` - AdobeAnalytics\n\* `Matomo` - Matomo\n\* `Optimizely` - Optimizely\n\* `Adyen` - Adyen\n\* `GoCardless` - GoCardless\n\* `Mollie` - Mollie\n\* `CheckoutCom` - CheckoutCom\n\* `Branch` - Branch\n\* `Criteo` - Criteo\n\* `Outbrain` - Outbrain\n\* `Taboola` - Taboola\n\* `AdRoll` - AdRoll\n\* `DisplayVideo360` - DisplayVideo360\n\* `GoogleAdManager` - GoogleAdManager\n\* `CampaignManager360` - CampaignManager360\n\* `SearchAds360` - SearchAds360\n\* `AdobeCommerce` - AdobeCommerce\n\* `AmazonSellingPartner` - AmazonSellingPartner\n\* `Ebay` - Ebay\n\* `Commercetools` - Commercetools\n\* `LightspeedRetail` - LightspeedRetail\n\* `ShipStation` - ShipStation\n\* `ConstantContact` - ConstantContact\n\* `Mailgun` - Mailgun\n\* `Eloqua` - Eloqua\n\* `Sailthru` - Sailthru\n\* `Ortto` - Ortto\n\* `Attentive` - Attentive\n\* `Kustomer` - Kustomer\n\* `Dixa` - Dixa\n\* `Gladly` - Gladly\n\* `Qualtrics` - Qualtrics\n\* `Delighted` - Delighted\n\* `AzureDevOps` - AzureDevOps\n\* `Rollbar` - Rollbar\n\* `Opsgenie` - Opsgenie\n\* `IncidentIo` - IncidentIo\n\* `Pingdom` - Pingdom\n\* `Cloudflare` - Cloudflare\n\* `CosmosDB` - CosmosDB\n\* `PlanetScale` - PlanetScale\n\* `SapHana` - SapHana\n\* `Rippling` - Rippling\n\* `HiBob` - HiBob\n\* `Personio` - Personio\n\* `Deel` - Deel\n\* `AdpWorkforceNow` - AdpWorkforceNow\n\* `Paylocity` - Paylocity\n\* `Gusto` - Gusto\n\* `CultureAmp` - CultureAmp\n\* `Lattice` - Lattice\n\* `SageIntacct` - SageIntacct\n\* `FreshBooks` - FreshBooks\n\* `Expensify` - Expensify\n\* `Ramp` - Ramp\n\* `Brex` - Brex\n\* `Coupa` - Coupa\n\* `SapConcur` - SapConcur\n\* `Apollo` - Apollo\n\* `Crunchbase` - Crunchbase\n\* `ZoomInfo` - ZoomInfo\n\* `Clari` - Clari\n\* `Chorus` - Chorus\n\* `Coda` - Coda\n\* `Guru` - Guru\n\* `Dropbox` - Dropbox\n\* `Docusign` - Docusign\n\* `PandaDoc` - PandaDoc\n\* `SapErp` - SapErp\n\* `SapSuccessFactors` - SapSuccessFactors\n\* `OracleEbs` - OracleEbs\n\* `OracleFusion` - OracleFusion\n\* `Custom` - Custom'+ )+ .describe(+ "The source type these credentials are for (e.g. 'Stripe', 'Postgres').\n\n\* `Ashby` - Ashby\n\* `Supabase` - Supabase\n\* `CustomerIO` - CustomerIO\n\* `Github` - Github\n\* `Stripe` - Stripe\n\* `Hubspot` - Hubspot\n\* `Postgres` - Postgres\n\* `Zendesk` - Zendesk\n\* `Snowflake` - Snowflake\n\* `Salesforce` - Salesforce\n\* `MySQL` - MySQL\n\* `MongoDB` - MongoDB\n\* `MSSQL` - MSSQL\n\* `Vitally` - Vitally\n\* `BigQuery` - BigQuery\n\* `Chargebee` - Chargebee\n\* `Clerk` - Clerk\n\* `GoogleAds` - GoogleAds\n\* `GoogleSearchConsole` - GoogleSearchConsole\n\* `TemporalIO` - TemporalIO\n\* `DoIt` - DoIt\n\* `GoogleSheets` - GoogleSheets\n\* `MetaAds` - MetaAds\n\* `Klaviyo` - Klaviyo\n\* `Mailchimp` - Mailchimp\n\* `Braze` - Braze\n\* `Mailjet` - Mailjet\n\* `Redshift` - Redshift\n\* `Polar` - Polar\n\* `RevenueCat` - RevenueCat\n\* `LinkedinAds` - LinkedinAds\n\* `RedditAds` - RedditAds\n\* `TikTokAds` - TikTokAds\n\* `BingAds` - BingAds\n\* `Shopify` - Shopify\n\* `Attio` - Attio\n\* `SnapchatAds` - SnapchatAds\n\* `Linear` - Linear\n\* `Intercom` - Intercom\n\* `Amplitude` - Amplitude\n\* `Mixpanel` - Mixpanel\n\* `Jira` - Jira\n\* `ActiveCampaign` - ActiveCampaign\n\* `Marketo` - Marketo\n\* `Adjust` - Adjust\n\* `AppsFlyer` - AppsFlyer\n\* `Freshdesk` - Freshdesk\n\* `GoogleAnalytics` - GoogleAnalytics\n\* `Pipedrive` - Pipedrive\n\* `SendGrid` - SendGrid\n\* `Slack` - Slack\n\* `PagerDuty` - PagerDuty\n\* `Asana` - Asana\n\* `Notion` - Notion\n\* `Airtable` - Airtable\n\* `Greenhouse` - Greenhouse\n\* `BambooHR` - BambooHR\n\* `Lever` - Lever\n\* `GitLab` - GitLab\n\* `Datadog` - Datadog\n\* `Sentry` - Sentry\n\* `Pendo` - Pendo\n\* `FullStory` - FullStory\n\* `AmazonAds` - AmazonAds\n\* `PinterestAds` - PinterestAds\n\* `AppleSearchAds` - AppleSearchAds\n\* `QuickBooks` - QuickBooks\n\* `Xero` - Xero\n\* `NetSuite` - NetSuite\n\* `WooCommerce` - WooCommerce\n\* `BigCommerce` - BigCommerce\n\* `PayPal` - PayPal\n\* `Square` - Square\n\* `Zoom` - Zoom\n\* `Trello` - Trello\n\* `Monday` - Monday\n\* `ClickUp` - ClickUp\n\* `Confluence` - Confluence\n\* `Recurly` - Recurly\n\* `SalesLoft` - SalesLoft\n\* `Outreach` - Outreach\n\* `Gong` - Gong\n\* `Calendly` - Calendly\n\* `Typeform` - Typeform\n\* `Iterable` - Iterable\n\* `ZohoCRM` - ZohoCRM\n\* `Close` - Close\n\* `Oracle` - Oracle\n\* `DynamoDB` - DynamoDB\n\* `Elasticsearch` - Elasticsearch\n\* `Kafka` - Kafka\n\* `LaunchDarkly` - LaunchDarkly\n\* `Braintree` - Braintree\n\* `Recharge` - Recharge\n\* `HelpScout` - HelpScout\n\* `Gorgias` - Gorgias\n\* `Instagram` - Instagram\n\* `YouTubeAnalytics` - YouTubeAnalytics\n\* `FacebookPages` - FacebookPages\n\* `TwitterAds` - TwitterAds\n\* `Workday` - Workday\n\* `ServiceNow` - ServiceNow\n\* `Pardot` - Pardot\n\* `Copper` - Copper\n\* `Front` - Front\n\* `ChartMogul` - ChartMogul\n\* `Zuora` - Zuora\n\* `Paddle` - Paddle\n\* `CircleCI` - CircleCI\n\* `CockroachDB` - CockroachDB\n\* `Firebase` - Firebase\n\* `AzureBlob` - AzureBlob\n\* `GoogleDrive` - GoogleDrive\n\* `OneDrive` - OneDrive\n\* `SharePoint` - SharePoint\n\* `Box` - Box\n\* `SFTP` - SFTP\n\* `MicrosoftTeams` - MicrosoftTeams\n\* `Aircall` - Aircall\n\* `Webflow` - Webflow\n\* `Okta` - Okta\n\* `Auth0` - Auth0\n\* `Productboard` - Productboard\n\* `Smartsheet` - Smartsheet\n\* `Wrike` - Wrike\n\* `Plaid` - Plaid\n\* `SurveyMonkey` - SurveyMonkey\n\* `Eventbrite` - Eventbrite\n\* `RingCentral` - RingCentral\n\* `Twilio` - Twilio\n\* `Freshsales` - Freshsales\n\* `Shortcut` - Shortcut\n\* `ConvertKit` - ConvertKit\n\* `Drip` - Drip\n\* `CampaignMonitor` - CampaignMonitor\n\* `MailerLite` - MailerLite\n\* `Omnisend` - Omnisend\n\* `Brevo` - Brevo\n\* `Postmark` - Postmark\n\* `Granola` - Granola\n\* `BuildBetter` - BuildBetter\n\* `Convex` - Convex\n\* `ClickHouse` - ClickHouse\n\* `Plain` - Plain\n\* `Resend` - Resend\n\* `PgAnalyze` - PgAnalyze\n\* `WorkOS` - WorkOS\n\* `AmazonS3` - AmazonS3\n\* `GoogleCloudStorage` - GoogleCloudStorage\n\* `Databricks` - Databricks\n\* `Dynamics365` - Dynamics365\n\* `SalesforceMarketingCloud` - SalesforceMarketingCloud\n\* `Db2` - Db2\n\* `Heap` - Heap\n\* `AdobeAnalytics` - AdobeAnalytics\n\* `Matomo` - Matomo\n\* `Optimizely` - Optimizely\n\* `Adyen` - Adyen\n\* `GoCardless` - GoCardless\n\* `Mollie` - Mollie\n\* `CheckoutCom` - CheckoutCom\n\* `Branch` - Branch\n\* `Criteo` - Criteo\n\* `Outbrain` - Outbrain\n\* `Taboola` - Taboola\n\* `AdRoll` - AdRoll\n\* `DisplayVideo360` - DisplayVideo360\n\* `GoogleAdManager` - GoogleAdManager\n\* `CampaignManager360` - CampaignManager360\n\* `SearchAds360` - SearchAds360\n\* `AdobeCommerce` - AdobeCommerce\n\* `AmazonSellingPartner` - AmazonSellingPartner\n\* `Ebay` - Ebay\n\* `Commercetools` - Commercetools\n\* `LightspeedRetail` - LightspeedRetail\n\* `ShipStation` - ShipStation\n\* `ConstantContact` - ConstantContact\n\* `Mailgun` - Mailgun\n\* `Eloqua` - Eloqua\n\* `Sailthru` - Sailthru\n\* `Ortto` - Ortto\n\* `Attentive` - Attentive\n\* `Kustomer` - Kustomer\n\* `Dixa` - Dixa\n\* `Gladly` - Gladly\n\* `Qualtrics` - Qualtrics\n\* `Delighted` - Delighted\n\* `AzureDevOps` - AzureDevOps\n\* `Rollbar` - Rollbar\n\* `Opsgenie` - Opsgenie\n\* `IncidentIo` - IncidentIo\n\* `Pingdom` - Pingdom\n\* `Cloudflare` - Cloudflare\n\* `CosmosDB` - CosmosDB\n\* `PlanetScale` - PlanetScale\n\* `SapHana` - SapHana\n\* `Rippling` - Rippling\n\* `HiBob` - HiBob\n\* `Personio` - Personio\n\* `Deel` - Deel\n\* `AdpWorkforceNow` - AdpWorkforceNow\n\* `Paylocity` - Paylocity\n\* `Gusto` - Gusto\n\* `CultureAmp` - CultureAmp\n\* `Lattice` - Lattice\n\* `SageIntacct` - SageIntacct\n\* `FreshBooks` - FreshBooks\n\* `Expensify` - Expensify\n\* `Ramp` - Ramp\n\* `Brex` - Brex\n\* `Coupa` - Coupa\n\* `SapConcur` - SapConcur\n\* `Apollo` - Apollo\n\* `Crunchbase` - Crunchbase\n\* `ZoomInfo` - ZoomInfo\n\* `Clari` - Clari\n\* `Chorus` - Chorus\n\* `Coda` - Coda\n\* `Guru` - Guru\n\* `Dropbox` - Dropbox\n\* `Docusign` - Docusign\n\* `PandaDoc` - PandaDoc\n\* `SapErp` - SapErp\n\* `SapSuccessFactors` - SapSuccessFactors\n\* `OracleEbs` - OracleEbs\n\* `OracleFusion` - OracleFusion\n\* `Custom` - Custom"+ ),+ payload: zod+ .record(zod.string(), zod.unknown())+ .describe(+ 'Connection details as flat keys for the source_type — the same fields the create flow accepts (host, port, password, API key, …). Checked against a live connection before being stored.'+ ),+})+export const insightVariablesCreateBodyNameMax = 400export const InsightVariablesCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/data_warehouse/frontend/scenes/SourceConnectScene/SourceConnectScene.tsx b/products/data_warehouse/frontend/scenes/SourceConnectScene/SourceConnectScene.tsxnew file mode 100644index 000000000000..1bea4e746772--- /dev/null+++ b/products/data_warehouse/frontend/scenes/SourceConnectScene/SourceConnectScene.tsx@@ -0,0 +1,137 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'++import { IconQuestion } from '@posthog/icons'+import { LemonButton, LemonSkeleton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { SceneExport } from 'scenes/sceneTypes'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { SourceFormComponent } from '../../shared/components/forms/SourceForm'+import { SourceIcon } from '../../shared/components/SourceIcon'+import { sourceConnectSceneLogic } from './sourceConnectSceneLogic'++export const scene: SceneExport = {+ component: SourceConnectScene,+ logic: sourceConnectSceneLogic,+}++export function SourceConnectScene(): JSX.Element {+ const {+ kind,+ sourceConfig,+ isOauthSource,+ storedCredential,+ availableSourcesLoading,+ isCredentialsFormSubmitting,+ } = useValues(sourceConnectSceneLogic)+ const { setCredentialsFormValue } = useActions(sourceConnectSceneLogic)++ if (availableSourcesLoading) {+ return <LemonSkeleton />+ }++ if (!sourceConfig) {+ return (+ <SceneContent>+ <LemonBanner type="error">+ {kind ? `Unknown source type '${kind}'.` : 'No source type specified.'} Check the link you were+ given and try again.+ </LemonBanner>+ </SceneContent>+ )+ }++ const sourceLabel = sourceConfig.label ?? sourceConfig.name++ return (+ <SceneContent>+ <SceneTitleSection+ name={`Connect ${sourceLabel}`}+ resourceType={{ type: 'data_pipeline' }}+ description={+ isOauthSource || storedCredential+ ? undefined+ : `Enter your ${sourceLabel} credentials. They are stored encrypted, kept only until the source is created (at most 24 hours), and never shared with anyone — including the assistant that sent you here.`+ }+ />+ <div className="max-w-200">+ {storedCredential ? (+ <LemonBanner type="success">+ <p className="font-semibold mb-1">{sourceLabel} credentials saved — you can close this tab.</p>+ <p className="m-0 text-sm">+ Return to your chat and let the assistant know you're done; it will finish setting up the+ source. Credential id: <code>{storedCredential.credential_id}</code>.+ </p>+ </LemonBanner>+ ) : isOauthSource ? (+ <LemonBanner type="info">+ <p className="font-semibold mb-1">{sourceLabel} connects through your browser.</p>+ <p className="m-0 text-sm">+ If you've just finished authorizing {sourceLabel} in this window, you're all set — return to+ your chat and let the assistant know, and it will finish setting up the source.+ </p>+ </LemonBanner>+ ) : (+ <Form+ logic={sourceConnectSceneLogic}+ formKey="credentialsForm"+ enableFormOnSubmit+ className="space-y-4"+ >+ <div className="flex items-center gap-2">+ <SourceIcon type={sourceConfig.name} size="small" />+ <span className="font-semibold">{sourceLabel}</span>+ </div>+ {(sourceConfig.permissionsCaption || sourceConfig.docsUrl) && (+ <div className="flex flex-row items-center gap-1">+ {sourceConfig.permissionsCaption && (+ <Tooltip+ title={+ <LemonMarkdown className="text-sm">+ {sourceConfig.permissionsCaption}+ </LemonMarkdown>+ }+ interactive+ >+ <LemonTag type="muted" size="small">+ Permissions required <IconQuestion />+ </LemonTag>+ </Tooltip>+ )}+ {sourceConfig.permissionsCaption && sourceConfig.docsUrl && <span> | </span>}+ {sourceConfig.docsUrl && (+ <Link to={sourceConfig.docsUrl} target="_blank">+ View docs+ </Link>+ )}+ </div>+ )}+ <SourceFormComponent+ sourceConfig={sourceConfig}+ showPrefix={false}+ showDescription={false}+ showAccessMethodSelector={false}+ showCdcConfig={false}+ setSourceConnectionDetailsValue={setCredentialsFormValue}+ />+ <LemonButton+ type="primary"+ htmlType="submit"+ loading={isCredentialsFormSubmitting}+ disabledReason={isCredentialsFormSubmitting ? 'Saving…' : undefined}+ >+ Save credentials+ </LemonButton>+ </Form>+ )}+ </div>+ </SceneContent>+ )+}++export default SourceConnectScenediff --git a/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.test.tsnew file mode 100644index 000000000000..971a7bd35532--- /dev/null+++ b/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.test.ts@@ -0,0 +1,138 @@+import { router } from 'kea-router'++import { useMocks } from '~/mocks/jest'+import type { SourceConfig } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { availableSourcesLogic } from '../NewSourceScene/availableSourcesLogic'+import { sourceConnectSceneLogic } from './sourceConnectSceneLogic'++const AVAILABLE_SOURCES: Record<string, SourceConfig> = {+ Postgres: {+ name: 'Postgres',+ iconPath: '',+ caption: '',+ fields: [{ type: 'text', name: 'host', label: 'Host', required: true, placeholder: '' }],+ } as unknown as SourceConfig,+ Hubspot: {+ name: 'Hubspot',+ iconPath: '',+ caption: '',+ fields: [+ {+ type: 'oauth',+ name: 'hubspot_integration_id',+ label: 'Hubspot account',+ required: true,+ kind: 'hubspot',+ },+ ],+ } as unknown as SourceConfig,+ Stripe: {+ name: 'Stripe',+ iconPath: '',+ caption: '',+ fields: [+ {+ type: 'select',+ name: 'auth_method',+ label: 'Auth method',+ required: true,+ defaultValue: 'api_key',+ options: [+ {+ label: 'API key',+ value: 'api_key',+ fields: [+ {+ type: 'password',+ name: 'stripe_secret_key',+ label: 'Secret key',+ required: true,+ placeholder: '',+ },+ ],+ },+ {+ label: 'OAuth',+ value: 'oauth',+ fields: [+ {+ type: 'oauth',+ name: 'stripe_integration_id',+ label: 'Stripe account',+ required: true,+ kind: 'stripe',+ },+ ],+ },+ ],+ },+ ],+ } as unknown as SourceConfig,+}++describe('sourceConnectSceneLogic', () => {+ let unmountAvailableSources: () => void+ let unmountLogic: () => void++ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/external_data_sources/wizard/': AVAILABLE_SOURCES,+ },+ })+ initKeaTests()+ unmountAvailableSources = availableSourcesLogic.mount()+ availableSourcesLogic.actions.loadSuccess(AVAILABLE_SOURCES)+ unmountLogic = sourceConnectSceneLogic.mount()+ })++ afterEach(() => {+ unmountLogic()+ unmountAvailableSources()+ })++ it.each([+ ['Postgres', 'Postgres'],+ ['postgres', 'Postgres'],+ ['HUBSPOT', 'Hubspot'],+ ])('resolves kind=%s to source config %s case-insensitively', (kind, expectedName) => {+ router.actions.push(`/data-warehouse/connect?kind=${kind}`)+ expect(sourceConnectSceneLogic.values.kind).toEqual(kind)+ expect(sourceConnectSceneLogic.values.sourceConfig?.name).toEqual(expectedName)+ })++ it('returns no source config for an unknown or missing kind', () => {+ router.actions.push('/data-warehouse/connect?kind=NotARealSource')+ expect(sourceConnectSceneLogic.values.sourceConfig).toBeNull()++ router.actions.push('/data-warehouse/connect')+ expect(sourceConnectSceneLogic.values.kind).toBeNull()+ expect(sourceConnectSceneLogic.values.sourceConfig).toBeNull()+ })++ it.each([+ ['Postgres', false],+ ['Hubspot', true],+ // Stripe's oauth field is nested inside a select option — must still count as oauth,+ // matching the backend's recursive _find_oauth_field+ ['Stripe', true],+ ])('classifies %s as oauth=%s', (kind, expected) => {+ router.actions.push(`/data-warehouse/connect?kind=${kind}`)+ expect(sourceConnectSceneLogic.values.isOauthSource).toEqual(expected)+ })++ it('starts with no stored credential and records one after setStoredCredential', () => {+ expect(sourceConnectSceneLogic.values.storedCredential).toBeNull()+ sourceConnectSceneLogic.actions.setStoredCredential({+ credential_id: 'ba07775f-8eaf-4d09-aa6f-50e37f17f243',+ source_type: 'Postgres',+ created_at: '2026-06-10T00:00:00Z',+ expires_at: '2026-06-11T00:00:00Z',+ })+ expect(sourceConnectSceneLogic.values.storedCredential?.credential_id).toEqual(+ 'ba07775f-8eaf-4d09-aa6f-50e37f17f243'+ )+ })+})diff --git a/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.tsx b/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.tsxnew file mode 100644index 000000000000..47d5d322d0d7--- /dev/null+++ b/products/data_warehouse/frontend/scenes/SourceConnectScene/sourceConnectSceneLogic.tsx@@ -0,0 +1,151 @@+import { actions, connect, kea, path, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'+import { urlToAction } from 'kea-router'++import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { Scene } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { ApiConfig } from '~/lib/api'+import { SourceConfig, SourceFieldConfig } from '~/queries/schema/schema-general'+import { Breadcrumb } from '~/types'++import { externalDataSourcesStoreCredentialsCreate } from '../../generated/api'+import type { SourceCredentialApi } from '../../generated/api.schemas'+import { availableSourcesLogic } from '../NewSourceScene/availableSourcesLogic'+import { getErrorsForFields } from '../NewSourceScene/sourceWizardLogic'+import type { sourceConnectSceneLogicType } from './sourceConnectSceneLogicType'++const containsOauthField = (fields: SourceFieldConfig[]): boolean =>+ fields.some((field) => {+ if (field.type === 'oauth') {+ return true+ }+ if (field.type === 'switch-group') {+ return containsOauthField(field.fields)+ }+ if (field.type === 'select') {+ return field.options.some((option) => containsOauthField(option.fields ?? []))+ }+ return false+ })++const buildCredentialsPayload = async (+ fields: SourceFieldConfig[],+ formPayload: Record<string, any>+): Promise<Record<string, any>> => {+ const payload: Record<string, any> = {}+ for (const field of fields) {+ const value = formPayload[field.name]+ if (field.type === 'file-upload') {+ if (value?.[0]) {+ // Assumes we're loading a JSON file, same as the wizard's submit+ const loadedFile: string = await new Promise((resolve, reject) => {+ const fileReader = new FileReader()+ fileReader.onload = (e) => resolve(e.target?.result as string)+ fileReader.onerror = (e) => reject(e)+ fileReader.readAsText(value[0])+ })+ payload[field.name] = JSON.parse(loadedFile)+ }+ } else {+ payload[field.name] = value+ }+ }+ return payload+}++export const sourceConnectSceneLogic = kea<sourceConnectSceneLogicType>([+ path(['products', 'dataWarehouse', 'sourceConnectSceneLogic']),+ connect(() => ({+ values: [availableSourcesLogic, ['availableSources', 'availableSourcesLoading']],+ })),+ actions({+ setKind: (kind: string | null) => ({ kind }),+ setStoredCredential: (credential: SourceCredentialApi) => ({ credential }),+ }),+ reducers({+ kind: [+ null as string | null,+ {+ setKind: (_, { kind }) => kind,+ },+ ],+ storedCredential: [+ null as SourceCredentialApi | null,+ {+ setStoredCredential: (_, { credential }) => credential,+ },+ ],+ }),+ selectors({+ sourceConfig: [+ (s) => [s.availableSources, s.kind],+ (availableSources, kind): SourceConfig | null => {+ if (!availableSources || !kind) {+ return null+ }+ return (+ Object.values(availableSources).find(+ (config) => config.name.toLowerCase() === kind.toLowerCase()+ ) ?? null+ )+ },+ ],+ isOauthSource: [+ (s) => [s.sourceConfig],+ (sourceConfig): boolean => (sourceConfig ? containsOauthField(sourceConfig.fields) : false),+ ],+ breadcrumbs: [+ (s) => [s.sourceConfig],+ (sourceConfig): Breadcrumb[] => [+ {+ key: Scene.Sources,+ name: 'Sources',+ path: urls.sources(),+ iconType: 'data_pipeline',+ },+ {+ key: Scene.DataWarehouseSourceConnect,+ name: sourceConfig ? `Connect ${sourceConfig.label ?? sourceConfig.name}` : 'Connect source',+ iconType: 'data_pipeline',+ },+ ],+ ],+ }),+ forms(({ actions, values }) => ({+ credentialsForm: {+ defaults: { payload: {} } as Record<string, any>,+ errors: (formValues) =>+ getErrorsForFields(values.sourceConfig?.fields ?? [], {+ prefix: '',+ payload: (formValues.payload ?? {}) as Record<string, any>,+ }),+ submit: async (formValues) => {+ if (!values.sourceConfig) {+ return+ }+ let payload: Record<string, any>+ try {+ payload = await buildCredentialsPayload(+ values.sourceConfig.fields,+ (formValues.payload ?? {}) as Record<string, any>+ )+ } catch {+ lemonToast.error('File is not valid')+ return+ }+ const credential = await externalDataSourcesStoreCredentialsCreate(+ String(ApiConfig.getCurrentTeamId()),+ { source_type: values.sourceConfig.name, payload }+ )+ actions.setStoredCredential(credential)+ },+ },+ })),+ urlToAction(({ actions }) => ({+ [urls.dataWarehouseSourceConnect()]: (_, searchParams) => {+ actions.setKind(searchParams.kind ?? null)+ },+ })),+])diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsxindex 260fa35beb60..ff6f03435694 100644--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx@@ -40,10 +40,13 @@ export interface SourceFormProps {showPrefix?: booleanshowDescription?: booleanshowAccessMethodSelector?: boolean+ showCdcConfig?: booleanjobInputs?: Record<string, any>initialAccessMethod?: 'warehouse' | 'direct'setSourceConfigValue?: (key: FieldName, value: any) => voidsourceWizardLogicProps?: SourceWizardLogicProps+ /** Override the form value setter — for hosts other than the wizard (e.g. the connect page). */+ setSourceConnectionDetailsValue?: (key: FieldName, value: any) => void}export function SourceAccessMethodSelector({@@ -641,16 +644,20 @@ export function SourceFormComponent({showPrefix = true,showDescription,showAccessMethodSelector = true,+ showCdcConfig = true,jobInputs,initialAccessMethod,setSourceConfigValue,sourceWizardLogicProps,+ setSourceConnectionDetailsValue: setSourceConnectionDetailsValueOverride,}: SourceFormProps): JSX.Element {const { availableSources, availableSourcesLoading } = useValues(availableSourcesLogic)const { featureFlags } = useValues(featureFlagLogic)- const setSourceConnectionDetailsValue = sourceWizardLogicProps- ? sourceWizardLogic(sourceWizardLogicProps).actions.setSourceConnectionDetailsValue- : undefined+ const setSourceConnectionDetailsValue =+ setSourceConnectionDetailsValueOverride ??+ (sourceWizardLogicProps+ ? sourceWizardLogic(sourceWizardLogicProps).actions.setSourceConnectionDetailsValue+ : undefined)// Default showDescription to same as showPrefix for backward compatibilityconst shouldShowDescription = showDescription ?? showPrefix@@ -776,6 +783,7 @@ export function SourceFormComponent({)}</Group>{!isUpdateMode &&+ showCdcConfig &&sourceConfig.name === 'Postgres' &&featureFlags[FEATURE_FLAGS.DWH_POSTGRES_CDC] &&selectedAccessMethod === 'warehouse' && <CDCConfigSection />}diff --git a/products/data_warehouse/manifest.tsx b/products/data_warehouse/manifest.tsxindex f4fc7cdf7be3..8513f1c75ea9 100644--- a/products/data_warehouse/manifest.tsx+++ b/products/data_warehouse/manifest.tsx@@ -58,6 +58,11 @@ export const manifest: ProductManifest = {projectBased: true,name: 'New data warehouse source',},+ DataWarehouseSourceConnect: {+ import: () => import('./frontend/scenes/SourceConnectScene/SourceConnectScene'),+ projectBased: true,+ name: 'Connect data warehouse source',+ },DataWarehouseSourceSchema: {import: () => import('./frontend/scenes/SchemaScene/SchemaScene'),projectBased: true,@@ -84,6 +89,7 @@ export const manifest: ProductManifest = {],'/data-management/sources/:id/:tab': ['DataWarehouseSource', 'dataWarehouseSource'],'/data-warehouse/new-source': ['DataWarehouseSourceNew', 'dataWarehouseSourceNew'],+ '/data-warehouse/connect': ['DataWarehouseSourceConnect', 'dataWarehouseSourceConnect'],},redirects: {'/data-warehouse/sources/:id': ({ id }) => urls.dataWarehouseSource(id, 'schemas'),@@ -130,6 +136,8 @@ export const manifest: ProductManifest = {const queryString = params.toString()return `/data-warehouse/new-source${queryString ? `?${queryString}` : ''}`},+ dataWarehouseSourceConnect: (kind?: string): string =>+ `/data-warehouse/connect${kind ? `?kind=${encodeURIComponent(kind)}` : ''}`,},treeItemsProducts: [{diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex dbdb9484dad6..8466b487fcdb 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -65,6 +65,80 @@ tools:data-warehouse-running-activity-retrieve:operation: data_warehouse_running_activity_retrieveenabled: false+ data-warehouse-source-connect-link:+ operation: external_data_sources_connect_link_retrieve+ enabled: true+ scopes:+ - external_data_source:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get a secure connect link for a source+ description: >+ Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the+ chat. For OAuth sources (Hubspot, Salesforce, Google Ads, …) it returns an authorization URL; for credential+ sources (Postgres, MySQL, Stripe API key, …) it links to a minimal page where the user enters only their+ credentials — the page stores them encrypted and temporarily, and does NOT create the source. This is the+ preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to+ confirm they're done, then find the stored reference (OAuth: 'integrations-list' filtered by the source's+ kind; credentials: 'data-warehouse-stored-credentials-list' filtered by source_type) and call+ 'data-warehouse-source-setup' with the returned integration_field key (e.g. {'hubspot_integration_id': 123}+ or {'credential_id': '<uuid>'}). Stored credentials are single-use and expire after 24 hours. Never ask the+ user to paste raw database passwords or API keys into the chat.+ param_overrides:+ source_type:+ input_schema: ExternalDataSourceTypeSchema+ data-warehouse-source-setup:+ operation: external_data_sources_setup_create+ enabled: true+ scopes:+ - external_data_source:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Set up a data warehouse source (one step)+ description: >+ Connect an external data source and start importing it into queryable warehouse tables in a single call.+ Validates credentials, discovers all available tables, enables them with sensible sync defaults (incremental+ where supported to keep ongoing cost low), and creates the source — no 'schemas' array required. For+ webhook-capable sources (e.g. Stripe) a webhook is auto-registered after creation: check the 'webhook' key+ in the response — on success webhook-capable tables sync in real time (including webhook-only tables like+ Stripe Discount); on failure (e.g. the API key can't create webhooks) tables keep the polling defaults and+ webhook-only tables stay disabled. If 'webhook.pending_inputs' is non-empty, ask the user for those values+ and submit them via 'external-data-sources-update-webhook-inputs-create'. Use this for revenue (Stripe), CRM+ (Hubspot, Salesforce), support tickets (Zendesk), e-commerce (Shopify), and your own databases (Postgres,+ MySQL, BigQuery, Snowflake). Discover required credential fields per source_type with+ 'external-data-sources-wizard'. Prefer references over raw secrets in the payload: for OAuth sources pass+ the integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id':+ '<uuid>'} referencing credentials the user stored via the 'data-warehouse-source-connect-link' page+ (discover ids with 'data-warehouse-stored-credentials-list'). Stored credentials are deleted once the source+ is created. For fine-grained per-table control, use 'external-data-sources-create' instead.+ exclude_params:+ - client_secret+ - account_id+ param_overrides:+ source_type:+ input_schema: ExternalDataSourceTypeSchema+ data-warehouse-stored-credentials-list:+ operation: external_data_sources_stored_credentials_list+ enabled: true+ scopes:+ - external_data_source:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List stored source credentials awaiting setup+ description: >+ List credentials the user stored via the 'data-warehouse-source-connect-link' page that haven't been+ consumed yet. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets+ themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page,+ take the newest credential_id for the source type and call 'data-warehouse-source-setup' with+ {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as+ setup consumes them — and expire after 24 hours if never used.data-warehouse-total-rows-stats-retrieve:operation: data_warehouse_total_rows_stats_retrieveenabled: false@@ -129,7 +203,7 @@ tools:destructive: falseidempotent: truelist: true- title: List data import schemas+ title: List data warehouse table schemas (imported tables)description: >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,@@ -143,7 +217,7 @@ tools:readOnly: falsedestructive: falseidempotent: true- title: Update data import schema+ title: Update data warehouse table schema sync configdescription: >Update a table schema's sync configuration. Can change sync type, sync frequency, incremental field, primarykey columns, CDC table mode, and enable/disable the schema.@@ -183,7 +257,7 @@ tools:readOnly: truedestructive: falseidempotent: true- title: Get data import schema+ title: Get data warehouse table schemadescription: >Get a single table schema by ID. Returns full details including sync status, sync frequency, incrementalfield, latest error, and the associated source and table metadata.@@ -242,15 +316,16 @@ tools:readOnly: falsedestructive: falseidempotent: false- title: Create data warehouse source- description: >- Create a new external data source connection. Before calling this, use 'external-data-sources-wizard' to- discover source types and 'external-data-sources-db-schema' to validate credentials and discover available- tables. Present the db-schema results to the user showing each table's available sync methods, incremental- fields, detected primary keys, and columns so they can configure before creation. The payload must include a- 'schemas' array where each entry has: name, should_sync (bool), sync_type (incremental/full_refresh/append),- and optionally incremental_field, incremental_field_type, and primary_key_columns from the db-schema- response.+ title: Create data warehouse source (advanced; prefer source setup)+ description: >+ Low-level create for a data warehouse import source when you need to hand-pick tables and sync types. For+ most cases prefer 'data-warehouse-source-setup', which validates credentials, discovers tables, applies+ sensible sync defaults, and creates the source in one call. Use this advanced path only for fine-grained+ control. The payload must include a 'schemas' array where each entry has: name, should_sync (bool),+ sync_type (incremental/full_refresh/append), and optionally incremental_field, incremental_field_type, and+ primary_key_columns. Discover tables and their available sync methods with 'external-data-sources-wizard'+ (source types and required fields) first. Sources back queryable warehouse tables for revenue (Stripe), CRM+ (Hubspot, Salesforce), support (Zendesk), and your own databases (Postgres, MySQL, BigQuery).exclude_params:- client_secret- account_id@@ -351,8 +426,10 @@ tools:idempotent: truetitle: Update data warehouse sourcedescription: >- Update an existing data warehouse source. Can change the prefix (table name prefix in HogQL), description,- or connection credentials via job_inputs. Cannot change the source_type or access_method after creation.+ Update an existing data warehouse source's prefix (table name prefix in HogQL) or description. Cannot change+ the source_type or access_method after creation. Avoid sending new connection credentials inline here — to+ rotate or fix credentials, point the user at 'data-warehouse-source-connect-link' so they re-enter them+ securely in their browser rather than pasting secrets into the chat.external-data-sources-refresh-schemas:operation: external_data_sources_refresh_schemas_createenabled: true@@ -411,6 +488,9 @@ tools:external-data-sources-source-prefix-create:operation: external_data_sources_source_prefix_createenabled: false+ external-data-sources-store-credentials-create:+ operation: external_data_sources_store_credentials_create+ enabled: falseexternal-data-sources-update:operation: external_data_sources_updateenabled: false@@ -457,11 +537,14 @@ tools:readOnly: truedestructive: falseidempotent: true- title: Get source type configurations- description: >- Return the configuration metadata for all supported data warehouse source types. Each entry describes the- required fields (host, port, database, credentials, etc.), field types, and OAuth flows. Use this to- discover what source types are available and what parameters are needed to create a new source.+ title: List data warehouse source types you can import+ description: >+ Return the configuration metadata for all supported data warehouse source types you can import data from —+ revenue/payments (Stripe, Chargebee), CRM (Hubspot, Salesforce), support tickets (Zendesk), product+ databases (Postgres, MySQL, BigQuery, Snowflake), ads, and more. Each entry describes the required fields+ (host, port, database, credentials, etc.), field types, and OAuth flows. Use this to discover what external+ data can be imported into queryable warehouse tables and what parameters a source needs. To actually connect+ a source, prefer 'data-warehouse-source-setup'.response:include:- '*.name'diff --git a/products/data_warehouse/skills/setting-up-a-data-warehouse-source/SKILL.md b/products/data_warehouse/skills/setting-up-a-data-warehouse-source/SKILL.mdindex 69f5d7408e31..26f536854368 100644--- a/products/data_warehouse/skills/setting-up-a-data-warehouse-source/SKILL.md+++ b/products/data_warehouse/skills/setting-up-a-data-warehouse-source/SKILL.md@@ -11,8 +11,12 @@ description: ># Setting up a data warehouse sourceUse this skill when the user wants to connect an external data source to PostHog's data warehouse for the first time.-The setup has a specific three-step flow (wizard → db-schema → create) — skipping steps leads to failed sources and-confused users.++**Default to the one-step flow:** `data-warehouse-source-setup` validates credentials, discovers every table, enables+them with sensible sync defaults (incremental where possible), and creates the source in a single call — no+`schemas` array to assemble. For credentials, hand the user a secure browser link with `data-warehouse-source-connect-link`+instead of collecting secrets in chat. Only drop to the manual `wizard → db-schema → create` flow when the user wants to+hand-pick which tables sync or set non-default sync types per table.## When to use this skill@@ -23,22 +27,66 @@ confused users.## Available tools-| Tool | Purpose |-| ------------------------------------------------------ | -------------------------------------------------------------------------------- |-| `external-data-sources-wizard` | Discover which source types exist and what fields each needs |-| `external-data-sources-db-schema` | Validate credentials and list tables with available sync methods per table |-| `external-data-sources-create` | Create the source — requires a `schemas` array built from the db-schema response |-| `external-data-sources-check-cdc-prerequisites-create` | Postgres CDC pre-flight check (optional, only for Postgres CDC) |-| `external-data-sources-webhook-info-retrieve` | Check if a source supports webhooks and whether one has been registered |-| `external-data-sources-create-webhook-create` | Register a webhook with the external service after source creation |-| `external-data-sources-update-webhook-inputs-create` | Supply the signing secret manually when auto-registration failed |-| `external-data-sources-list` | After creation, confirm the source is listed and see its initial status |-| `external-data-schemas-list` | See per-table sync status once the source is created |--## The three-step flow--Every source setup follows the same shape. Don't try to shortcut to `external-data-sources-create` — you need the-db-schema response to build a valid `schemas` payload.+| Tool | Purpose |+| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |+| `data-warehouse-source-connect-link` | **Preferred for credentials** — get a secure browser/OAuth link so the user authenticates without pasting secrets in chat |+| `data-warehouse-source-setup` | **Preferred to create** — one call: validate creds, discover tables, apply sync defaults, create the source |+| `external-data-sources-wizard` | Discover which source types exist and what fields each needs (advanced flow) |+| `external-data-sources-db-schema` | Validate credentials and list tables with available sync methods per table (advanced flow) |+| `external-data-sources-create` | Advanced create — requires a `schemas` array built from the db-schema response |+| `external-data-sources-check-cdc-prerequisites-create` | Postgres CDC pre-flight check (optional, only for Postgres CDC) |+| `external-data-sources-webhook-info-retrieve` | Check if a source supports webhooks and whether one has been registered |+| `external-data-sources-create-webhook-create` | Register a webhook with the external service after source creation |+| `external-data-sources-update-webhook-inputs-create` | Supply the signing secret manually when auto-registration failed |+| `external-data-sources-list` | After creation, confirm the source is listed and see its initial status |+| `external-data-schemas-list` | See per-table sync status once the source is created |++## Recommended: one-step setup++Most setups should use this path — it avoids the most common failures (skipping db-schema, malformed `schemas`,+missing required fields).++1. **Discover the source type and its fields** (optional): `external-data-sources-wizard` lists every source type and+ the credential fields each needs. Use it to know what to ask the user for; skip it if the source type is obvious.+2. **Collect credentials securely**: call `data-warehouse-source-connect-link({source_type})`. It returns a+ `connect_url` to share with the user. Either way the page is a terminal hand-off: it collects the authorization or+ credentials and nothing else — the user returns to the chat and you finish setup:+ - **OAuth sources** (Hubspot, Salesforce, Google Ads, …) → an authorize URL. After the user confirms they've+ authorized, find the new integration id via `integrations-list` (filter by the source's kind) and pass the+ returned `integration_field` key to setup (e.g. `{"hubspot_integration_id": 123}`).+ - **Credential sources** (Postgres, MySQL, Stripe API key, …) → a minimal connect page where they enter only their+ credentials over TLS. The page validates them against a live connection and stashes them encrypted in a temporary+ store — it does NOT create the source. After the user confirms they're done, find the stored credential id via+ `data-warehouse-stored-credentials-list` (filter by `source_type`, newest first; the page also shows the id to+ the user) and pass `{"credential_id": <id>}` to setup. Stored credentials are single-use — deleted as soon as+ setup consumes them — and expire after 24 hours.++ Never ask the user to paste raw database passwords or API keys into the chat.++3. **Create in one call**: `data-warehouse-source-setup({source_type, payload, prefix})`. The server validates+ credentials, discovers all tables, enables them with sync defaults (incremental where a tracking column exists,+ else append, else full_refresh — never CDC), sets `created_via=mcp`, and creates the source. The `payload` carries+ a credential reference (`{"credential_id": ...}` or the OAuth integration id key) — or inline credentials for+ headless automation; no `schemas` array is needed. On success you get the new source `id`; call+ `external-data-schemas-list` to show the user what was enabled and how each table will sync.++Notes specific to this path:++- **All discovered tables are enabled.** That's intended (incremental defaults keep ongoing cost low), but flag row+ counts for very large tables and offer the advanced flow if the user wants to sync only a subset.+- **Webhooks are auto-registered** for sources that support them (currently Stripe). Check the `webhook` key in the+ setup response: on success, webhook-capable tables sync in real time and webhook-only tables (e.g. Stripe Discount)+ are enabled too; on failure (e.g. the API key can't create webhooks), tables keep the polling defaults and+ webhook-only tables stay disabled — relay the `webhook.error` to the user and offer Step 6 to register manually.+ If `webhook.pending_inputs` is non-empty, collect those values and submit via+ `external-data-sources-update-webhook-inputs-create`. CDC is never chosen automatically; use the advanced flow ++ CDC steps for near-real-time Postgres.+- Inline credentials in `payload` still work for headless/automation, but prefer the connect-link handoff above.++## Advanced: hand-pick tables (three-step flow)++Use this when the user wants to choose exactly which tables sync or set non-default sync types. Don't try to shortcut+to `external-data-sources-create` — you need the db-schema response to build a valid `schemas` payload.```text┌────────────────────┐@@ -262,8 +310,11 @@ If the user wants near-real-time replication from Postgres:response. You can't "also add an orders table" unless db-schema found one.- **Prefix is load-bearing.** It's part of every HogQL query the user will ever write against these tables. Picksomething short, descriptive, and not already taken.-- **OAuth sources are different.** Hubspot, Salesforce, Google Ads etc. need the user to authorize via the PostHog- UI. Direct them there — don't try to collect OAuth tokens in chat.+- **Prefer the secure connect-link for any credentials.** Use `data-warehouse-source-connect-link` so the user+ authenticates in their browser — OAuth sources (Hubspot, Salesforce, Google Ads) authorize via PostHog, and+ credential sources (Postgres, Stripe key, …) enter secrets on the minimal connect page, which stores them without+ creating the source. Don't collect OAuth tokens or database passwords in chat; pass the integration id or+ `credential_id` reference to setup — source creation always happens through setup, not the UI.- **Webhooks are a separate step after create.** Setting `sync_type: "webhook"` on a schema doesn't register thewebhook — the `create-webhook` call does. Always follow create → create-webhook → webhook-info for webhook-typeschemas, and never leave a webhook schema dangling without registration (it just won't receive events).diff --git a/products/data_warehouse/skills/suggesting-data-imports/SKILL.md b/products/data_warehouse/skills/suggesting-data-imports/SKILL.mdindex c3a10f407d2c..7b6eb837803c 100644--- a/products/data_warehouse/skills/suggesting-data-imports/SKILL.md+++ b/products/data_warehouse/skills/suggesting-data-imports/SKILL.md@@ -69,9 +69,11 @@ Example: "Your Stripe data isn't in PostHog yet. If you connect a Stripe source,### 5. Offer to set up the source-If the user wants to proceed, hand off to the **`setting-up-a-data-warehouse-source`** skill — it covers the full-three-step flow (wizard → db-schema → create), sync-type selection, webhook registration, and prefix guidance.-Do not duplicate that workflow here.+If the user wants to proceed, the fastest path is the one-step `data-warehouse-source-setup` tool (validate creds →+discover tables → sync defaults → create, in one call), with `data-warehouse-source-connect-link` to collect+credentials securely in the browser rather than in chat. For anything beyond the happy path (hand-picking tables,+non-default sync types, webhooks, CDC), hand off to the **`setting-up-a-data-warehouse-source`** skill, which covers+the full flow, sync-type selection, webhook registration, and prefix guidance. Do not duplicate that workflow here.### 6. Show what's possible after import@@ -87,7 +89,7 @@ Common join patterns:- **Don't guess table names.** Always check `posthog:read-data-warehouse-schema` and `posthog:external-data-schemas-list` before saying data doesn't exist.- **Check prefixes.** Imported tables are often prefixed (e.g. `stripe_charges` not `charges`). The user might not know the prefix.-- **OAuth sources require the UI.** Some sources (Google Ads, Meta Ads, Hubspot with OAuth) require browser-based OAuth flows. You can't complete these via MCP — direct the user to the PostHog UI at `/data-warehouse/new`.+- **Collect credentials securely.** Use `data-warehouse-source-connect-link` to hand the user a browser link — OAuth sources (Google Ads, Meta Ads, Hubspot) authorize via PostHog, and credential sources enter secrets on a minimal connect page that stashes them temporarily without creating the source. Afterwards pass the integration id or `{"credential_id": <id>}` (discovered via `data-warehouse-stored-credentials-list`) to `data-warehouse-source-setup` — stored credentials are single-use and expire after 24 hours. Don't collect passwords or OAuth tokens in chat.- **Not all systems are supported.** If the user's system isn't in the wizard list, suggest using Postgres/MySQL as a bridge if they can export to a database, or mention that custom sources can be requested.## Related tools@@ -96,6 +98,8 @@ Common join patterns:- `posthog:external-data-schemas-list`: Check what tables are already imported- `posthog:read-data-warehouse-schema`: See all queryable tables including views- `posthog:external-data-sources-wizard`: Get available source types+- `posthog:data-warehouse-source-connect-link`: Get a secure browser/OAuth link to collect credentials+- `posthog:data-warehouse-source-setup`: One-step create (validate, discover tables, apply sync defaults, create)- `posthog:execute-sql`: Run queries to demonstrate what's possible## Related skillsdiff --git a/products/warehouse_sources/backend/migrations/0006_pending_source_credential.py b/products/warehouse_sources/backend/migrations/0006_pending_source_credential.pynew file mode 100644index 000000000000..3e1e9d5cd2cc--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0006_pending_source_credential.py@@ -0,0 +1,297 @@+# Generated by Django 5.2.14 on 2026-06-11 20:47++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+import posthog.helpers.encrypted_fields++import products.warehouse_sources.backend.models.pending_source_credential+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1218_team_ingested_production_event_last_checked_at"),+ ("warehouse_sources", "0005_alter_externaldatasource_source_type"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="PendingSourceCredential",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "source_type",+ models.CharField(+ choices=[+ ("Ashby", "Ashby"),+ ("Supabase", "Supabase"),+ ("CustomerIO", "CustomerIO"),+ ("Github", "Github"),+ ("Stripe", "Stripe"),+ ("Hubspot", "Hubspot"),+ ("Postgres", "Postgres"),+ ("Zendesk", "Zendesk"),+ ("Snowflake", "Snowflake"),+ ("Salesforce", "Salesforce"),+ ("MySQL", "MySQL"),+ ("MongoDB", "MongoDB"),+ ("MSSQL", "MSSQL"),+ ("Vitally", "Vitally"),+ ("BigQuery", "BigQuery"),+ ("Chargebee", "Chargebee"),+ ("Clerk", "Clerk"),+ ("GoogleAds", "GoogleAds"),+ ("GoogleSearchConsole", "GoogleSearchConsole"),+ ("TemporalIO", "TemporalIO"),+ ("DoIt", "DoIt"),+ ("GoogleSheets", "GoogleSheets"),+ ("MetaAds", "MetaAds"),+ ("Klaviyo", "Klaviyo"),+ ("Mailchimp", "Mailchimp"),+ ("Braze", "Braze"),+ ("Mailjet", "Mailjet"),+ ("Redshift", "Redshift"),+ ("Polar", "Polar"),+ ("RevenueCat", "RevenueCat"),+ ("LinkedinAds", "LinkedinAds"),+ ("RedditAds", "RedditAds"),+ ("TikTokAds", "TikTokAds"),+ ("BingAds", "BingAds"),+ ("Shopify", "Shopify"),+ ("Attio", "Attio"),+ ("SnapchatAds", "SnapchatAds"),+ ("Linear", "Linear"),+ ("Intercom", "Intercom"),+ ("Amplitude", "Amplitude"),+ ("Mixpanel", "Mixpanel"),+ ("Jira", "Jira"),+ ("ActiveCampaign", "ActiveCampaign"),+ ("Marketo", "Marketo"),+ ("Adjust", "Adjust"),+ ("AppsFlyer", "AppsFlyer"),+ ("Freshdesk", "Freshdesk"),+ ("GoogleAnalytics", "GoogleAnalytics"),+ ("Pipedrive", "Pipedrive"),+ ("SendGrid", "SendGrid"),+ ("Slack", "Slack"),+ ("PagerDuty", "PagerDuty"),+ ("Asana", "Asana"),+ ("Notion", "Notion"),+ ("Airtable", "Airtable"),+ ("Greenhouse", "Greenhouse"),+ ("BambooHR", "BambooHR"),+ ("Lever", "Lever"),+ ("GitLab", "GitLab"),+ ("Datadog", "Datadog"),+ ("Sentry", "Sentry"),+ ("Pendo", "Pendo"),+ ("FullStory", "FullStory"),+ ("AmazonAds", "AmazonAds"),+ ("PinterestAds", "PinterestAds"),+ ("AppleSearchAds", "AppleSearchAds"),+ ("QuickBooks", "QuickBooks"),+ ("Xero", "Xero"),+ ("NetSuite", "NetSuite"),+ ("WooCommerce", "WooCommerce"),+ ("BigCommerce", "BigCommerce"),+ ("PayPal", "PayPal"),+ ("Square", "Square"),+ ("Zoom", "Zoom"),+ ("Trello", "Trello"),+ ("Monday", "Monday"),+ ("ClickUp", "ClickUp"),+ ("Confluence", "Confluence"),+ ("Recurly", "Recurly"),+ ("SalesLoft", "SalesLoft"),+ ("Outreach", "Outreach"),+ ("Gong", "Gong"),+ ("Calendly", "Calendly"),+ ("Typeform", "Typeform"),+ ("Iterable", "Iterable"),+ ("ZohoCRM", "ZohoCRM"),+ ("Close", "Close"),+ ("Oracle", "Oracle"),+ ("DynamoDB", "DynamoDB"),+ ("Elasticsearch", "Elasticsearch"),+ ("Kafka", "Kafka"),+ ("LaunchDarkly", "LaunchDarkly"),+ ("Braintree", "Braintree"),+ ("Recharge", "Recharge"),+ ("HelpScout", "HelpScout"),+ ("Gorgias", "Gorgias"),+ ("Instagram", "Instagram"),+ ("YouTubeAnalytics", "YouTubeAnalytics"),+ ("FacebookPages", "FacebookPages"),+ ("TwitterAds", "TwitterAds"),+ ("Workday", "Workday"),+ ("ServiceNow", "ServiceNow"),+ ("Pardot", "Pardot"),+ ("Copper", "Copper"),+ ("Front", "Front"),+ ("ChartMogul", "ChartMogul"),+ ("Zuora", "Zuora"),+ ("Paddle", "Paddle"),+ ("CircleCI", "CircleCI"),+ ("CockroachDB", "CockroachDB"),+ ("Firebase", "Firebase"),+ ("AzureBlob", "AzureBlob"),+ ("GoogleDrive", "GoogleDrive"),+ ("OneDrive", "OneDrive"),+ ("SharePoint", "SharePoint"),+ ("Box", "Box"),+ ("SFTP", "SFTP"),+ ("MicrosoftTeams", "MicrosoftTeams"),+ ("Aircall", "Aircall"),+ ("Webflow", "Webflow"),+ ("Okta", "Okta"),+ ("Auth0", "Auth0"),+ ("Productboard", "Productboard"),+ ("Smartsheet", "Smartsheet"),+ ("Wrike", "Wrike"),+ ("Plaid", "Plaid"),+ ("SurveyMonkey", "SurveyMonkey"),+ ("Eventbrite", "Eventbrite"),+ ("RingCentral", "RingCentral"),+ ("Twilio", "Twilio"),+ ("Freshsales", "Freshsales"),+ ("Shortcut", "Shortcut"),+ ("ConvertKit", "ConvertKit"),+ ("Drip", "Drip"),+ ("CampaignMonitor", "CampaignMonitor"),+ ("MailerLite", "MailerLite"),+ ("Omnisend", "Omnisend"),+ ("Brevo", "Brevo"),+ ("Postmark", "Postmark"),+ ("Granola", "Granola"),+ ("BuildBetter", "BuildBetter"),+ ("Convex", "Convex"),+ ("ClickHouse", "ClickHouse"),+ ("Plain", "Plain"),+ ("Resend", "Resend"),+ ("PgAnalyze", "PgAnalyze"),+ ("WorkOS", "WorkOS"),+ ("AmazonS3", "AmazonS3"),+ ("GoogleCloudStorage", "GoogleCloudStorage"),+ ("Databricks", "Databricks"),+ ("Dynamics365", "Dynamics365"),+ ("SalesforceMarketingCloud", "SalesforceMarketingCloud"),+ ("Db2", "Db2"),+ ("Heap", "Heap"),+ ("AdobeAnalytics", "AdobeAnalytics"),+ ("Matomo", "Matomo"),+ ("Optimizely", "Optimizely"),+ ("Adyen", "Adyen"),+ ("GoCardless", "GoCardless"),+ ("Mollie", "Mollie"),+ ("CheckoutCom", "CheckoutCom"),+ ("Branch", "Branch"),+ ("Criteo", "Criteo"),+ ("Outbrain", "Outbrain"),+ ("Taboola", "Taboola"),+ ("AdRoll", "AdRoll"),+ ("DisplayVideo360", "DisplayVideo360"),+ ("GoogleAdManager", "GoogleAdManager"),+ ("CampaignManager360", "CampaignManager360"),+ ("SearchAds360", "SearchAds360"),+ ("AdobeCommerce", "AdobeCommerce"),+ ("AmazonSellingPartner", "AmazonSellingPartner"),+ ("Ebay", "Ebay"),+ ("Commercetools", "Commercetools"),+ ("LightspeedRetail", "LightspeedRetail"),+ ("ShipStation", "ShipStation"),+ ("ConstantContact", "ConstantContact"),+ ("Mailgun", "Mailgun"),+ ("Eloqua", "Eloqua"),+ ("Sailthru", "Sailthru"),+ ("Ortto", "Ortto"),+ ("Attentive", "Attentive"),+ ("Kustomer", "Kustomer"),+ ("Dixa", "Dixa"),+ ("Gladly", "Gladly"),+ ("Qualtrics", "Qualtrics"),+ ("Delighted", "Delighted"),+ ("AzureDevOps", "AzureDevOps"),+ ("Rollbar", "Rollbar"),+ ("Opsgenie", "Opsgenie"),+ ("IncidentIo", "IncidentIo"),+ ("Pingdom", "Pingdom"),+ ("Cloudflare", "Cloudflare"),+ ("CosmosDB", "CosmosDB"),+ ("PlanetScale", "PlanetScale"),+ ("SapHana", "SapHana"),+ ("Rippling", "Rippling"),+ ("HiBob", "HiBob"),+ ("Personio", "Personio"),+ ("Deel", "Deel"),+ ("AdpWorkforceNow", "AdpWorkforceNow"),+ ("Paylocity", "Paylocity"),+ ("Gusto", "Gusto"),+ ("CultureAmp", "CultureAmp"),+ ("Lattice", "Lattice"),+ ("SageIntacct", "SageIntacct"),+ ("FreshBooks", "FreshBooks"),+ ("Expensify", "Expensify"),+ ("Ramp", "Ramp"),+ ("Brex", "Brex"),+ ("Coupa", "Coupa"),+ ("SapConcur", "SapConcur"),+ ("Apollo", "Apollo"),+ ("Crunchbase", "Crunchbase"),+ ("ZoomInfo", "ZoomInfo"),+ ("Clari", "Clari"),+ ("Chorus", "Chorus"),+ ("Coda", "Coda"),+ ("Guru", "Guru"),+ ("Dropbox", "Dropbox"),+ ("Docusign", "Docusign"),+ ("PandaDoc", "PandaDoc"),+ ("SapErp", "SapErp"),+ ("SapSuccessFactors", "SapSuccessFactors"),+ ("OracleEbs", "OracleEbs"),+ ("OracleFusion", "OracleFusion"),+ ("Custom", "Custom"),+ ],+ max_length=128,+ ),+ ),+ (+ "payload",+ posthog.helpers.encrypted_fields.EncryptedJSONField(default=dict),+ ),+ (+ "expires_at",+ models.DateTimeField(+ default=products.warehouse_sources.backend.models.pending_source_credential.pending_credential_default_expiry+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "abstract": False,+ },+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 880a55d0fb25..de63ddbbce46 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_alter_externaldatasource_source_type+0006_pending_source_credentialdiff --git a/products/warehouse_sources/backend/models/__init__.py b/products/warehouse_sources/backend/models/__init__.pyindex fc7688a62434..2942c480799f 100644--- a/products/warehouse_sources/backend/models/__init__.py+++ b/products/warehouse_sources/backend/models/__init__.py@@ -2,6 +2,7 @@ from .credential import DataWarehouseCredentialfrom .external_data_job import ExternalDataJobfrom .external_data_schema import ExternalDataSchemafrom .external_data_source import ExternalDataSource+from .pending_source_credential import PendingSourceCredentialfrom .table import DataWarehouseTable__all__ = [@@ -10,4 +11,5 @@ __all__ = ["ExternalDataJob","ExternalDataSchema","ExternalDataSource",+ "PendingSourceCredential",]diff --git a/products/warehouse_sources/backend/models/pending_source_credential.py b/products/warehouse_sources/backend/models/pending_source_credential.pynew file mode 100644index 000000000000..b714de00ce9a--- /dev/null+++ b/products/warehouse_sources/backend/models/pending_source_credential.py@@ -0,0 +1,32 @@+from datetime import datetime, timedelta++from django.db import models+from django.utils import timezone++from posthog.helpers.encrypted_fields import EncryptedJSONField+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import CreatedMetaFields, UUIDTModel, sane_repr++from products.data_warehouse.backend.types import ExternalDataSourceType++PENDING_CREDENTIAL_TTL = timedelta(hours=24)+++def pending_credential_default_expiry() -> datetime:+ return timezone.now() + PENDING_CREDENTIAL_TTL+++class PendingSourceCredential(TeamScopedRootMixin, CreatedMetaFields, UUIDTModel):+ """Temporary stash for source credentials collected via the source connect page.++ Credentials are validated against a live connection, stored encrypted, and referenced by id when+ creating the source (so secrets never pass through an agent conversation). Rows are deleted as+ soon as the source is created, and ignored/purged after `expires_at` if never consumed.+ """++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ source_type = models.CharField(max_length=128, choices=ExternalDataSourceType)+ payload = EncryptedJSONField(default=dict)+ expires_at = models.DateTimeField(default=pending_credential_default_expiry)++ __repr__ = sane_repr("id", "team_id", "source_type")diff --git a/services/mcp/definitions/data_warehouse.yaml b/services/mcp/definitions/data_warehouse.yamlindex 2e42fc921497..c0e056bdd5fe 100644--- a/services/mcp/definitions/data_warehouse.yaml+++ b/services/mcp/definitions/data_warehouse.yaml@@ -102,6 +102,9 @@ tools:external-data-sources-check-cdc-prerequisites-for-source-create:operation: external_data_sources_check_cdc_prerequisites_for_source_createenabled: false+ external-data-sources-connect-link-retrieve:+ operation: external_data_sources_connect_link_retrieve+ enabled: falseexternal-data-sources-connections-list:operation: external_data_sources_connections_listenabled: false@@ -147,9 +150,18 @@ tools:external-data-sources-revenue-analytics-config-partial-update:operation: external_data_sources_revenue_analytics_config_partial_updateenabled: false+ external-data-sources-setup-create:+ operation: external_data_sources_setup_create+ enabled: falseexternal-data-sources-source-prefix-create:operation: external_data_sources_source_prefix_createenabled: false+ external-data-sources-store-credentials-create:+ operation: external_data_sources_store_credentials_create+ enabled: false+ external-data-sources-stored-credentials-list:+ operation: external_data_sources_stored_credentials_list+ enabled: falseexternal-data-sources-update:operation: external_data_sources_updateenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 44b09bf98a88..91029f633ca1 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1325,6 +1325,48 @@"readOnlyHint": true}},+ "data-warehouse-source-connect-link": {+ "description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. For OAuth sources (Hubspot, Salesforce, Google Ads, …) it returns an authorization URL; for credential sources (Postgres, MySQL, Stripe API key, …) it links to a minimal page where the user enters only their credentials — the page stores them encrypted and temporarily, and does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored reference (OAuth: 'integrations-list' filtered by the source's kind; credentials: 'data-warehouse-stored-credentials-list' filtered by source_type) and call 'data-warehouse-source-setup' with the returned integration_field key (e.g. {'hubspot_integration_id': 123} or {'credential_id': '<uuid>'}). Stored credentials are single-use and expire after 24 hours. Never ask the user to paste raw database passwords or API keys into the chat.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Get a secure connect link for a source",+ "title": "Get a secure connect link for a source",+ "required_scopes": ["external_data_source:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "data-warehouse-source-setup": {+ "description": "Connect an external data source and start importing it into queryable warehouse tables in a single call. Validates credentials, discovers all available tables, enables them with sensible sync defaults (incremental where supported to keep ongoing cost low), and creates the source — no 'schemas' array required. For webhook-capable sources (e.g. Stripe) a webhook is auto-registered after creation: check the 'webhook' key in the response — on success webhook-capable tables sync in real time (including webhook-only tables like Stripe Discount); on failure (e.g. the API key can't create webhooks) tables keep the polling defaults and webhook-only tables stay disabled. If 'webhook.pending_inputs' is non-empty, ask the user for those values and submit them via 'external-data-sources-update-webhook-inputs-create'. Use this for revenue (Stripe), CRM (Hubspot, Salesforce), support tickets (Zendesk), e-commerce (Shopify), and your own databases (Postgres, MySQL, BigQuery, Snowflake). Discover required credential fields per source_type with 'external-data-sources-wizard'. Prefer references over raw secrets in the payload: for OAuth sources pass the integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': '<uuid>'} referencing credentials the user stored via the 'data-warehouse-source-connect-link' page (discover ids with 'data-warehouse-stored-credentials-list'). Stored credentials are deleted once the source is created. For fine-grained per-table control, use 'external-data-sources-create' instead.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Set up a data warehouse source (one step)",+ "title": "Set up a data warehouse source (one step)",+ "required_scopes": ["external_data_source:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "data-warehouse-stored-credentials-list": {+ "description": "List credentials the user stored via the 'data-warehouse-source-connect-link' page that haven't been consumed yet. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as setup consumes them — and expire after 24 hours if never used.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "List stored source credentials awaiting setup",+ "title": "List stored source credentials awaiting setup",+ "required_scopes": ["external_data_source:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"delete-feature-flag": {"description": "Soft-delete a feature flag by ID in the current project.","category": "Feature flags",@@ -2211,8 +2253,8 @@"description": "List all table schemas across all data warehouse sources. Each schema represents one table being synced from an 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.","category": "Data warehouse","feature": "data_warehouse",- "summary": "List data import schemas",- "title": "List data import schemas",+ "summary": "List data warehouse table schemas (imported tables)",+ "title": "List data warehouse table schemas (imported tables)","required_scopes": ["external_data_source:read"],"annotations": {"destructiveHint": false,@@ -2225,8 +2267,8 @@"description": "Update a table schema's sync configuration. Can change sync type, sync frequency, incremental field, primary key columns, CDC table mode, and enable/disable the schema.","category": "Data warehouse","feature": "data_warehouse",- "summary": "Update data import schema",- "title": "Update data import schema",+ "summary": "Update data warehouse table schema sync config",+ "title": "Update data warehouse table schema sync config","required_scopes": ["external_data_source:write"],"annotations": {"destructiveHint": false,@@ -2267,8 +2309,8 @@"description": "Get a single table schema by ID. Returns full details including sync status, sync frequency, incremental field, latest error, and the associated source and table metadata.","category": "Data warehouse","feature": "data_warehouse",- "summary": "Get data import schema",- "title": "Get data import schema",+ "summary": "Get data warehouse table schema",+ "title": "Get data warehouse table schema","required_scopes": ["external_data_source:read"],"annotations": {"destructiveHint": false,@@ -2306,11 +2348,11 @@}},"external-data-sources-create": {- "description": "Create a new external data source connection. Before calling this, use 'external-data-sources-wizard' to discover source types and 'external-data-sources-db-schema' to validate credentials and discover available tables. Present the db-schema results to the user showing each table's available sync methods, incremental fields, detected primary keys, and columns so they can configure before creation. The payload must include a 'schemas' array where each entry has: name, should_sync (bool), sync_type (incremental/full_refresh/append), and optionally incremental_field, incremental_field_type, and primary_key_columns from the db-schema response.",+ "description": "Low-level create for a data warehouse import source when you need to hand-pick tables and sync types. For most cases prefer 'data-warehouse-source-setup', which validates credentials, discovers tables, applies sensible sync defaults, and creates the source in one call. Use this advanced path only for fine-grained control. The payload must include a 'schemas' array where each entry has: name, should_sync (bool), sync_type (incremental/full_refresh/append), and optionally incremental_field, incremental_field_type, and primary_key_columns. Discover tables and their available sync methods with 'external-data-sources-wizard' (source types and required fields) first. Sources back queryable warehouse tables for revenue (Stripe), CRM (Hubspot, Salesforce), support (Zendesk), and your own databases (Postgres, MySQL, BigQuery).","category": "Data warehouse","feature": "data_warehouse",- "summary": "Create data warehouse source",- "title": "Create data warehouse source",+ "summary": "Create data warehouse source (advanced; prefer source setup)",+ "title": "Create data warehouse source (advanced; prefer source setup)","required_scopes": ["external_data_source:write"],"annotations": {"destructiveHint": false,@@ -2376,7 +2418,7 @@}},"external-data-sources-partial-update": {- "description": "Update an existing data warehouse source. Can change the prefix (table name prefix in HogQL), description, or connection credentials via job_inputs. Cannot change the source_type or access_method after creation.",+ "description": "Update an existing data warehouse source's prefix (table name prefix in HogQL) or description. Cannot change the source_type or access_method after creation. Avoid sending new connection credentials inline here — to rotate or fix credentials, point the user at 'data-warehouse-source-connect-link' so they re-enter them securely in their browser rather than pasting secrets into the chat.","category": "Data warehouse","feature": "data_warehouse","summary": "Update data warehouse source",@@ -2460,11 +2502,11 @@}},"external-data-sources-wizard": {- "description": "Return the configuration metadata for all supported data warehouse source types. Each entry describes the required fields (host, port, database, credentials, etc.), field types, and OAuth flows. Use this to discover what source types are available and what parameters are needed to create a new source.",+ "description": "Return the configuration metadata for all supported data warehouse source types you can import data from — revenue/payments (Stripe, Chargebee), CRM (Hubspot, Salesforce), support tickets (Zendesk), product databases (Postgres, MySQL, BigQuery, Snowflake), ads, and more. Each entry describes the required fields (host, port, database, credentials, etc.), field types, and OAuth flows. Use this to discover what external data can be imported into queryable warehouse tables and what parameters a source needs. To actually connect a source, prefer 'data-warehouse-source-setup'.","category": "Data warehouse","feature": "data_warehouse",- "summary": "Get source type configurations",- "title": "Get source type configurations",+ "summary": "List data warehouse source types you can import",+ "title": "List data warehouse source types you can import","required_scopes": ["external_data_source:read"],"annotations": {"destructiveHint": false,diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex e06bf798db54..6601ea38e6c4 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1341,6 +1341,48 @@"readOnlyHint": true}},+ "data-warehouse-source-connect-link": {+ "description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. For OAuth sources (Hubspot, Salesforce, Google Ads, …) it returns an authorization URL; for credential sources (Postgres, MySQL, Stripe API key, …) it links to a minimal page where the user enters only their credentials — the page stores them encrypted and temporarily, and does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored reference (OAuth: 'integrations-list' filtered by the source's kind; credentials: 'data-warehouse-stored-credentials-list' filtered by source_type) and call 'data-warehouse-source-setup' with the returned integration_field key (e.g. {'hubspot_integration_id': 123} or {'credential_id': '<uuid>'}). Stored credentials are single-use and expire after 24 hours. Never ask the user to paste raw database passwords or API keys into the chat.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Get a secure connect link for a source",+ "title": "Get a secure connect link for a source",+ "required_scopes": ["external_data_source:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "data-warehouse-source-setup": {+ "description": "Connect an external data source and start importing it into queryable warehouse tables in a single call. Validates credentials, discovers all available tables, enables them with sensible sync defaults (incremental where supported to keep ongoing cost low), and creates the source — no 'schemas' array required. For webhook-capable sources (e.g. Stripe) a webhook is auto-registered after creation: check the 'webhook' key in the response — on success webhook-capable tables sync in real time (including webhook-only tables like Stripe Discount); on failure (e.g. the API key can't create webhooks) tables keep the polling defaults and webhook-only tables stay disabled. If 'webhook.pending_inputs' is non-empty, ask the user for those values and submit them via 'external-data-sources-update-webhook-inputs-create'. Use this for revenue (Stripe), CRM (Hubspot, Salesforce), support tickets (Zendesk), e-commerce (Shopify), and your own databases (Postgres, MySQL, BigQuery, Snowflake). Discover required credential fields per source_type with 'external-data-sources-wizard'. Prefer references over raw secrets in the payload: for OAuth sources pass the integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': '<uuid>'} referencing credentials the user stored via the 'data-warehouse-source-connect-link' page (discover ids with 'data-warehouse-stored-credentials-list'). Stored credentials are deleted once the source is created. For fine-grained per-table control, use 'external-data-sources-create' instead.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Set up a data warehouse source (one step)",+ "title": "Set up a data warehouse source (one step)",+ "required_scopes": ["external_data_source:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "data-warehouse-stored-credentials-list": {+ "description": "List credentials the user stored via the 'data-warehouse-source-connect-link' page that haven't been consumed yet. Returns metadata only (credential_id, source_type, created_at, expires_at) — never the secrets themselves. Newest first; filter by source_type. After the user confirms they've finished the connect page, take the newest credential_id for the source type and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use — they are deleted as soon as setup consumes them — and expire after 24 hours if never used.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "List stored source credentials awaiting setup",+ "title": "List stored source credentials awaiting setup",+ "required_scopes": ["external_data_source:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"debug-mcp-ui-apps": {"description": "Debug tool for testing MCP Apps SDK integration. Returns sample data displayed in an interactive UI app with component showcase. Use this to verify that MCP Apps are working correctly.","category": "Debug",@@ -2395,8 +2437,8 @@"description": "List all table schemas across all data warehouse sources. Each schema represents one table being synced from an 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.","category": "Data warehouse","feature": "data_warehouse",- "summary": "List data import schemas",- "title": "List data import schemas",+ "summary": "List data warehouse table schemas (imported tables)",+ "title": "List data warehouse table schemas (imported tables)","required_scopes": ["external_data_source:read"],"annotations": {"destructiveHint": false,@@ -2409,8 +2451,8 @@"description": "Update a table schema's sync configuration. Can change sync type, sync frequency, incremental field, primary key columns, CDC table mode, and enable/disable the schema.","category": "Data warehouse","feature": "data_warehouse",- "summary": "Update data import schema",- "title": "Update data import schema",+ "summary": "Update data warehouse table schema sync config",+ "title": "Update data warehouse table schema sync config","required_scopes": ["external_data_source:write"],"annotations": {"destructiveHint": false,@@ -2451,8 +2493,8 @@"description": "Get a single table schema by ID. Returns full details including sync status, sync frequency, incremental field, latest error, and the associated source and table metadata.","category": "Data warehouse","feature": "data_warehouse",- "summary": "Get data import schema",- "title": "Get data import schema",+ "summary": "Get data warehouse table schema",+ "title": "Get data warehouse table schema","required_scopes": ["external_data_source:read"],"annotations": {"destructiveHint": false,@@ -2490,11 +2532,11 @@}},"external-data-sources-create": {- "description": "Create a new external data source connection. Before calling this, use 'external-data-sources-wizard' to discover source types and 'external-data-sources-db-schema' to validate credentials and discover available tables. Present the db-schema results to the user showing each table's available sync methods, incremental fields, detected primary keys, and columns so they can configure before creation. The payload must include a 'schemas' array where each entry has: name, should_sync (bool), sync_type (incremental/full_refresh/append), and optionally incremental_field, incremental_field_type, and primary_key_columns from the db-schema response.",+ "description": "Low-level create for a data warehouse import source when you need to hand-pick tables and sync types. For most cases prefer 'data-warehouse-source-setup', which validates credentials, discovers tables, applies sensible sync defaults, and creates the source in one call. Use this advanced path only for fine-grained control. The payload must include a 'schemas' array where each entry has: name, should_sync (bool), sync_type (incremental/full_refresh/append), and optionally incremental_field, incremental_field_type, and primary_key_columns. Discover tables and their available sync methods with 'external-data-sources-wizard' (source types and required fields) first. Sources back queryable warehouse tables for revenue (Stripe), CRM (Hubspot, Salesforce), support (Zendesk), and your own databases (Postgres, MySQL, BigQuery).","category": "Data warehouse","feature": "data_warehouse",- "summary": "Create data warehouse source",- "title": "Create data warehouse source",+ "summary": "Create data warehouse source (advanced; prefer source setup)",+ "title": "Create data warehouse source (advanced; prefer source setup)","required_scopes": ["external_data_source:write"],"annotations": {"destructiveHint": false,@@ -2588,7 +2630,7 @@}},"external-data-sources-partial-update": {- "description": "Update an existing data warehouse source. Can change the prefix (table name prefix in HogQL), description, or connection credentials via job_inputs. Cannot change the source_type or access_method after creation.",+ "description": "Update an existing data warehouse source's prefix (table name prefix in HogQL) or description. Cannot change the source_type or access_method after creation. Avoid sending new connection credentials inline here — to rotate or fix credentials, point the user at 'data-warehouse-source-connect-link' so they re-enter them securely in their browser rather than pasting secrets into the chat.","category": "Data warehouse","feature": "data_warehouse","summary": "Update data warehouse source",@@ -2672,11 +2714,11 @@}},"external-data-sources-wizard": {- "description": "Return the configuration metadata for all supported data warehouse source types. Each entry describes the required fields (host, port, database, credentials, etc.), field types, and OAuth flows. Use this to discover what source types are available and what parameters are needed to create a new source.",+ "description": "Return the configuration metadata for all supported data warehouse source types you can import data from — revenue/payments (Stripe, Chargebee), CRM (Hubspot, Salesforce), support tickets (Zendesk), product databases (Postgres, MySQL, BigQuery, Snowflake), ads, and more. Each entry describes the required fields (host, port, database, credentials, etc.), field types, and OAuth flows. Use this to discover what external data can be imported into queryable warehouse tables and what parameters a source needs. To actually connect a source, prefer 'data-warehouse-source-setup'.","category": "Data warehouse","feature": "data_warehouse",- "summary": "Get source type configurations",- "title": "Get source type configurations",+ "summary": "List data warehouse source types you can import",+ "title": "List data warehouse source types you can import","required_scopes": ["external_data_source:read"],"annotations": {"destructiveHint": false,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7e709b1258cf..b31d3cf85ae9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7893,6 +7893,18 @@ export namespace Schemas {PositionBased: 'position_based',} as const;+ /**+ * * `oauth` - oauth+ * * `credentials` - credentials+ */+ export type AuthMethodEnum = typeof AuthMethodEnum[keyof typeof AuthMethodEnum];+++ export const AuthMethodEnum = {+ Oauth: 'oauth',+ Credentials: 'credentials',+ } as const;+export interface Author {/** Login handle of the pull request author. */handle: string;@@ -40531,6 +40543,276 @@ export namespace Schemas {runs: SlackThreadContextRun[];}+ export interface SourceConnectLink {+ /** The source type the link is for. */+ source_type: string;+ /** 'oauth' = the user authorizes in their browser; 'credentials' = the user enters credentials in the PostHog UI. Either way secrets never pass through the agent.+ *+ * * `oauth` - oauth+ * * `credentials` - credentials */+ auth_method: AuthMethodEnum;+ /** Full URL to share with the user. They open it in a browser to authorize or enter credentials directly in PostHog — credentials never pass through the agent or the chat. */+ connect_url: string;+ /**+ * The payload key to pass to data-warehouse-source-setup: for OAuth sources, the source's integration id key (e.g. 'hubspot_integration_id'); for credential sources, 'credential_id' referencing the credentials the user stored via the connect page.+ * @nullable+ */+ integration_field: string | null;+ /** Next steps for the agent to relay to the user. */+ instructions: string;+ }++ export interface SourceCredential {+ /** Stored credential id. Pass to the setup endpoint as {'credential_id': <id>} to create the source. */+ credential_id: string;+ /** The source type the stored credentials are for. */+ source_type: string;+ /** When the credentials were stored. */+ created_at: string;+ /** When the stored credentials expire. Unconsumed credentials are unusable past this time. */+ expires_at: string;+ }++ /**+ * Connection details as flat keys for the source_type — the same fields the create flow accepts (host, port, password, API key, …). Checked against a live connection before being stored.+ */+ export type SourceCredentialCreatePayload = { [key: string]: unknown };++ export interface SourceCredentialCreate {+ /** The source type these credentials are for (e.g. 'Stripe', 'Postgres').+ *+ * * `Ashby` - Ashby+ * * `Supabase` - Supabase+ * * `CustomerIO` - CustomerIO+ * * `Github` - Github+ * * `Stripe` - Stripe+ * * `Hubspot` - Hubspot+ * * `Postgres` - Postgres+ * * `Zendesk` - Zendesk+ * * `Snowflake` - Snowflake+ * * `Salesforce` - Salesforce+ * * `MySQL` - MySQL+ * * `MongoDB` - MongoDB+ * * `MSSQL` - MSSQL+ * * `Vitally` - Vitally+ * * `BigQuery` - BigQuery+ * * `Chargebee` - Chargebee+ * * `Clerk` - Clerk+ * * `GoogleAds` - GoogleAds+ * * `GoogleSearchConsole` - GoogleSearchConsole+ * * `TemporalIO` - TemporalIO+ * * `DoIt` - DoIt+ * * `GoogleSheets` - GoogleSheets+ * * `MetaAds` - MetaAds+ * * `Klaviyo` - Klaviyo+ * * `Mailchimp` - Mailchimp+ * * `Braze` - Braze+ * * `Mailjet` - Mailjet+ * * `Redshift` - Redshift+ * * `Polar` - Polar+ * * `RevenueCat` - RevenueCat+ * * `LinkedinAds` - LinkedinAds+ * * `RedditAds` - RedditAds+ * * `TikTokAds` - TikTokAds+ * * `BingAds` - BingAds+ * * `Shopify` - Shopify+ * * `Attio` - Attio+ * * `SnapchatAds` - SnapchatAds+ * * `Linear` - Linear+ * * `Intercom` - Intercom+ * * `Amplitude` - Amplitude+ * * `Mixpanel` - Mixpanel+ * * `Jira` - Jira+ * * `ActiveCampaign` - ActiveCampaign+ * * `Marketo` - Marketo+ * * `Adjust` - Adjust+ * * `AppsFlyer` - AppsFlyer+ * * `Freshdesk` - Freshdesk+ * * `GoogleAnalytics` - GoogleAnalytics+ * * `Pipedrive` - Pipedrive+ * * `SendGrid` - SendGrid+ * * `Slack` - Slack+ * * `PagerDuty` - PagerDuty+ * * `Asana` - Asana+ * * `Notion` - Notion+ * * `Airtable` - Airtable+ * * `Greenhouse` - Greenhouse+ * * `BambooHR` - BambooHR+ * * `Lever` - Lever+ * * `GitLab` - GitLab+ * * `Datadog` - Datadog+ * * `Sentry` - Sentry+ * * `Pendo` - Pendo+ * * `FullStory` - FullStory+ * * `AmazonAds` - AmazonAds+ * * `PinterestAds` - PinterestAds+ * * `AppleSearchAds` - AppleSearchAds+ * * `QuickBooks` - QuickBooks+ * * `Xero` - Xero+ * * `NetSuite` - NetSuite+ * * `WooCommerce` - WooCommerce+ * * `BigCommerce` - BigCommerce+ * * `PayPal` - PayPal+ * * `Square` - Square+ * * `Zoom` - Zoom+ * * `Trello` - Trello+ * * `Monday` - Monday+ * * `ClickUp` - ClickUp+ * * `Confluence` - Confluence+ * * `Recurly` - Recurly+ * * `SalesLoft` - SalesLoft+ * * `Outreach` - Outreach+ * * `Gong` - Gong+ * * `Calendly` - Calendly+ * * `Typeform` - Typeform+ * * `Iterable` - Iterable+ * * `ZohoCRM` - ZohoCRM+ * * `Close` - Close+ * * `Oracle` - Oracle+ * * `DynamoDB` - DynamoDB+ * * `Elasticsearch` - Elasticsearch+ * * `Kafka` - Kafka+ * * `LaunchDarkly` - LaunchDarkly+ * * `Braintree` - Braintree+ * * `Recharge` - Recharge+ * * `HelpScout` - HelpScout+ * * `Gorgias` - Gorgias+ * * `Instagram` - Instagram+ * * `YouTubeAnalytics` - YouTubeAnalytics+ * * `FacebookPages` - FacebookPages+ * * `TwitterAds` - TwitterAds+ * * `Workday` - Workday+ * * `ServiceNow` - ServiceNow+ * * `Pardot` - Pardot+ * * `Copper` - Copper+ * * `Front` - Front+ * * `ChartMogul` - ChartMogul+ * * `Zuora` - Zuora+ * * `Paddle` - Paddle+ * * `CircleCI` - CircleCI+ * * `CockroachDB` - CockroachDB+ * * `Firebase` - Firebase+ * * `AzureBlob` - AzureBlob+ * * `GoogleDrive` - GoogleDrive+ * * `OneDrive` - OneDrive+ * * `SharePoint` - SharePoint+ * * `Box` - Box+ * * `SFTP` - SFTP+ * * `MicrosoftTeams` - MicrosoftTeams+ * * `Aircall` - Aircall+ * * `Webflow` - Webflow+ * * `Okta` - Okta+ * * `Auth0` - Auth0+ * * `Productboard` - Productboard+ * * `Smartsheet` - Smartsheet+ * * `Wrike` - Wrike+ * * `Plaid` - Plaid+ * * `SurveyMonkey` - SurveyMonkey+ * * `Eventbrite` - Eventbrite+ * * `RingCentral` - RingCentral+ * * `Twilio` - Twilio+ * * `Freshsales` - Freshsales+ * * `Shortcut` - Shortcut+ * * `ConvertKit` - ConvertKit+ * * `Drip` - Drip+ * * `CampaignMonitor` - CampaignMonitor+ * * `MailerLite` - MailerLite+ * * `Omnisend` - Omnisend+ * * `Brevo` - Brevo+ * * `Postmark` - Postmark+ * * `Granola` - Granola+ * * `BuildBetter` - BuildBetter+ * * `Convex` - Convex+ * * `ClickHouse` - ClickHouse+ * * `Plain` - Plain+ * * `Resend` - Resend+ * * `PgAnalyze` - PgAnalyze+ * * `WorkOS` - WorkOS+ * * `AmazonS3` - AmazonS3+ * * `GoogleCloudStorage` - GoogleCloudStorage+ * * `Databricks` - Databricks+ * * `Dynamics365` - Dynamics365+ * * `SalesforceMarketingCloud` - SalesforceMarketingCloud+ * * `Db2` - Db2+ * * `Heap` - Heap+ * * `AdobeAnalytics` - AdobeAnalytics+ * * `Matomo` - Matomo+ * * `Optimizely` - Optimizely+ * * `Adyen` - Adyen+ * * `GoCardless` - GoCardless+ * * `Mollie` - Mollie+ * * `CheckoutCom` - CheckoutCom+ * * `Branch` - Branch+ * * `Criteo` - Criteo+ * * `Outbrain` - Outbrain+ * * `Taboola` - Taboola+ * * `AdRoll` - AdRoll+ * * `DisplayVideo360` - DisplayVideo360+ * * `GoogleAdManager` - GoogleAdManager+ * * `CampaignManager360` - CampaignManager360+ * * `SearchAds360` - SearchAds360+ * * `AdobeCommerce` - AdobeCommerce+ * * `AmazonSellingPartner` - AmazonSellingPartner+ * * `Ebay` - Ebay+ * * `Commercetools` - Commercetools+ * * `LightspeedRetail` - LightspeedRetail+ * * `ShipStation` - ShipStation+ * * `ConstantContact` - ConstantContact+ * * `Mailgun` - Mailgun+ * * `Eloqua` - Eloqua+ * * `Sailthru` - Sailthru+ * * `Ortto` - Ortto+ * * `Attentive` - Attentive+ * * `Kustomer` - Kustomer+ * * `Dixa` - Dixa+ * * `Gladly` - Gladly+ * * `Qualtrics` - Qualtrics+ * * `Delighted` - Delighted+ * * `AzureDevOps` - AzureDevOps+ * * `Rollbar` - Rollbar+ * * `Opsgenie` - Opsgenie+ * * `IncidentIo` - IncidentIo+ * * `Pingdom` - Pingdom+ * * `Cloudflare` - Cloudflare+ * * `CosmosDB` - CosmosDB+ * * `PlanetScale` - PlanetScale+ * * `SapHana` - SapHana+ * * `Rippling` - Rippling+ * * `HiBob` - HiBob+ * * `Personio` - Personio+ * * `Deel` - Deel+ * * `AdpWorkforceNow` - AdpWorkforceNow+ * * `Paylocity` - Paylocity+ * * `Gusto` - Gusto+ * * `CultureAmp` - CultureAmp+ * * `Lattice` - Lattice+ * * `SageIntacct` - SageIntacct+ * * `FreshBooks` - FreshBooks+ * * `Expensify` - Expensify+ * * `Ramp` - Ramp+ * * `Brex` - Brex+ * * `Coupa` - Coupa+ * * `SapConcur` - SapConcur+ * * `Apollo` - Apollo+ * * `Crunchbase` - Crunchbase+ * * `ZoomInfo` - ZoomInfo+ * * `Clari` - Clari+ * * `Chorus` - Chorus+ * * `Coda` - Coda+ * * `Guru` - Guru+ * * `Dropbox` - Dropbox+ * * `Docusign` - Docusign+ * * `PandaDoc` - PandaDoc+ * * `SapErp` - SapErp+ * * `SapSuccessFactors` - SapSuccessFactors+ * * `OracleEbs` - OracleEbs+ * * `OracleFusion` - OracleFusion+ * * `Custom` - Custom */+ source_type: ExternalDataSourceTypeEnum;+ /** Connection details as flat keys for the source_type — the same fields the create flow accepts (host, port, password, API key, …). Checked against a live connection before being stored. */+ payload: SourceCredentialCreatePayload;+ }+export interface SourceMappingSuggestion {/** The raw utm_source value seen on events */raw_utm_source: string;@@ -40556,6 +40838,282 @@ export namespace Schemas {Mapped: 'mapped',} as const;+ /**+ * Connection details as flat keys for the source_type (discover required fields with the wizard tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} referencing credentials the user stored via the connect-link page (discover ids with the stored_credentials endpoint) — they are merged in server-side and deleted once consumed. A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible sync defaults.+ */+ export type SourceSetupPayload = { [key: string]: unknown };++ export interface SourceSetup {+ /** The source type to set up (e.g. 'Stripe', 'Postgres', 'Hubspot').+ *+ * * `Ashby` - Ashby+ * * `Supabase` - Supabase+ * * `CustomerIO` - CustomerIO+ * * `Github` - Github+ * * `Stripe` - Stripe+ * * `Hubspot` - Hubspot+ * * `Postgres` - Postgres+ * * `Zendesk` - Zendesk+ * * `Snowflake` - Snowflake+ * * `Salesforce` - Salesforce+ * * `MySQL` - MySQL+ * * `MongoDB` - MongoDB+ * * `MSSQL` - MSSQL+ * * `Vitally` - Vitally+ * * `BigQuery` - BigQuery+ * * `Chargebee` - Chargebee+ * * `Clerk` - Clerk+ * * `GoogleAds` - GoogleAds+ * * `GoogleSearchConsole` - GoogleSearchConsole+ * * `TemporalIO` - TemporalIO+ * * `DoIt` - DoIt+ * * `GoogleSheets` - GoogleSheets+ * * `MetaAds` - MetaAds+ * * `Klaviyo` - Klaviyo+ * * `Mailchimp` - Mailchimp+ * * `Braze` - Braze+ * * `Mailjet` - Mailjet+ * * `Redshift` - Redshift+ * * `Polar` - Polar+ * * `RevenueCat` - RevenueCat+ * * `LinkedinAds` - LinkedinAds+ * * `RedditAds` - RedditAds+ * * `TikTokAds` - TikTokAds+ * * `BingAds` - BingAds+ * * `Shopify` - Shopify+ * * `Attio` - Attio+ * * `SnapchatAds` - SnapchatAds+ * * `Linear` - Linear+ * * `Intercom` - Intercom+ * * `Amplitude` - Amplitude+ * * `Mixpanel` - Mixpanel+ * * `Jira` - Jira+ * * `ActiveCampaign` - ActiveCampaign+ * * `Marketo` - Marketo+ * * `Adjust` - Adjust+ * * `AppsFlyer` - AppsFlyer+ * * `Freshdesk` - Freshdesk+ * * `GoogleAnalytics` - GoogleAnalytics+ * * `Pipedrive` - Pipedrive+ * * `SendGrid` - SendGrid+ * * `Slack` - Slack+ * * `PagerDuty` - PagerDuty+ * * `Asana` - Asana+ * * `Notion` - Notion+ * * `Airtable` - Airtable+ * * `Greenhouse` - Greenhouse+ * * `BambooHR` - BambooHR+ * * `Lever` - Lever+ * * `GitLab` - GitLab+ * * `Datadog` - Datadog+ * * `Sentry` - Sentry+ * * `Pendo` - Pendo+ * * `FullStory` - FullStory+ * * `AmazonAds` - AmazonAds+ * * `PinterestAds` - PinterestAds+ * * `AppleSearchAds` - AppleSearchAds+ * * `QuickBooks` - QuickBooks+ * * `Xero` - Xero+ * * `NetSuite` - NetSuite+ * * `WooCommerce` - WooCommerce+ * * `BigCommerce` - BigCommerce+ * * `PayPal` - PayPal+ * * `Square` - Square+ * * `Zoom` - Zoom+ * * `Trello` - Trello+ * * `Monday` - Monday+ * * `ClickUp` - ClickUp+ * * `Confluence` - Confluence+ * * `Recurly` - Recurly+ * * `SalesLoft` - SalesLoft+ * * `Outreach` - Outreach+ * * `Gong` - Gong+ * * `Calendly` - Calendly+ * * `Typeform` - Typeform+ * * `Iterable` - Iterable+ * * `ZohoCRM` - ZohoCRM+ * * `Close` - Close+ * * `Oracle` - Oracle+ * * `DynamoDB` - DynamoDB+ * * `Elasticsearch` - Elasticsearch+ * * `Kafka` - Kafka+ * * `LaunchDarkly` - LaunchDarkly+ * * `Braintree` - Braintree+ * * `Recharge` - Recharge+ * * `HelpScout` - HelpScout+ * * `Gorgias` - Gorgias+ * * `Instagram` - Instagram+ * * `YouTubeAnalytics` - YouTubeAnalytics+ * * `FacebookPages` - FacebookPages+ * * `TwitterAds` - TwitterAds+ * * `Workday` - Workday+ * * `ServiceNow` - ServiceNow+ * * `Pardot` - Pardot+ * * `Copper` - Copper+ * * `Front` - Front+ * * `ChartMogul` - ChartMogul+ * * `Zuora` - Zuora+ * * `Paddle` - Paddle+ * * `CircleCI` - CircleCI+ * * `CockroachDB` - CockroachDB+ * * `Firebase` - Firebase+ * * `AzureBlob` - AzureBlob+ * * `GoogleDrive` - GoogleDrive+ * * `OneDrive` - OneDrive+ * * `SharePoint` - SharePoint+ * * `Box` - Box+ * * `SFTP` - SFTP+ * * `MicrosoftTeams` - MicrosoftTeams+ * * `Aircall` - Aircall+ * * `Webflow` - Webflow+ * * `Okta` - Okta+ * * `Auth0` - Auth0+ * * `Productboard` - Productboard+ * * `Smartsheet` - Smartsheet+ * * `Wrike` - Wrike+ * * `Plaid` - Plaid+ * * `SurveyMonkey` - SurveyMonkey+ * * `Eventbrite` - Eventbrite+ * * `RingCentral` - RingCentral+ * * `Twilio` - Twilio+ * * `Freshsales` - Freshsales+ * * `Shortcut` - Shortcut+ * * `ConvertKit` - ConvertKit+ * * `Drip` - Drip+ * * `CampaignMonitor` - CampaignMonitor+ * * `MailerLite` - MailerLite+ * * `Omnisend` - Omnisend+ * * `Brevo` - Brevo+ * * `Postmark` - Postmark+ * * `Granola` - Granola+ * * `BuildBetter` - BuildBetter+ * * `Convex` - Convex+ * * `ClickHouse` - ClickHouse+ * * `Plain` - Plain+ * * `Resend` - Resend+ * * `PgAnalyze` - PgAnalyze+ * * `WorkOS` - WorkOS+ * * `AmazonS3` - AmazonS3+ * * `GoogleCloudStorage` - GoogleCloudStorage+ * * `Databricks` - Databricks+ * * `Dynamics365` - Dynamics365+ * * `SalesforceMarketingCloud` - SalesforceMarketingCloud+ * * `Db2` - Db2+ * * `Heap` - Heap+ * * `AdobeAnalytics` - AdobeAnalytics+ * * `Matomo` - Matomo+ * * `Optimizely` - Optimizely+ * * `Adyen` - Adyen+ * * `GoCardless` - GoCardless+ * * `Mollie` - Mollie+ * * `CheckoutCom` - CheckoutCom+ * * `Branch` - Branch+ * * `Criteo` - Criteo+ * * `Outbrain` - Outbrain+ * * `Taboola` - Taboola+ * * `AdRoll` - AdRoll+ * * `DisplayVideo360` - DisplayVideo360+ * * `GoogleAdManager` - GoogleAdManager+ * * `CampaignManager360` - CampaignManager360+ * * `SearchAds360` - SearchAds360+ * * `AdobeCommerce` - AdobeCommerce+ * * `AmazonSellingPartner` - AmazonSellingPartner+ * * `Ebay` - Ebay+ * * `Commercetools` - Commercetools+ * * `LightspeedRetail` - LightspeedRetail+ * * `ShipStation` - ShipStation+ * * `ConstantContact` - ConstantContact+ * * `Mailgun` - Mailgun+ * * `Eloqua` - Eloqua+ * * `Sailthru` - Sailthru+ * * `Ortto` - Ortto+ * * `Attentive` - Attentive+ * * `Kustomer` - Kustomer+ * * `Dixa` - Dixa+ * * `Gladly` - Gladly+ * * `Qualtrics` - Qualtrics+ * * `Delighted` - Delighted+ * * `AzureDevOps` - AzureDevOps+ * * `Rollbar` - Rollbar+ * * `Opsgenie` - Opsgenie+ * * `IncidentIo` - IncidentIo+ * * `Pingdom` - Pingdom+ * * `Cloudflare` - Cloudflare+ * * `CosmosDB` - CosmosDB+ * * `PlanetScale` - PlanetScale+ * * `SapHana` - SapHana+ * * `Rippling` - Rippling+ * * `HiBob` - HiBob+ * * `Personio` - Personio+ * * `Deel` - Deel+ * * `AdpWorkforceNow` - AdpWorkforceNow+ * * `Paylocity` - Paylocity+ * * `Gusto` - Gusto+ * * `CultureAmp` - CultureAmp+ * * `Lattice` - Lattice+ * * `SageIntacct` - SageIntacct+ * * `FreshBooks` - FreshBooks+ * * `Expensify` - Expensify+ * * `Ramp` - Ramp+ * * `Brex` - Brex+ * * `Coupa` - Coupa+ * * `SapConcur` - SapConcur+ * * `Apollo` - Apollo+ * * `Crunchbase` - Crunchbase+ * * `ZoomInfo` - ZoomInfo+ * * `Clari` - Clari+ * * `Chorus` - Chorus+ * * `Coda` - Coda+ * * `Guru` - Guru+ * * `Dropbox` - Dropbox+ * * `Docusign` - Docusign+ * * `PandaDoc` - PandaDoc+ * * `SapErp` - SapErp+ * * `SapSuccessFactors` - SapSuccessFactors+ * * `OracleEbs` - OracleEbs+ * * `OracleFusion` - OracleFusion+ * * `Custom` - Custom */+ source_type: ExternalDataSourceTypeEnum;+ /** Connection details as flat keys for the source_type (discover required fields with the wizard tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} referencing credentials the user stored via the connect-link page (discover ids with the stored_credentials endpoint) — they are merged in server-side and deleted once consumed. A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible sync defaults. */+ payload?: SourceSetupPayload;+ /**+ * Table name prefix in HogQL, e.g. 'stripe' produces stripe_charges. Defaults to the source type.+ * @maxLength 100+ * @nullable+ */+ prefix?: string | null;+ /**+ * Human-readable description.+ * @maxLength 400+ * @nullable+ */+ description?: string | null;+ }++ export interface SourceSetupWebhook {+ /** Whether the webhook was registered with the external service. When true, webhook-capable tables (including webhook-only ones) sync via real-time webhooks; when false, tables fall back to the polling sync defaults and webhook-only tables stay disabled. */+ success: boolean;+ /**+ * The PostHog endpoint the external service delivers events to.+ * @nullable+ */+ webhook_url: string | null;+ /**+ * Why webhook registration failed (e.g. the credentials lack webhook permissions).+ * @nullable+ */+ error: string | null;+ /** Webhook input names the user still needs to provide (e.g. a signing secret the external API did not return on create). Submit them via the update_webhook_inputs endpoint. */+ pending_inputs: string[];+ }++ export interface SourceSetupResponse {+ /** ID of the created external data source. */+ id: string;+ /** Outcome of automatic webhook registration. Only present for sources that support webhooks (e.g. Stripe) and have webhook-capable tables. */+ webhook?: SourceSetupWebhook;+ }+/*** * `severity` - severity* * `service` - service@@ -44572,6 +45130,13 @@ export namespace Schemas {errors?: string[];};+ export type EnvironmentsExternalDataSourcesConnectLinkRetrieveParams = {+ /**+ * The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').+ */+ source_type: string;+ };+export type EnvironmentsExternalDataSourcesConnectionsListParams = {/*** Number of results to return per page.@@ -44587,6 +45152,17 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsExternalDataSourcesStoredCredentialsListParams = {+ /**+ * A search term.+ */+ search?: string;+ /**+ * Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres').+ */+ source_type?: string;+ };+export type EnvironmentsFileDownloadBatchExportsListParams = {/*** Number of results to return per page.@@ -50242,6 +50818,13 @@ export namespace Schemas {errors?: string[];};+ export type ExternalDataSourcesConnectLinkRetrieveParams = {+ /**+ * The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').+ */+ source_type: string;+ };+export type ExternalDataSourcesConnectionsListParams = {/*** Number of results to return per page.@@ -50257,6 +50840,17 @@ export namespace Schemas {search?: string;};+ export type ExternalDataSourcesStoredCredentialsListParams = {+ /**+ * A search term.+ */+ search?: string;+ /**+ * Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres').+ */+ source_type?: string;+ };+export type FeatureFlagsListParams = {active?: FeatureFlagsListActive;/**diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.tsindex 3c122e26f11c..8b70205ec0dd 100644--- a/services/mcp/src/generated/data_warehouse/api.ts+++ b/services/mcp/src/generated/data_warehouse/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 35 enabled ops+ * PostHog API - MCP 38 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -1003,6 +1003,29 @@ export const ExternalDataSourcesCheckCdcPrerequisitesCreateParams = /* @__PURE__),})+/**+ * Return a secure browser link for connecting a data warehouse source.+ *+ * For OAuth sources the link starts the OAuth authorize flow; for credential sources it opens a minimal+ * connect page where the user enters only their credentials — no table selection, no source creation.+ * Either way the user authenticates in their browser, credentials never pass through the agent, and the+ * agent finishes setup afterwards by passing the resulting reference (integration id or credential id)+ * to data-warehouse-source-setup.+ */+export const ExternalDataSourcesConnectLinkRetrieveParams = /* @__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 ExternalDataSourcesConnectLinkRetrieveQueryParams = /* @__PURE__ */ zod.object({+ source_type: zod+ .string()+ .describe("The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot')."),+})+/*** Create, Read, Update and Delete External data Sources.*/@@ -1020,6 +1043,308 @@ export const ExternalDataSourcesConnectionsListQueryParams = /* @__PURE__ */ zodsearch: zod.string().optional().describe('A search term.'),})+/**+ * One-shot data warehouse source setup.+ *+ * Validate credentials, discover available tables, enable them all with sensible sync defaults+ * (incremental where supported, else append, else full refresh), and create the source in a single+ * call — the caller never has to assemble a `schemas` array. For sources that support webhooks+ * (e.g. Stripe), a webhook is auto-registered after creation: on success webhook-capable tables+ * switch to real-time webhook sync (unlocking webhook-only tables); on failure the polling+ * defaults stay in place. For fine-grained table/sync control, use the lower-level+ * `database_schema` + `create` flow instead.+ */+export const ExternalDataSourcesSetupCreateParams = /* @__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 externalDataSourcesSetupCreateBodyPrefixMax = 100++export const externalDataSourcesSetupCreateBodyDescriptionMax = 400++export const ExternalDataSourcesSetupCreateBody = /* @__PURE__ */ zod.object({+ source_type: zod+ .enum([+ 'Ashby',+ 'Supabase',+ 'CustomerIO',+ 'Github',+ 'Stripe',+ 'Hubspot',+ 'Postgres',+ 'Zendesk',+ 'Snowflake',+ 'Salesforce',+ 'MySQL',+ 'MongoDB',+ 'MSSQL',+ 'Vitally',+ 'BigQuery',+ 'Chargebee',+ 'Clerk',+ 'GoogleAds',+ 'GoogleSearchConsole',+ 'TemporalIO',+ 'DoIt',+ 'GoogleSheets',+ 'MetaAds',+ 'Klaviyo',+ 'Mailchimp',+ 'Braze',+ 'Mailjet',+ 'Redshift',+ 'Polar',+ 'RevenueCat',+ 'LinkedinAds',+ 'RedditAds',+ 'TikTokAds',+ 'BingAds',+ 'Shopify',+ 'Attio',+ 'SnapchatAds',+ 'Linear',+ 'Intercom',+ 'Amplitude',+ 'Mixpanel',+ 'Jira',+ 'ActiveCampaign',+ 'Marketo',+ 'Adjust',+ 'AppsFlyer',+ 'Freshdesk',+ 'GoogleAnalytics',+ 'Pipedrive',+ 'SendGrid',+ 'Slack',+ 'PagerDuty',+ 'Asana',+ 'Notion',+ 'Airtable',+ 'Greenhouse',+ 'BambooHR',+ 'Lever',+ 'GitLab',+ 'Datadog',+ 'Sentry',+ 'Pendo',+ 'FullStory',+ 'AmazonAds',+ 'PinterestAds',+ 'AppleSearchAds',+ 'QuickBooks',+ 'Xero',+ 'NetSuite',+ 'WooCommerce',+ 'BigCommerce',+ 'PayPal',+ 'Square',+ 'Zoom',+ 'Trello',+ 'Monday',+ 'ClickUp',+ 'Confluence',+ 'Recurly',+ 'SalesLoft',+ 'Outreach',+ 'Gong',+ 'Calendly',+ 'Typeform',+ 'Iterable',+ 'ZohoCRM',+ 'Close',+ 'Oracle',+ 'DynamoDB',+ 'Elasticsearch',+ 'Kafka',+ 'LaunchDarkly',+ 'Braintree',+ 'Recharge',+ 'HelpScout',+ 'Gorgias',+ 'Instagram',+ 'YouTubeAnalytics',+ 'FacebookPages',+ 'TwitterAds',+ 'Workday',+ 'ServiceNow',+ 'Pardot',+ 'Copper',+ 'Front',+ 'ChartMogul',+ 'Zuora',+ 'Paddle',+ 'CircleCI',+ 'CockroachDB',+ 'Firebase',+ 'AzureBlob',+ 'GoogleDrive',+ 'OneDrive',+ 'SharePoint',+ 'Box',+ 'SFTP',+ 'MicrosoftTeams',+ 'Aircall',+ 'Webflow',+ 'Okta',+ 'Auth0',+ 'Productboard',+ 'Smartsheet',+ 'Wrike',+ 'Plaid',+ 'SurveyMonkey',+ 'Eventbrite',+ 'RingCentral',+ 'Twilio',+ 'Freshsales',+ 'Shortcut',+ 'ConvertKit',+ 'Drip',+ 'CampaignMonitor',+ 'MailerLite',+ 'Omnisend',+ 'Brevo',+ 'Postmark',+ 'Granola',+ 'BuildBetter',+ 'Convex',+ 'ClickHouse',+ 'Plain',+ 'Resend',+ 'PgAnalyze',+ 'WorkOS',+ 'AmazonS3',+ 'GoogleCloudStorage',+ 'Databricks',+ 'Dynamics365',+ 'SalesforceMarketingCloud',+ 'Db2',+ 'Heap',+ 'AdobeAnalytics',+ 'Matomo',+ 'Optimizely',+ 'Adyen',+ 'GoCardless',+ 'Mollie',+ 'CheckoutCom',+ 'Branch',+ 'Criteo',+ 'Outbrain',+ 'Taboola',+ 'AdRoll',+ 'DisplayVideo360',+ 'GoogleAdManager',+ 'CampaignManager360',+ 'SearchAds360',+ 'AdobeCommerce',+ 'AmazonSellingPartner',+ 'Ebay',+ 'Commercetools',+ 'LightspeedRetail',+ 'ShipStation',+ 'ConstantContact',+ 'Mailgun',+ 'Eloqua',+ 'Sailthru',+ 'Ortto',+ 'Attentive',+ 'Kustomer',+ 'Dixa',+ 'Gladly',+ 'Qualtrics',+ 'Delighted',+ 'AzureDevOps',+ 'Rollbar',+ 'Opsgenie',+ 'IncidentIo',+ 'Pingdom',+ 'Cloudflare',+ 'CosmosDB',+ 'PlanetScale',+ 'SapHana',+ 'Rippling',+ 'HiBob',+ 'Personio',+ 'Deel',+ 'AdpWorkforceNow',+ 'Paylocity',+ 'Gusto',+ 'CultureAmp',+ 'Lattice',+ 'SageIntacct',+ 'FreshBooks',+ 'Expensify',+ 'Ramp',+ 'Brex',+ 'Coupa',+ 'SapConcur',+ 'Apollo',+ 'Crunchbase',+ 'ZoomInfo',+ 'Clari',+ 'Chorus',+ 'Coda',+ 'Guru',+ 'Dropbox',+ 'Docusign',+ 'PandaDoc',+ 'SapErp',+ 'SapSuccessFactors',+ 'OracleEbs',+ 'OracleFusion',+ 'Custom',+ ])+ .describe(+ '* `Ashby` - Ashby\n* `Supabase` - Supabase\n* `CustomerIO` - CustomerIO\n* `Github` - Github\n* `Stripe` - Stripe\n* `Hubspot` - Hubspot\n* `Postgres` - Postgres\n* `Zendesk` - Zendesk\n* `Snowflake` - Snowflake\n* `Salesforce` - Salesforce\n* `MySQL` - MySQL\n* `MongoDB` - MongoDB\n* `MSSQL` - MSSQL\n* `Vitally` - Vitally\n* `BigQuery` - BigQuery\n* `Chargebee` - Chargebee\n* `Clerk` - Clerk\n* `GoogleAds` - GoogleAds\n* `GoogleSearchConsole` - GoogleSearchConsole\n* `TemporalIO` - TemporalIO\n* `DoIt` - DoIt\n* `GoogleSheets` - GoogleSheets\n* `MetaAds` - MetaAds\n* `Klaviyo` - Klaviyo\n* `Mailchimp` - Mailchimp\n* `Braze` - Braze\n* `Mailjet` - Mailjet\n* `Redshift` - Redshift\n* `Polar` - Polar\n* `RevenueCat` - RevenueCat\n* `LinkedinAds` - LinkedinAds\n* `RedditAds` - RedditAds\n* `TikTokAds` - TikTokAds\n* `BingAds` - BingAds\n* `Shopify` - Shopify\n* `Attio` - Attio\n* `SnapchatAds` - SnapchatAds\n* `Linear` - Linear\n* `Intercom` - Intercom\n* `Amplitude` - Amplitude\n* `Mixpanel` - Mixpanel\n* `Jira` - Jira\n* `ActiveCampaign` - ActiveCampaign\n* `Marketo` - Marketo\n* `Adjust` - Adjust\n* `AppsFlyer` - AppsFlyer\n* `Freshdesk` - Freshdesk\n* `GoogleAnalytics` - GoogleAnalytics\n* `Pipedrive` - Pipedrive\n* `SendGrid` - SendGrid\n* `Slack` - Slack\n* `PagerDuty` - PagerDuty\n* `Asana` - Asana\n* `Notion` - Notion\n* `Airtable` - Airtable\n* `Greenhouse` - Greenhouse\n* `BambooHR` - BambooHR\n* `Lever` - Lever\n* `GitLab` - GitLab\n* `Datadog` - Datadog\n* `Sentry` - Sentry\n* `Pendo` - Pendo\n* `FullStory` - FullStory\n* `AmazonAds` - AmazonAds\n* `PinterestAds` - PinterestAds\n* `AppleSearchAds` - AppleSearchAds\n* `QuickBooks` - QuickBooks\n* `Xero` - Xero\n* `NetSuite` - NetSuite\n* `WooCommerce` - WooCommerce\n* `BigCommerce` - BigCommerce\n* `PayPal` - PayPal\n* `Square` - Square\n* `Zoom` - Zoom\n* `Trello` - Trello\n* `Monday` - Monday\n* `ClickUp` - ClickUp\n* `Confluence` - Confluence\n* `Recurly` - Recurly\n* `SalesLoft` - SalesLoft\n* `Outreach` - Outreach\n* `Gong` - Gong\n* `Calendly` - Calendly\n* `Typeform` - Typeform\n* `Iterable` - Iterable\n* `ZohoCRM` - ZohoCRM\n* `Close` - Close\n* `Oracle` - Oracle\n* `DynamoDB` - DynamoDB\n* `Elasticsearch` - Elasticsearch\n* `Kafka` - Kafka\n* `LaunchDarkly` - LaunchDarkly\n* `Braintree` - Braintree\n* `Recharge` - Recharge\n* `HelpScout` - HelpScout\n* `Gorgias` - Gorgias\n* `Instagram` - Instagram\n* `YouTubeAnalytics` - YouTubeAnalytics\n* `FacebookPages` - FacebookPages\n* `TwitterAds` - TwitterAds\n* `Workday` - Workday\n* `ServiceNow` - ServiceNow\n* `Pardot` - Pardot\n* `Copper` - Copper\n* `Front` - Front\n* `ChartMogul` - ChartMogul\n* `Zuora` - Zuora\n* `Paddle` - Paddle\n* `CircleCI` - CircleCI\n* `CockroachDB` - CockroachDB\n* `Firebase` - Firebase\n* `AzureBlob` - AzureBlob\n* `GoogleDrive` - GoogleDrive\n* `OneDrive` - OneDrive\n* `SharePoint` - SharePoint\n* `Box` - Box\n* `SFTP` - SFTP\n* `MicrosoftTeams` - MicrosoftTeams\n* `Aircall` - Aircall\n* `Webflow` - Webflow\n* `Okta` - Okta\n* `Auth0` - Auth0\n* `Productboard` - Productboard\n* `Smartsheet` - Smartsheet\n* `Wrike` - Wrike\n* `Plaid` - Plaid\n* `SurveyMonkey` - SurveyMonkey\n* `Eventbrite` - Eventbrite\n* `RingCentral` - RingCentral\n* `Twilio` - Twilio\n* `Freshsales` - Freshsales\n* `Shortcut` - Shortcut\n* `ConvertKit` - ConvertKit\n* `Drip` - Drip\n* `CampaignMonitor` - CampaignMonitor\n* `MailerLite` - MailerLite\n* `Omnisend` - Omnisend\n* `Brevo` - Brevo\n* `Postmark` - Postmark\n* `Granola` - Granola\n* `BuildBetter` - BuildBetter\n* `Convex` - Convex\n* `ClickHouse` - ClickHouse\n* `Plain` - Plain\n* `Resend` - Resend\n* `PgAnalyze` - PgAnalyze\n* `WorkOS` - WorkOS\n* `AmazonS3` - AmazonS3\n* `GoogleCloudStorage` - GoogleCloudStorage\n* `Databricks` - Databricks\n* `Dynamics365` - Dynamics365\n* `SalesforceMarketingCloud` - SalesforceMarketingCloud\n* `Db2` - Db2\n* `Heap` - Heap\n* `AdobeAnalytics` - AdobeAnalytics\n* `Matomo` - Matomo\n* `Optimizely` - Optimizely\n* `Adyen` - Adyen\n* `GoCardless` - GoCardless\n* `Mollie` - Mollie\n* `CheckoutCom` - CheckoutCom\n* `Branch` - Branch\n* `Criteo` - Criteo\n* `Outbrain` - Outbrain\n* `Taboola` - Taboola\n* `AdRoll` - AdRoll\n* `DisplayVideo360` - DisplayVideo360\n* `GoogleAdManager` - GoogleAdManager\n* `CampaignManager360` - CampaignManager360\n* `SearchAds360` - SearchAds360\n* `AdobeCommerce` - AdobeCommerce\n* `AmazonSellingPartner` - AmazonSellingPartner\n* `Ebay` - Ebay\n* `Commercetools` - Commercetools\n* `LightspeedRetail` - LightspeedRetail\n* `ShipStation` - ShipStation\n* `ConstantContact` - ConstantContact\n* `Mailgun` - Mailgun\n* `Eloqua` - Eloqua\n* `Sailthru` - Sailthru\n* `Ortto` - Ortto\n* `Attentive` - Attentive\n* `Kustomer` - Kustomer\n* `Dixa` - Dixa\n* `Gladly` - Gladly\n* `Qualtrics` - Qualtrics\n* `Delighted` - Delighted\n* `AzureDevOps` - AzureDevOps\n* `Rollbar` - Rollbar\n* `Opsgenie` - Opsgenie\n* `IncidentIo` - IncidentIo\n* `Pingdom` - Pingdom\n* `Cloudflare` - Cloudflare\n* `CosmosDB` - CosmosDB\n* `PlanetScale` - PlanetScale\n* `SapHana` - SapHana\n* `Rippling` - Rippling\n* `HiBob` - HiBob\n* `Personio` - Personio\n* `Deel` - Deel\n* `AdpWorkforceNow` - AdpWorkforceNow\n* `Paylocity` - Paylocity\n* `Gusto` - Gusto\n* `CultureAmp` - CultureAmp\n* `Lattice` - Lattice\n* `SageIntacct` - SageIntacct\n* `FreshBooks` - FreshBooks\n* `Expensify` - Expensify\n* `Ramp` - Ramp\n* `Brex` - Brex\n* `Coupa` - Coupa\n* `SapConcur` - SapConcur\n* `Apollo` - Apollo\n* `Crunchbase` - Crunchbase\n* `ZoomInfo` - ZoomInfo\n* `Clari` - Clari\n* `Chorus` - Chorus\n* `Coda` - Coda\n* `Guru` - Guru\n* `Dropbox` - Dropbox\n* `Docusign` - Docusign\n* `PandaDoc` - PandaDoc\n* `SapErp` - SapErp\n* `SapSuccessFactors` - SapSuccessFactors\n* `OracleEbs` - OracleEbs\n* `OracleFusion` - OracleFusion\n* `Custom` - Custom'+ )+ .describe(+ "The source type to set up (e.g. 'Stripe', 'Postgres', 'Hubspot').\n\n* `Ashby` - Ashby\n* `Supabase` - Supabase\n* `CustomerIO` - CustomerIO\n* `Github` - Github\n* `Stripe` - Stripe\n* `Hubspot` - Hubspot\n* `Postgres` - Postgres\n* `Zendesk` - Zendesk\n* `Snowflake` - Snowflake\n* `Salesforce` - Salesforce\n* `MySQL` - MySQL\n* `MongoDB` - MongoDB\n* `MSSQL` - MSSQL\n* `Vitally` - Vitally\n* `BigQuery` - BigQuery\n* `Chargebee` - Chargebee\n* `Clerk` - Clerk\n* `GoogleAds` - GoogleAds\n* `GoogleSearchConsole` - GoogleSearchConsole\n* `TemporalIO` - TemporalIO\n* `DoIt` - DoIt\n* `GoogleSheets` - GoogleSheets\n* `MetaAds` - MetaAds\n* `Klaviyo` - Klaviyo\n* `Mailchimp` - Mailchimp\n* `Braze` - Braze\n* `Mailjet` - Mailjet\n* `Redshift` - Redshift\n* `Polar` - Polar\n* `RevenueCat` - RevenueCat\n* `LinkedinAds` - LinkedinAds\n* `RedditAds` - RedditAds\n* `TikTokAds` - TikTokAds\n* `BingAds` - BingAds\n* `Shopify` - Shopify\n* `Attio` - Attio\n* `SnapchatAds` - SnapchatAds\n* `Linear` - Linear\n* `Intercom` - Intercom\n* `Amplitude` - Amplitude\n* `Mixpanel` - Mixpanel\n* `Jira` - Jira\n* `ActiveCampaign` - ActiveCampaign\n* `Marketo` - Marketo\n* `Adjust` - Adjust\n* `AppsFlyer` - AppsFlyer\n* `Freshdesk` - Freshdesk\n* `GoogleAnalytics` - GoogleAnalytics\n* `Pipedrive` - Pipedrive\n* `SendGrid` - SendGrid\n* `Slack` - Slack\n* `PagerDuty` - PagerDuty\n* `Asana` - Asana\n* `Notion` - Notion\n* `Airtable` - Airtable\n* `Greenhouse` - Greenhouse\n* `BambooHR` - BambooHR\n* `Lever` - Lever\n* `GitLab` - GitLab\n* `Datadog` - Datadog\n* `Sentry` - Sentry\n* `Pendo` - Pendo\n* `FullStory` - FullStory\n* `AmazonAds` - AmazonAds\n* `PinterestAds` - PinterestAds\n* `AppleSearchAds` - AppleSearchAds\n* `QuickBooks` - QuickBooks\n* `Xero` - Xero\n* `NetSuite` - NetSuite\n* `WooCommerce` - WooCommerce\n* `BigCommerce` - BigCommerce\n* `PayPal` - PayPal\n* `Square` - Square\n* `Zoom` - Zoom\n* `Trello` - Trello\n* `Monday` - Monday\n* `ClickUp` - ClickUp\n* `Confluence` - Confluence\n* `Recurly` - Recurly\n* `SalesLoft` - SalesLoft\n* `Outreach` - Outreach\n* `Gong` - Gong\n* `Calendly` - Calendly\n* `Typeform` - Typeform\n* `Iterable` - Iterable\n* `ZohoCRM` - ZohoCRM\n* `Close` - Close\n* `Oracle` - Oracle\n* `DynamoDB` - DynamoDB\n* `Elasticsearch` - Elasticsearch\n* `Kafka` - Kafka\n* `LaunchDarkly` - LaunchDarkly\n* `Braintree` - Braintree\n* `Recharge` - Recharge\n* `HelpScout` - HelpScout\n* `Gorgias` - Gorgias\n* `Instagram` - Instagram\n* `YouTubeAnalytics` - YouTubeAnalytics\n* `FacebookPages` - FacebookPages\n* `TwitterAds` - TwitterAds\n* `Workday` - Workday\n* `ServiceNow` - ServiceNow\n* `Pardot` - Pardot\n* `Copper` - Copper\n* `Front` - Front\n* `ChartMogul` - ChartMogul\n* `Zuora` - Zuora\n* `Paddle` - Paddle\n* `CircleCI` - CircleCI\n* `CockroachDB` - CockroachDB\n* `Firebase` - Firebase\n* `AzureBlob` - AzureBlob\n* `GoogleDrive` - GoogleDrive\n* `OneDrive` - OneDrive\n* `SharePoint` - SharePoint\n* `Box` - Box\n* `SFTP` - SFTP\n* `MicrosoftTeams` - MicrosoftTeams\n* `Aircall` - Aircall\n* `Webflow` - Webflow\n* `Okta` - Okta\n* `Auth0` - Auth0\n* `Productboard` - Productboard\n* `Smartsheet` - Smartsheet\n* `Wrike` - Wrike\n* `Plaid` - Plaid\n* `SurveyMonkey` - SurveyMonkey\n* `Eventbrite` - Eventbrite\n* `RingCentral` - RingCentral\n* `Twilio` - Twilio\n* `Freshsales` - Freshsales\n* `Shortcut` - Shortcut\n* `ConvertKit` - ConvertKit\n* `Drip` - Drip\n* `CampaignMonitor` - CampaignMonitor\n* `MailerLite` - MailerLite\n* `Omnisend` - Omnisend\n* `Brevo` - Brevo\n* `Postmark` - Postmark\n* `Granola` - Granola\n* `BuildBetter` - BuildBetter\n* `Convex` - Convex\n* `ClickHouse` - ClickHouse\n* `Plain` - Plain\n* `Resend` - Resend\n* `PgAnalyze` - PgAnalyze\n* `WorkOS` - WorkOS\n* `AmazonS3` - AmazonS3\n* `GoogleCloudStorage` - GoogleCloudStorage\n* `Databricks` - Databricks\n* `Dynamics365` - Dynamics365\n* `SalesforceMarketingCloud` - SalesforceMarketingCloud\n* `Db2` - Db2\n* `Heap` - Heap\n* `AdobeAnalytics` - AdobeAnalytics\n* `Matomo` - Matomo\n* `Optimizely` - Optimizely\n* `Adyen` - Adyen\n* `GoCardless` - GoCardless\n* `Mollie` - Mollie\n* `CheckoutCom` - CheckoutCom\n* `Branch` - Branch\n* `Criteo` - Criteo\n* `Outbrain` - Outbrain\n* `Taboola` - Taboola\n* `AdRoll` - AdRoll\n* `DisplayVideo360` - DisplayVideo360\n* `GoogleAdManager` - GoogleAdManager\n* `CampaignManager360` - CampaignManager360\n* `SearchAds360` - SearchAds360\n* `AdobeCommerce` - AdobeCommerce\n* `AmazonSellingPartner` - AmazonSellingPartner\n* `Ebay` - Ebay\n* `Commercetools` - Commercetools\n* `LightspeedRetail` - LightspeedRetail\n* `ShipStation` - ShipStation\n* `ConstantContact` - ConstantContact\n* `Mailgun` - Mailgun\n* `Eloqua` - Eloqua\n* `Sailthru` - Sailthru\n* `Ortto` - Ortto\n* `Attentive` - Attentive\n* `Kustomer` - Kustomer\n* `Dixa` - Dixa\n* `Gladly` - Gladly\n* `Qualtrics` - Qualtrics\n* `Delighted` - Delighted\n* `AzureDevOps` - AzureDevOps\n* `Rollbar` - Rollbar\n* `Opsgenie` - Opsgenie\n* `IncidentIo` - IncidentIo\n* `Pingdom` - Pingdom\n* `Cloudflare` - Cloudflare\n* `CosmosDB` - CosmosDB\n* `PlanetScale` - PlanetScale\n* `SapHana` - SapHana\n* `Rippling` - Rippling\n* `HiBob` - HiBob\n* `Personio` - Personio\n* `Deel` - Deel\n* `AdpWorkforceNow` - AdpWorkforceNow\n* `Paylocity` - Paylocity\n* `Gusto` - Gusto\n* `CultureAmp` - CultureAmp\n* `Lattice` - Lattice\n* `SageIntacct` - SageIntacct\n* `FreshBooks` - FreshBooks\n* `Expensify` - Expensify\n* `Ramp` - Ramp\n* `Brex` - Brex\n* `Coupa` - Coupa\n* `SapConcur` - SapConcur\n* `Apollo` - Apollo\n* `Crunchbase` - Crunchbase\n* `ZoomInfo` - ZoomInfo\n* `Clari` - Clari\n* `Chorus` - Chorus\n* `Coda` - Coda\n* `Guru` - Guru\n* `Dropbox` - Dropbox\n* `Docusign` - Docusign\n* `PandaDoc` - PandaDoc\n* `SapErp` - SapErp\n* `SapSuccessFactors` - SapSuccessFactors\n* `OracleEbs` - OracleEbs\n* `OracleFusion` - OracleFusion\n* `Custom` - Custom"+ ),+ payload: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ "Connection details as flat keys for the source_type (discover required fields with the wizard tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} referencing credentials the user stored via the connect-link page (discover ids with the stored_credentials endpoint) — they are merged in server-side and deleted once consumed. A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible sync defaults."+ ),+ prefix: zod+ .string()+ .max(externalDataSourcesSetupCreateBodyPrefixMax)+ .nullish()+ .describe("Table name prefix in HogQL, e.g. 'stripe' produces stripe_charges. Defaults to the source type."),+ description: zod+ .string()+ .max(externalDataSourcesSetupCreateBodyDescriptionMax)+ .nullish()+ .describe('Human-readable description.'),+})++/**+ * List credentials stored via the source connect page that haven't been consumed yet.+ *+ * Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored+ * credentials are temporary: they disappear once consumed by `setup` or when they expire.+ * Newest first, so after a user confirms they've finished the connect page, the first entry+ * for the source type is the one to pass to `setup`.+ */+export const ExternalDataSourcesStoredCredentialsListParams = /* @__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 ExternalDataSourcesStoredCredentialsListQueryParams = /* @__PURE__ */ zod.object({+ search: zod.string().optional().describe('A search term.'),+ source_type: zod+ .string()+ .optional()+ .describe("Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres')."),+})+/*** Create, Read, Update and Delete External data Sources.*/diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.tsindex f165ec56ff18..216b7624fe4f 100644--- a/services/mcp/src/tools/generated/data_warehouse.ts+++ b/services/mcp/src/tools/generated/data_warehouse.ts@@ -16,6 +16,7 @@ import {ExternalDataSchemasResyncCreateBody,ExternalDataSchemasResyncCreateParams,ExternalDataSchemasRetrieveParams,+ ExternalDataSourcesConnectLinkRetrieveQueryParams,ExternalDataSourcesConnectionsListQueryParams,ExternalDataSourcesCreateBody,ExternalDataSourcesCreateWebhookCreateBody,@@ -31,6 +32,8 @@ import {ExternalDataSourcesReloadCreateBody,ExternalDataSourcesReloadCreateParams,ExternalDataSourcesRetrieveParams,+ ExternalDataSourcesSetupCreateBody,+ ExternalDataSourcesStoredCredentialsListQueryParams,ExternalDataSourcesUpdateWebhookInputsCreateBody,ExternalDataSourcesUpdateWebhookInputsCreateParams,ExternalDataSourcesWebhookInfoRetrieveParams,@@ -75,6 +78,82 @@ const dataWarehouseDataHealthIssuesRetrieve = (): ToolBase<},})+const DataWarehouseSourceConnectLinkSchema = ExternalDataSourcesConnectLinkRetrieveQueryParams.extend({+ source_type: ExternalDataSourceTypeSchema,+})++const dataWarehouseSourceConnectLink = (): ToolBase<+ typeof DataWarehouseSourceConnectLinkSchema,+ Schemas.SourceConnectLink+> => ({+ name: 'data-warehouse-source-connect-link',+ schema: DataWarehouseSourceConnectLinkSchema,+ handler: async (context: Context, params: z.infer<typeof DataWarehouseSourceConnectLinkSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SourceConnectLink>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/connect_link/`,+ query: {+ source_type: params.source_type,+ },+ })+ return result+ },+})++const DataWarehouseSourceSetupSchema = ExternalDataSourcesSetupCreateBody.extend({+ source_type: ExternalDataSourceTypeSchema,+})++const dataWarehouseSourceSetup = (): ToolBase<typeof DataWarehouseSourceSetupSchema, Schemas.SourceSetupResponse> => ({+ name: 'data-warehouse-source-setup',+ schema: DataWarehouseSourceSetupSchema,+ handler: async (context: Context, params: z.infer<typeof DataWarehouseSourceSetupSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.source_type !== undefined) {+ body['source_type'] = params.source_type+ }+ if (params.payload !== undefined) {+ body['payload'] = params.payload+ }+ if (params.prefix !== undefined) {+ body['prefix'] = params.prefix+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ const result = await context.api.request<Schemas.SourceSetupResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/setup/`,+ body,+ })+ return result+ },+})++const DataWarehouseStoredCredentialsListSchema = ExternalDataSourcesStoredCredentialsListQueryParams++const dataWarehouseStoredCredentialsList = (): ToolBase<+ typeof DataWarehouseStoredCredentialsListSchema,+ WithPostHogUrl<Schemas.SourceCredential[]>+> => ({+ name: 'data-warehouse-stored-credentials-list',+ schema: DataWarehouseStoredCredentialsListSchema,+ handler: async (context: Context, params: z.infer<typeof DataWarehouseStoredCredentialsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SourceCredential[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/stored_credentials/`,+ query: {+ search: params.search,+ source_type: params.source_type,+ },+ })+ return await withPostHogUrl(context, result, '/sql')+ },+})+const ExternalDataSchemasCancelSchema = ExternalDataSchemasCancelCreateParams.omit({ project_id: true }).extend(ExternalDataSchemasCancelCreateBody.shape)@@ -1127,6 +1206,9 @@ const viewUpdate = (): ToolBase<typeof ViewUpdateSchema, WithPostHogUrl<Schemas.export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'data-warehouse-data-health-issues-retrieve': dataWarehouseDataHealthIssuesRetrieve,+ 'data-warehouse-source-connect-link': dataWarehouseSourceConnectLink,+ 'data-warehouse-source-setup': dataWarehouseSourceSetup,+ 'data-warehouse-stored-credentials-list': dataWarehouseStoredCredentialsList,'external-data-schemas-cancel': externalDataSchemasCancel,'external-data-schemas-delete-data': externalDataSchemasDeleteData,'external-data-schemas-incremental-fields-create': externalDataSchemasIncrementalFieldsCreate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-source-connect-link.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-source-connect-link.jsonnew file mode 100644index 000000000000..8df2993b38ed--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-source-connect-link.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "source_type": {+ "description": "The source type name (e.g. \"Postgres\", \"MySQL\", \"Stripe\"). Use external-data-sources-wizard to see available types and their required fields.",+ "type": "string"+ }+ },+ "required": ["source_type"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-source-setup.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-source-setup.jsonnew file mode 100644index 000000000000..352bf54d67af--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-source-setup.json@@ -0,0 +1,43 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "description": {+ "anyOf": [+ {+ "maxLength": 400,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Human-readable description."+ },+ "payload": {+ "additionalProperties": {},+ "description": "Connection details as flat keys for the source_type (discover required fields with the wizard tool). Prefer references over raw secrets: for OAuth sources pass the source's integration id key (e.g. {'hubspot_integration_id': 123}); for credential sources pass {'credential_id': <id>} referencing credentials the user stored via the connect-link page (discover ids with the stored_credentials endpoint) — they are merged in server-side and deleted once consumed. A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible sync defaults.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "prefix": {+ "anyOf": [+ {+ "maxLength": 100,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Table name prefix in HogQL, e.g. 'stripe' produces stripe_charges. Defaults to the source type."+ },+ "source_type": {+ "description": "The source type name (e.g. \"Postgres\", \"MySQL\", \"Stripe\"). Use external-data-sources-wizard to see available types and their required fields.",+ "type": "string"+ }+ },+ "required": ["source_type"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-stored-credentials-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-stored-credentials-list.jsonnew file mode 100644index 000000000000..316af4d6629c--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-warehouse-stored-credentials-list.json@@ -0,0 +1,14 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "search": {+ "description": "A search term.",+ "type": "string"+ },+ "source_type": {+ "description": "Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres').",+ "type": "string"+ }+ },+ "type": "object"+}