Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement the x ads import source (#109070)

Tom Owers48bab298df35
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index a3e0c0cad1af..ccffee890862 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -24,6 +24,7 @@ import { urls } from 'scenes/urls'
import { EmailIntegrationDomainGroupedType, IntegrationKind, IntegrationType } from '~/types'
import {
+ integrationsCreate,
integrationsGithubAvailableInstallationsRetrieve,
integrationsGithubReposRetrieve,
integrationsGithubLinkExistingCreate,
@@ -126,6 +127,7 @@ export interface integrationsLogicValues {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
)[]
@@ -237,6 +239,7 @@ export interface integrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
searchParams: any
@@ -372,6 +375,7 @@ export interface integrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
}[],
@@ -435,6 +439,7 @@ export interface integrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
}[]
@@ -492,6 +497,7 @@ export interface integrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
}
@@ -556,6 +562,7 @@ export interface integrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics',
payload?: {
@@ -605,6 +612,7 @@ export interface integrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
payload?: {
@@ -700,6 +708,7 @@ export interface integrationsLogicMeta {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
)[]
@@ -1178,6 +1187,46 @@ export const integrationsLogic = kea<integrationsLogicType>([
cache.disposables.dispose('focusRefetch')
},
handleOauthCallback: async ({ kind, searchParams }) => {
+ if (kind === 'twitter-ads') {
+ // The server binds the temporary token to the initiating user and project instead of a state cookie.
+ let replaceUrl = urls.settings('project-integrations')
+ try {
+ if (searchParams.denied) {
+ lemonToast.info('X Ads connection cancelled.')
+ } else {
+ const parsedTeamId = Number(getCookie('ph_twitter_ads_team_id'))
+ const projectId =
+ Number.isFinite(parsedTeamId) && parsedTeamId > 0
+ ? String(parsedTeamId)
+ : String(values.currentProjectId)
+ const integration = await integrationsCreate(projectId, {
+ kind,
+ config: {
+ oauth_token: searchParams.oauth_token,
+ oauth_verifier: searchParams.oauth_verifier,
+ },
+ })
+ const nextUrl =
+ typeof integration.config === 'object' &&
+ integration.config !== null &&
+ 'next' in integration.config &&
+ typeof integration.config.next === 'string'
+ ? integration.config.next
+ : replaceUrl
+ const url = new URL(nextUrl, window.location.origin)
+ url.searchParams.set(OAUTH_INTEGRATION_ID_PARAM, String(integration.id))
+ replaceUrl = url.pathname + url.search + url.hash
+ actions.loadIntegrations()
+ lemonToast.success('Integration successful.')
+ }
+ } catch (e) {
+ toastApiError(e)
+ } finally {
+ router.actions.replace(replaceUrl)
+ }
+ return
+ }
+
const { state, code, error, stripe_user_id, account_id, user_id } = searchParams
const { next, token, source, server_id, team_id } = fromParamsGivenUrl(state)
const resolvedKind = kind
diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.ts
index a096b0127e37..ebf4dc8265af 100644
--- a/frontend/src/lib/integrations/utils.ts
+++ b/frontend/src/lib/integrations/utils.ts
@@ -41,6 +41,7 @@ import IconSnowflake from 'public/services/snowflake.png'
import IconStripe from 'public/services/stripe.png'
import IconTikTok from 'public/services/tiktok.png'
import IconTwilio from 'public/services/twilio.png'
+import IconTwitterAds from 'public/services/twitter_ads.png'
import IconVercel from 'public/services/vercel.png'
import IconYouTubeAnalytics from 'public/services/youtube_analytics.png'
@@ -111,6 +112,7 @@ export const ICONS: Record<IntegrationKind, any> = {
twilio: IconTwilio,
clickup: IconClickUp,
'reddit-ads': IconReddit,
+ 'twitter-ads': IconTwitterAds,
databricks: IconDatabricks,
'tiktok-ads': IconTikTok,
'bing-ads': IconBingAds,
@@ -156,6 +158,8 @@ export const getIntegrationNameFromKind = (kind: string): string => {
return 'LinkedIn Ads'
case 'reddit-ads':
return 'Reddit Ads'
+ case 'twitter-ads':
+ return 'X Ads'
case 'tiktok-ads':
return 'TikTok Ads'
case 'bing-ads':
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index d29c74b9f38c..22a282afe789 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -30573,7 +30573,8 @@
"aws-redshift",
"s3-compatible",
"snowflake",
- "youtube-analytics"
+ "youtube-analytics",
+ "twitter-ads"
],
"type": "string"
},
diff --git a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
index b6e73ee2e112..2a0bd50c46d0 100644
--- a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts
@@ -57,6 +57,7 @@ export interface organizationIntegrationsLogicValues {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
)[]
@@ -134,6 +135,7 @@ export interface organizationIntegrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
}[],
@@ -193,6 +195,7 @@ export interface organizationIntegrationsLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
}[]
@@ -250,6 +253,7 @@ export interface organizationIntegrationsLogicMeta {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
)[]
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index c0f09c1f035a..84fb1f98d633 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5638,6 +5638,7 @@ export const INTEGRATION_KINDS = [
's3-compatible',
'snowflake',
'youtube-analytics',
+ 'twitter-ads',
] as const
export type IntegrationKind = (typeof INTEGRATION_KINDS)[number]
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index baa702417cad..8e95d3af37b1 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -105,6 +105,7 @@ from posthog.models.integration import (
resolve_aliased_oauth_kind,
)
from posthog.models.integration.github_audit import GitHubAudit
+from posthog.models.integration.twitter_ads import TwitterAdsIntegration
from posthog.models.user_integration import UserIntegration
from posthog.permissions import (
AccessControlPermission,
@@ -1099,6 +1100,11 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
raise ValidationError(str(e))
return instance
+ elif validated_data["kind"] == "twitter-ads":
+ return TwitterAdsIntegration.integration_from_callback(
+ team_id, request.user, validated_data.get("config") or {}
+ )
+
elif validated_data["kind"] in OauthIntegration.supported_kinds:
# Stripe marketplace installs redirect to /integrations/stripe/callback without
# a PostHog-minted CSRF state token — Stripe drives the OAuth flow itself.
@@ -1533,6 +1539,18 @@ class IntegrationViewSet(
next = request.GET.get("next", "")
token = os.urandom(33).hex()
+ if kind == "twitter-ads":
+ response = redirect(TwitterAdsIntegration.authorize_url(self.team_id, cast(User, request.user).id, next))
+ response.set_cookie(
+ "ph_twitter_ads_team_id",
+ str(self.team_id),
+ max_age=600,
+ samesite="Lax",
+ secure=request.is_secure(),
+ httponly=False,
+ )
+ return response
+
if kind in OauthIntegration.supported_kinds:
region: str | None = None
scopes: list[str] | None = None
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 72da7a9c2daf..f4e78a76ee4b 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -2,6 +2,7 @@ import hmac
import json
import time
import hashlib
+from contextlib import nullcontext
from datetime import timedelta
from typing import Any, cast
from urllib.parse import quote, urlencode
@@ -27,6 +28,7 @@ from fakeredis import FakeConnection
from parameterized import parameterized
from prometheus_client import REGISTRY
from redis.exceptions import RedisError
+from requests_oauthlib import OAuth1
from rest_framework import status
from rest_framework.exceptions import ValidationError
from slack_sdk.errors import SlackApiError
@@ -63,6 +65,7 @@ from posthog.models.integration import (
github_account_type,
)
from posthog.models.integration.github_audit import GitHubAudit, GitHubAuditPayload
+from posthog.models.integration.twitter_ads import TwitterAdsIntegration
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
@@ -3087,6 +3090,150 @@ class TestGitHubIntegrationCreatedReporting:
assert mock_report.call_count == 1
+class TestTwitterAdsIntegration:
+ @pytest.fixture(autouse=True)
+ def setup_environment(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+
+ @pytest.mark.parametrize("key,secret", [("", "secret"), ("key", ""), ("", "")])
+ def test_twitter_authorize_requires_app_settings(self, client: HttpClient, key: str, secret: str) -> None:
+ client.force_login(self.user)
+ with (
+ override_settings(TWITTER_ADS_CONSUMER_KEY=key, TWITTER_ADS_CONSUMER_SECRET=secret),
+ patch("posthog.models.integration.twitter_ads.requests.post") as http,
+ ):
+ response = client.get(f"/api/environments/{self.team.pk}/integrations/authorize/", {"kind": "twitter-ads"})
+ assert response.status_code == 400
+ assert response.json()["detail"] == "Kind not configured"
+ http.assert_not_called()
+
+ @override_settings(TWITTER_ADS_CONSUMER_KEY="fake-key", TWITTER_ADS_CONSUMER_SECRET="fake-secret")
+ @patch("posthog.models.integration.twitter_ads.requests.post")
+ def test_twitter_authorize_binds_and_callback_consumes_grant(self, http: MagicMock, client: HttpClient) -> None:
+ client.force_login(self.user)
+ request_token = MagicMock(
+ status_code=200,
+ text="oauth_token=fake-temporary&oauth_token_secret=fake-temporary-secret&oauth_callback_confirmed=true",
+ )
+ access_token = MagicMock(
+ status_code=200,
+ text="oauth_token=fake-access&oauth_token_secret=fake-access-secret&user_id=123&screen_name=example_ads",
+ )
+ http.side_effect = [request_token, access_token]
+ next_url = "/data-warehouse/new?source=TwitterAds"
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/authorize/", {"kind": "twitter-ads", "next": next_url}
+ )
+ assert response.status_code == 302
+ assert response.headers["Location"] == "https://api.x.com/oauth/authorize?oauth_token=fake-temporary"
+ assert cache.get(TwitterAdsIntegration.binding_key("fake-temporary")) == {
+ "oauth_token_secret": "fake-temporary-secret",
+ "team_id": self.team.pk,
+ "user_id": self.user.pk,
+ "next": next_url,
+ }
+ auth = http.call_args.kwargs["auth"]
+ assert isinstance(auth, OAuth1)
+ assert auth.client.callback_uri.endswith("/integrations/twitter-ads/callback")
+ payload = {
+ "kind": "twitter-ads",
+ "config": {"oauth_token": "fake-temporary", "oauth_verifier": "fake-verifier"},
+ }
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations/", payload, content_type="application/json"
+ )
+ assert response.status_code == 201
+ integration = Integration.objects.get(pk=response.json()["id"])
+ assert integration.integration_id == "123"
+ assert integration.config == {"screen_name": "example_ads", "user_id": "123", "next": next_url}
+ assert integration.sensitive_config == {
+ "oauth_token": "fake-access",
+ "oauth_token_secret": "fake-access-secret",
+ }
+ assert "fake-access" not in response.content.decode()
+ assert "fake-temporary" not in response.content.decode()
+ assert cache.get(TwitterAdsIntegration.binding_key("fake-temporary")) is None
+ auth = http.call_args.kwargs["auth"]
+ assert auth.client.resource_owner_key == "fake-temporary"
+ assert auth.client.resource_owner_secret == "fake-temporary-secret"
+ assert auth.client.verifier == "fake-verifier"
+ repeated = client.post(
+ f"/api/environments/{self.team.pk}/integrations/", payload, content_type="application/json"
+ )
+ assert repeated.status_code == 400
+ assert http.call_count == 2
+
+ @pytest.mark.parametrize(
+ "binding_case", ["different-user", "different-team", "unknown", "expired", "concurrent-use"]
+ )
+ @override_settings(TWITTER_ADS_CONSUMER_KEY="fake-key", TWITTER_ADS_CONSUMER_SECRET="fake-secret")
+ def test_twitter_callback_rejects_unbound_tokens(self, client: HttpClient, binding_case: str) -> None:
+ client.force_login(self.user)
+ key = TwitterAdsIntegration.binding_key("fake-unbound")
+ cache.delete(key)
+ binding = {"oauth_token_secret": "fake-secret", "team_id": self.team.pk, "user_id": self.user.pk, "next": ""}
+ if binding_case == "different-user":
+ other = User.objects.create_and_join(self.organization, "[email protected]", "test")
+ binding["user_id"] = other.pk
+ elif binding_case == "different-team":
+ other_team = Team.objects.create(organization=self.organization, name="Other project")
+ binding["team_id"] = other_team.pk
+ if binding_case != "unknown":
+ cache.set(key, binding, timeout=0 if binding_case == "expired" else 600)
+ with (
+ patch("posthog.models.integration.twitter_ads.requests.post") as http,
+ patch("posthog.models.integration.twitter_ads.cache.delete", return_value=False)
+ if binding_case == "concurrent-use"
+ else nullcontext(),
+ ):
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations/",
+ {"kind": "twitter-ads", "config": {"oauth_token": "fake-unbound", "oauth_verifier": "fake-verifier"}},
+ content_type="application/json",
+ )
+ assert response.status_code == 400
+ assert not Integration.objects.filter(team=self.team, kind="twitter-ads").exists()
+ http.assert_not_called()
+ cache.delete(key)
+
+ @pytest.mark.parametrize("next_url", ["https://example.com/", "//example.com/", "/\\example.com/"])
+ @override_settings(TWITTER_ADS_CONSUMER_KEY="fake-key", TWITTER_ADS_CONSUMER_SECRET="fake-secret")
+ def test_twitter_authorize_rejects_external_next_url(self, client: HttpClient, next_url: str) -> None:
+ client.force_login(self.user)
+ with patch("posthog.models.integration.twitter_ads.requests.post") as http:
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/authorize/", {"kind": "twitter-ads", "next": next_url}
+ )
+ assert response.status_code == 400
+ http.assert_not_called()
+
+ @pytest.mark.parametrize("provider_response", ["denied", "missing-secret", "unconfirmed", "network"])
+ @override_settings(TWITTER_ADS_CONSUMER_KEY="fake-key", TWITTER_ADS_CONSUMER_SECRET="fake-secret")
+ def test_twitter_provider_failure_exposes_no_credentials(self, client: HttpClient, provider_response: str) -> None:
+ client.force_login(self.user)
+ payload = "oauth_token=fake-temporary&oauth_token_secret=fake-secret&oauth_callback_confirmed=true"
+ if provider_response == "missing-secret":
+ payload = "oauth_token=fake-temporary&oauth_callback_confirmed=true"
+ elif provider_response == "unconfirmed":
+ payload = payload.replace("confirmed=true", "confirmed=false")
+ provider = requests.Response()
+ provider.status_code = 401 if provider_response == "denied" else 200
+ provider._content = payload.encode()
+ with patch(
+ "posthog.models.integration.twitter_ads.requests.post",
+ return_value=provider,
+ side_effect=requests.ConnectionError("fake-secret") if provider_response == "network" else None,
+ ):
+ response = client.get(f"/api/environments/{self.team.pk}/integrations/authorize/", {"kind": "twitter-ads"})
+ assert response.status_code == 400
+ assert "fake-secret" not in response.content.decode()
+ assert "fake-temporary" not in response.content.decode()
+
+
class TestGitHubIntegrationStateValidation:
@pytest.fixture(autouse=True)
def setup_environment(self, db):
diff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.py
index e48f49f6b986..78db7d4cdff6 100644
--- a/posthog/models/integration/model.py
+++ b/posthog/models/integration/model.py
@@ -162,6 +162,7 @@ class Integration(models.Model):
POSTGRESQL = "postgresql"
POSTHOG = "posthog"
REDDIT_ADS = "reddit-ads"
+ TWITTER_ADS = "twitter-ads"
RESEND = "resend"
S3_COMPATIBLE = "s3-compatible"
SALESFORCE = "salesforce"
@@ -214,6 +215,8 @@ class Integration(models.Model):
@property
def display_name(self) -> str:
+ if self.kind == "twitter-ads":
+ return self.config.get("screen_name") or self.integration_id
if self.kind == "pinterest-ads":
# Pinterest's OAuth username is an opaque hash, so prefer the business name when there is one.
return self.config.get("business_name") or self.config.get("username") or self.integration_id
diff --git a/posthog/models/integration/twitter_ads.py b/posthog/models/integration/twitter_ads.py
new file mode 100644
index 000000000000..bdf611840247
--- /dev/null
+++ b/posthog/models/integration/twitter_ads.py
@@ -0,0 +1,121 @@
+import hashlib
+from typing import TYPE_CHECKING
+from urllib.parse import parse_qs, urlencode
+
+from django.conf import settings
+from django.core.cache import cache
+from django.utils.http import url_has_allowed_host_and_scheme
+
+import requests
+from requests_oauthlib import OAuth1
+from rest_framework.exceptions import ValidationError
+
+from posthog.models.integration.model import Integration
+from posthog.models.integration.oauth import OauthIntegration
+
+if TYPE_CHECKING:
+ from posthog.models.user import User
+
+
+class TwitterAdsIntegration:
+ binding_ttl = 600
+
+ @staticmethod
+ def binding_key(token: str) -> str:
+ return f"twitter_ads_oauth:{hashlib.sha256(token.encode()).hexdigest()}"
+
+ @staticmethod
+ def require_configured() -> None:
+ if not settings.TWITTER_ADS_CONSUMER_KEY or not settings.TWITTER_ADS_CONSUMER_SECRET:
+ raise ValidationError("Kind not configured")
+
+ @staticmethod
+ def _exchange(endpoint: str, auth: OAuth1, required: tuple[str, ...]) -> dict[str, str]:
+ try:
+ response = requests.post(
+ f"https://api.x.com/oauth/{endpoint}", auth=auth, timeout=30, allow_redirects=False
+ )
+ response.raise_for_status()
+ if response.status_code != 200:
+ raise ValueError("Unexpected OAuth response")
+ values = parse_qs(response.text)
+ result = {key: value[0] for key, value in values.items() if len(value) == 1}
+ if not all(result.get(key) for key in required):
+ raise ValueError("Incomplete OAuth response")
+ return result
+ except (requests.RequestException, ValueError):
+ raise ValidationError(
+ "X could not authorize this connection. Please connect your X Ads account again."
+ ) from None
+
+ @classmethod
+ def authorize_url(cls, team_id: int, user_id: int, next_url: str) -> str:
+ cls.require_configured()
+ if next_url and (
+ not next_url.startswith("/") or not url_has_allowed_host_and_scheme(next_url, allowed_hosts=set())
+ ):
+ raise ValidationError("Invalid next URL")
+ tokens = cls._exchange(
+ "request_token",
+ OAuth1(
+ settings.TWITTER_ADS_CONSUMER_KEY,
+ settings.TWITTER_ADS_CONSUMER_SECRET,
+ callback_uri=OauthIntegration.redirect_uri("twitter-ads"),
+ ),
+ ("oauth_token", "oauth_token_secret", "oauth_callback_confirmed"),
+ )
+ if tokens["oauth_callback_confirmed"] != "true":
+ raise ValidationError("X did not confirm the callback URL. Please try connecting again.")
+ cache.set(
+ cls.binding_key(tokens["oauth_token"]),
+ {
+ "oauth_token_secret": tokens["oauth_token_secret"],
+ "team_id": team_id,
+ "user_id": user_id,
+ "next": next_url,
+ },
+ timeout=cls.binding_ttl,
+ )
+ return f"https://api.x.com/oauth/authorize?{urlencode({'oauth_token': tokens['oauth_token']})}"
+
+ @classmethod
+ def integration_from_callback(cls, team_id: int, user: "User", config: dict[str, object]) -> Integration:
+ cls.require_configured()
+ token = config.get("oauth_token")
+ verifier = config.get("oauth_verifier")
+ if not isinstance(token, str) or not token or not isinstance(verifier, str) or not verifier:
+ raise ValidationError("X authorization token and verifier are required")
+ key = cls.binding_key(token)
+ binding = cache.get(key)
+ if not binding or binding["team_id"] != team_id or binding["user_id"] != user.id:
+ raise ValidationError(
+ "X authorization expired or does not belong to this user and project. Please connect again."
+ )
+ # Atomic deletion lets only one callback exchange this grant, even if requests arrive together.
+ if not cache.delete(key):
+ raise ValidationError("X authorization has already been used. Please connect again.")
+ tokens = cls._exchange(
+ "access_token",
+ OAuth1(
+ settings.TWITTER_ADS_CONSUMER_KEY,
+ settings.TWITTER_ADS_CONSUMER_SECRET,
+ token,
+ binding["oauth_token_secret"],
+ verifier=verifier,
+ ),
+ ("oauth_token", "oauth_token_secret", "user_id", "screen_name"),
+ )
+ integration, _ = Integration.objects.update_or_create(
+ team_id=team_id,
+ kind="twitter-ads",
+ integration_id=tokens["user_id"],
+ defaults={
+ "created_by": user,
+ "config": {"screen_name": tokens["screen_name"], "user_id": tokens["user_id"], "next": binding["next"]},
+ "sensitive_config": {
+ "oauth_token": tokens["oauth_token"],
+ "oauth_token_secret": tokens["oauth_token_secret"],
+ },
+ },
+ )
+ return integration
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 31eddde64776..17a7569f2fb8 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1773,6 +1773,7 @@ class IntegrationKind(StrEnum):
S3_COMPATIBLE = "s3-compatible"
SNOWFLAKE = "snowflake"
YOUTUBE_ANALYTICS = "youtube-analytics"
+ TWITTER_ADS = "twitter-ads"
class IntervalType(StrEnum):
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 69bfa2dbc18d..8d297bbfab73 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -125,6 +125,9 @@ BING_ADS_CLIENT_ID_FALLBACK = get_from_env("BING_ADS_CLIENT_ID_FALLBACK", "")
BING_ADS_CLIENT_SECRET_FALLBACK = get_from_env("BING_ADS_CLIENT_SECRET_FALLBACK", "")
BING_ADS_DEVELOPER_TOKEN = get_from_env("BING_ADS_DEVELOPER_TOKEN", "")
+TWITTER_ADS_CONSUMER_KEY = get_from_env("TWITTER_ADS_CONSUMER_KEY", "")
+TWITTER_ADS_CONSUMER_SECRET = get_from_env("TWITTER_ADS_CONSUMER_SECRET", "")
+
REDDIT_ADS_CLIENT_ID = get_from_env("REDDIT_ADS_CLIENT_ID", "")
REDDIT_ADS_CLIENT_SECRET = get_from_env("REDDIT_ADS_CLIENT_SECRET", "")
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 788e32d43479..9726233d2198 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -5293,6 +5293,7 @@ export const IntegrationKindApi = {
S3Compatible: 's3-compatible',
Snowflake: 'snowflake',
YoutubeAnalytics: 'youtube-analytics',
+ TwitterAds: 'twitter-ads',
} as const
export interface ErrorTrackingExternalReferenceIntegrationApi {
diff --git a/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
index 0365b3303e7d..755d57c3fa64 100644
--- a/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
+++ b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts
@@ -157,6 +157,7 @@ export interface destinationModalLogicActions {
| 'stripe'
| 'tiktok-ads'
| 'twilio'
+ | 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
}
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index 8067ed112605..bf0652a206da 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -187,6 +187,7 @@ export interface RoleLookupResponseApi {
* * `postgresql` - Postgresql
* * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
+ * * `twitter-ads` - Twitter Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
* * `salesforce` - Salesforce
@@ -239,6 +240,7 @@ export const IntegrationKindEnumApi = {
Postgresql: 'postgresql',
Posthog: 'posthog',
RedditAds: 'reddit-ads',
+ TwitterAds: 'twitter-ads',
Resend: 'resend',
S3Compatible: 's3-compatible',
Salesforce: 'salesforce',
@@ -613,6 +615,7 @@ export interface IntegrationAccessRequestApi {
* * `postgresql` - Postgresql
* * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
+ * * `twitter-ads` - Twitter Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
* * `salesforce` - Salesforce
@@ -777,6 +780,7 @@ export type IntegrationsListParams = {
* * `postgresql` - Postgresql
* * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
+ * * `twitter-ads` - Twitter Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
* * `salesforce` - Salesforce
@@ -850,6 +854,7 @@ export const IntegrationsListKind = {
Stripe: 'stripe',
TiktokAds: 'tiktok-ads',
Twilio: 'twilio',
+ TwitterAds: 'twitter-ads',
Vercel: 'vercel',
YoutubeAnalytics: 'youtube-analytics',
} as const
diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.ts
index 5299be58a7f0..876302b4bbbf 100644
--- a/products/integrations/frontend/generated/api.zod.ts
+++ b/products/integrations/frontend/generated/api.zod.ts
@@ -98,6 +98,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
'postgresql',
'posthog',
'reddit-ads',
+ 'twitter-ads',
'resend',
's3-compatible',
'salesforce',
@@ -112,7 +113,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -158,6 +159,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
'postgresql',
'posthog',
'reddit-ads',
+ 'twitter-ads',
'resend',
's3-compatible',
'salesforce',
@@ -173,7 +175,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -219,6 +221,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
'postgresql',
'posthog',
'reddit-ads',
+ 'twitter-ads',
'resend',
's3-compatible',
'salesforce',
@@ -233,7 +236,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -286,6 +289,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
'postgresql',
'posthog',
'reddit-ads',
+ 'twitter-ads',
'resend',
's3-compatible',
'salesforce',
@@ -300,7 +304,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
config: zod.unknown().optional(),
})
@@ -401,6 +405,7 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
'postgresql',
'posthog',
'reddit-ads',
+ 'twitter-ads',
'resend',
's3-compatible',
'salesforce',
@@ -415,10 +420,10 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
'youtube-analytics',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
)
.describe(
- "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics"
+ "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics"
),
reason: zod
.string()
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 1c788aa6456c..0e3586c02589 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -4350,6 +4350,7 @@ export const IntegrationKindApi = {
S3Compatible: 's3-compatible',
Snowflake: 'snowflake',
YoutubeAnalytics: 'youtube-analytics',
+ TwitterAds: 'twitter-ads',
} as const
export interface ErrorTrackingExternalReferenceIntegrationApi {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index b0020099246f..f4db1273e692 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -758,6 +758,7 @@ the row lists both.
| twelve_labs | HTTP | requests | ✅ |
| twenty | HTTP | requests + `rest_source.RESTClient` | ✅ |
| twilio | HTTP | requests | ✅ |
+| twitter_ads | HTTP | requests | ✅ |
| tyntec_sms | HTTP | requests + `rest_source.RESTClient` | ✅ |
| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ubidots | HTTP | requests | ✅ |
@@ -1460,7 +1461,6 @@ doesn't conflict with concurrent PRs.
- trustradius
- twitch
- twitter
-- twitter_ads
- two_c2p
- tyntec_sms
- typesense
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitterads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitterads.py
index ea18a1ac2188..ac125c5ff9f5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitterads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitterads.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class TwitterAdsSourceConfig(config.Config):
- pass
+ account_id: str
+ twitter_ads_integration_id: int = config.value(converter=config.str_to_int)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/canonical_descriptions.py
new file mode 100644
index 000000000000..9a3bd5a4eed1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/canonical_descriptions.py
@@ -0,0 +1,64 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "campaigns": {
+ "description": "An X advertising campaign containing line items and funded by a funding instrument.",
+ "docs_url": "https://docs.x.com/x-ads-api/campaign-management/reference#campaigns",
+ "columns": {
+ "id": "Campaign identifier.",
+ "funding_instrument_id": "Funding instrument that supplies the campaign's budget and billing currency.",
+ "name": "Campaign name.",
+ "deleted": "Whether the campaign has been deleted.",
+ },
+ },
+ "line_items": {
+ "description": "An ad group within an X campaign, with its objective, targeting, and bid settings.",
+ "docs_url": "https://docs.x.com/x-ads-api/campaign-management/reference#line-items",
+ "columns": {
+ "id": "Line item identifier.",
+ "campaign_id": "Parent campaign identifier.",
+ "objective": "Advertising objective.",
+ },
+ },
+ "promoted_tweets": {
+ "description": "An association between an X Post and the line item that promotes it.",
+ "docs_url": "https://docs.x.com/x-ads-api/campaign-management/reference#promoted-tweets",
+ "columns": {
+ "id": "Promoted Post identifier.",
+ "tweet_id": "Identifier of the promoted Post.",
+ "line_item_id": "Line item that promotes the Post.",
+ },
+ },
+ "funding_instruments": {
+ "description": "A payment or credit arrangement funding X advertising campaigns.",
+ "docs_url": "https://docs.x.com/x-ads-api/campaign-management/reference#funding-instruments",
+ "columns": {
+ "id": "Funding instrument identifier.",
+ "currency": "ISO 4217 billing currency.",
+ "type": "Funding instrument type.",
+ },
+ },
+ "media_creatives": {
+ "description": "A media creative associated with an X advertising line item.",
+ "docs_url": "https://docs.x.com/x-ads-api/campaign-management/reference#media-creatives",
+ "columns": {"id": "Media creative identifier.", "line_item_id": "Line item that promotes the creative."},
+ },
+ **{
+ table: {
+ "description": f"Daily unsegmented X advertising metrics for a {entity}, separated by placement.",
+ "docs_url": "https://docs.x.com/x-ads-api/analytics",
+ "columns": {
+ "entity_id": f"Identifier of the {entity} whose metrics are reported.",
+ "date": "Report day in the ad account's reporting timezone.",
+ "placement": "Advertising placement for these metrics.",
+ "billed_charge_local_micro": "Billed spend in millionths of the funding instrument's currency.",
+ "currency": "ISO 4217 billing currency from the campaign's funding instrument.",
+ "impressions": "Number of times the ad was served.",
+ "clicks": "Total clicks, including favorites and other engagements.",
+ },
+ }
+ for table, entity in (("campaign_stats", "campaign"), ("line_item_stats", "line item"))
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/settings.py
new file mode 100644
index 000000000000..b057c252dbdf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/settings.py
@@ -0,0 +1,20 @@
+API_VERSION = "12"
+ENTITY_TABLES = ("campaigns", "line_items", "promoted_tweets", "funding_instruments", "media_creatives")
+STATS_TABLES = {"campaign_stats": "CAMPAIGN", "line_item_stats": "LINE_ITEM"}
+PLACEMENTS = ("ALL_ON_TWITTER", "SPOTLIGHT", "TREND")
+LOOKBACK_SECONDS = 3 * 24 * 60 * 60
+REVOKED_GRANT = "Your X Ads connection is no longer valid. Reconnect your X account, then re-enable the sync."
+ACCOUNT_ACCESS_DENIED = (
+ "The connected X account cannot access this ad account. Check its ad-account permissions, then reconnect."
+)
+MISSING_INTEGRATION = "The connected X Ads integration is missing or disconnected. Reconnect your X account."
+MISSING_APP = "The PostHog X Ads app is not configured. Contact support."
+
+PRIMARY_KEYS = {
+ **{table: ["id"] for table in ENTITY_TABLES},
+ **{table: ["entity_id", "date", "placement"] for table in STATS_TABLES},
+}
+PARTITION_KEYS = {
+ **{table: ["created_at"] for table in ENTITY_TABLES},
+ **{table: ["date"] for table in STATS_TABLES},
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/source.py
index 6652ad9d7c96..34fc40980191 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/source.py
@@ -1,16 +1,63 @@
from typing import cast
+from urllib.parse import quote
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+import requests
+
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldOauthAccountSelectConfig,
+ SourceFieldOauthConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ IntegrationAccountListingError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ incremental_field,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.twitterads import (
TwitterAdsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.settings import (
+ ACCOUNT_ACCESS_DENIED,
+ API_VERSION,
+ ENTITY_TABLES,
+ LOOKBACK_SECONDS,
+ MISSING_APP,
+ MISSING_INTEGRATION,
+ PRIMARY_KEYS,
+ REVOKED_GRANT,
+ STATS_TABLES,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.twitter_ads import (
+ TwitterAdsClient,
+ TwitterAdsResumeConfig,
+ twitter_ads_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TwitterAdsSource(SimpleSource[TwitterAdsSourceConfig]):
+class TwitterAdsSource(ResumableSource[TwitterAdsSourceConfig, TwitterAdsResumeConfig], OAuthMixin):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = "https://docs.x.com/x-ads-api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TWITTERADS
@@ -20,9 +67,135 @@ class TwitterAdsSource(SimpleSource[TwitterAdsSourceConfig]):
return SourceConfig(
name=ExternalDataSourceType.TWITTERADS,
category=DataWarehouseSourceCategory.ADVERTISING,
- keywords=["x ads"],
- label="Twitter Ads",
+ keywords=["x ads", "twitter ads"],
+ label="X Ads",
iconPath="/static/services/twitter_ads.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/twitter-ads",
+ releaseStatus=ReleaseStatus.ALPHA,
+ # Hidden until PostHog's X app is approved for Ads API access and its keys are deployed.
+ featureFlag="dwh-twitter-ads",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldOauthConfig(
+ name="twitter_ads_integration_id", label="X Ads account", required=True, kind="twitter-ads"
+ ),
+ SourceFieldOauthAccountSelectConfig(
+ name="account_id",
+ label="Ad account",
+ integrationField="twitter_ads_integration_id",
+ integrationKind="twitter-ads",
+ required=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": REVOKED_GRANT,
+ "403 Client Error": ACCOUNT_ACCESS_DENIED,
+ "Integration not found": MISSING_INTEGRATION,
+ "Missing integration ID": MISSING_INTEGRATION,
+ MISSING_INTEGRATION: MISSING_INTEGRATION,
+ MISSING_APP: MISSING_APP,
+ }
+
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> list[IntegrationAccount]:
+ try:
+ client = TwitterAdsClient(self.get_oauth_integration(integration_id, team_id))
+ return [
+ IntegrationAccount(value=row["id"], display_name=row.get("name") or row["id"], secondary_text=row["id"])
+ for page in client.pages("accounts")
+ for row in page["data"]
+ if not row.get("deleted")
+ ]
+ except ValueError as error:
+ raise IntegrationAccountListingError(
+ MISSING_APP if str(error) == MISSING_APP else MISSING_INTEGRATION
+ ) from None
+ except requests.HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status in (401, 403):
+ raise IntegrationAccountListingError(
+ REVOKED_GRANT if status == 401 else ACCOUNT_ACCESS_DENIED
+ ) from None
+ raise
+ except requests.RequestException:
+ raise IntegrationAccountListingError("Could not reach X Ads. Please try again.") from None
+
+ def validate_credentials(
+ self,
+ config: TwitterAdsSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ try:
+ client = TwitterAdsClient(
+ self.get_oauth_integration(config.twitter_ads_integration_id, team_id), api_version or API_VERSION
+ )
+ client.get(f"accounts/{quote(config.account_id, safe='')}", {"with_deleted": "true"})
+ return True, None
+ except ValueError as error:
+ return False, MISSING_APP if str(error) == MISSING_APP else MISSING_INTEGRATION
+ except requests.HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ return (
+ False,
+ REVOKED_GRANT
+ if status == 401
+ else ACCOUNT_ACCESS_DENIED
+ if status == 403
+ else "X Ads could not validate this ad account. Please try again.",
+ )
+ except requests.RequestException:
+ return False, "Could not reach X Ads. Please try again."
+
+ def get_schemas(
+ self,
+ config: TwitterAdsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return [
+ SourceSchema(
+ name=name,
+ supports_incremental=name in STATS_TABLES,
+ supports_append=False,
+ incremental_fields=[incremental_field("date")] if name in STATS_TABLES else [],
+ default_incremental_lookback_seconds=LOOKBACK_SECONDS if name in STATS_TABLES else None,
+ detected_primary_keys=PRIMARY_KEYS[name],
+ )
+ for name in (*ENTITY_TABLES, *STATS_TABLES)
+ if names is None or name in names
+ ]
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TwitterAdsResumeConfig]:
+ return ResumableSourceManager(inputs, TwitterAdsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TwitterAdsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TwitterAdsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ client = TwitterAdsClient(
+ self.get_oauth_integration(config.twitter_ads_integration_id, inputs.team_id),
+ inputs.api_version or API_VERSION,
+ )
+ return twitter_ads_source(
+ client,
+ config.account_id,
+ inputs.schema_name,
+ resumable_source_manager,
+ inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads.py
new file mode 100644
index 000000000000..5278c2b99ffd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads.py
@@ -0,0 +1,200 @@
+import json
+from collections.abc import Iterable
+from datetime import (
+ UTC,
+ date,
+ datetime,
+ timedelta,
+ timezone as fixed_timezone,
+)
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+from zoneinfo import ZoneInfo
+
+import pytest
+import time_machine
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+import requests
+from requests_oauthlib import OAuth1
+
+from posthog.models.integration.model import Integration
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.settings import PLACEMENTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.twitter_ads import (
+ TwitterAdsClient,
+ TwitterAdsResumeConfig,
+ twitter_ads_source,
+)
+
+
+def client() -> TwitterAdsClient:
+ integration = Integration(
+ kind="twitter-ads", sensitive_config={"oauth_token": "fake-access", "oauth_token_secret": "fake-secret"}
+ )
+ with override_settings(
+ TWITTER_ADS_CONSUMER_KEY="fake-consumer", TWITTER_ADS_CONSUMER_SECRET="fake-consumer-secret"
+ ):
+ return TwitterAdsClient(integration)
+
+
+def manager() -> MagicMock:
+ manager = MagicMock()
+ manager.load_state.return_value = None
+ return manager
+
+
+def response(payload: dict) -> requests.Response:
+ result = requests.Response()
+ result.status_code = 200
+ result._content = json.dumps(payload).encode()
+ return result
+
+
+def sync_items(resource: SourceResponse) -> Iterable[Any]:
+ return cast(Iterable[Any], resource.items())
+
+
+def request_url(request: requests.PreparedRequest) -> str:
+ assert isinstance(request.url, str)
+ return request.url
+
+
+def test_signing_pagination_and_resume(client: TwitterAdsClient, manager: MagicMock) -> None:
+ with patch.object(
+ client.session,
+ "send",
+ side_effect=[
+ response({"data": [{"id": "one"}], "next_cursor": "next-page"}),
+ response({"data": [{"id": "two", "deleted": True}], "next_cursor": None}),
+ ],
+ ) as send:
+ resource = twitter_ads_source(client, "account", "campaigns", manager, None)
+ assert list(sync_items(resource)) == [[{"id": "one"}], [{"id": "two", "deleted": True}]]
+ requests_sent = [call.args[0] for call in send.call_args_list]
+ assert isinstance(client.session.auth, OAuth1)
+ assert all(b"oauth_signature=" in request.headers["Authorization"] for request in requests_sent)
+ assert all(parse_qs(urlparse(request_url(request)).query)["with_deleted"] == ["true"] for request in requests_sent)
+ assert parse_qs(urlparse(request_url(requests_sent[1])).query)["cursor"] == ["next-page"]
+ assert manager.save_state.call_args_list[0].args[0] == TwitterAdsResumeConfig(cursor="next-page")
+ assert manager.save_state.call_args_list[1].args[0].complete
+ manager.load_state.return_value = TwitterAdsResumeConfig(cursor="saved-page")
+ with patch.object(client.session, "send", return_value=response({"data": [], "next_cursor": None})) as send:
+ list(sync_items(resource))
+ assert parse_qs(urlparse(request_url(send.call_args.args[0])).query)["cursor"] == ["saved-page"]
+ manager.load_state.return_value = TwitterAdsResumeConfig(complete=True)
+ with patch.object(client.session, "send") as send:
+ assert list(sync_items(resource)) == []
+ send.assert_not_called()
+
+
[email protected]("table", ["campaign_stats", "line_item_stats"])
[email protected]("incremental_since", [None, date(2025, 10, 30)])
+def test_stats_limits_daily_rows_currency_and_dst(
+ client: TwitterAdsClient, manager: MagicMock, table: str, incremental_since: date | None
+) -> None:
+ account_timezone = ZoneInfo("America/Los_Angeles")
+ timezone = fixed_timezone(timedelta(hours=-8))
+ calls = []
+ campaigns = [{"id": f"campaign-{i:02}", "funding_instrument_id": "funding"} for i in range(21)]
+ line_items = [{"id": f"line-{i:02}", "campaign_id": campaign["id"]} for i, campaign in enumerate(campaigns)]
+
+ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:
+ url = request_url(request)
+ params = parse_qs(urlparse(url).query)
+ path = urlparse(url).path
+ if path.endswith("/funding_instruments"):
+ return response({"data": [{"id": "funding", "currency": "EUR"}]})
+ if path.endswith("/campaigns"):
+ return response({"data": campaigns})
+ if path.endswith("/line_items"):
+ return response({"data": line_items})
+ if "/stats/" not in path:
+ return response({"data": {"timezone": account_timezone.key, "created_at": "2025-10-25T10:00:00Z"}})
+ start = datetime.fromisoformat(params["start_time"][0]).astimezone(timezone)
+ end = datetime.fromisoformat(params["end_time"][0]).astimezone(timezone)
+ ids = params["entity_ids"][0].split(",")
+ assert len(ids) <= 20
+ assert end.astimezone(UTC) - start.astimezone(UTC) <= timedelta(days=7)
+ assert params["start_time"][0].endswith("T08:00:00Z")
+ assert params["end_time"][0].endswith("T08:00:00Z")
+ assert start.hour == end.hour == 0
+ assert start.minute == end.minute == 0
+ assert params["granularity"] == ["DAY"]
+ assert params["metric_groups"] == ["ENGAGEMENT,BILLING"]
+ assert params["entity"] == ["CAMPAIGN" if table == "campaign_stats" else "LINE_ITEM"]
+ days = (end.date() - start.date()).days
+ calls.append((start.date(), end.date(), params["placement"][0], ids))
+ return response(
+ {
+ "data": [
+ {
+ "id": entity_id,
+ "id_data": [
+ {
+ "segment": None,
+ "metrics": {
+ "impressions": list(range(days)),
+ "clicks": [2] * days,
+ "billed_charge_local_micro": [1000000] * days,
+ },
+ }
+ ],
+ }
+ for entity_id in ids
+ ]
+ }
+ )
+
+ with (
+ time_machine.travel("2025-11-10T20:00:00Z", tick=False),
+ patch.object(client.session, "send", side_effect=send),
+ ):
+ resource = twitter_ads_source(client, "account", table, manager, incremental_since)
+ rows = [row for page in sync_items(resource) for row in page]
+ start = incremental_since or date(2025, 10, 25)
+ assert len(rows) == 21 * (date(2025, 11, 10) - start).days * len(PLACEMENTS)
+ assert len({(row["entity_id"], row["date"], row["placement"]) for row in rows}) == len(rows)
+ assert {row["currency"] for row in rows} == {"EUR"}
+ assert {row["billed_charge_local_micro"] for row in rows} == {1000000}
+ assert {row["clicks"] for row in rows} == {2}
+ assert all(row["account_id"] == "account" for row in rows)
+ assert min(row["date"] for row in rows) == start
+ assert max(row["date"] for row in rows) == date(2025, 11, 9)
+ assert {call[2] for call in calls} == set(PLACEMENTS)
+ assert resource.primary_keys == ["entity_id", "date", "placement"]
+ assert resource.partition_keys == ["date"]
+ assert resource.sort_mode is None
+ assert manager.save_state.call_args.args[0].complete
+ first_checkpoint = manager.save_state.call_args_list[0].args[0]
+ manager.load_state.return_value = first_checkpoint
+ with (
+ time_machine.travel("2025-11-15T20:00:00Z", tick=False),
+ patch.object(client.session, "send", side_effect=send),
+ ):
+ resumed = [row for page in sync_items(resource) for row in page]
+ assert min(row["date"] for row in resumed) == date.fromisoformat(first_checkpoint.next_date)
+ assert max(row["date"] for row in resumed) == date(2025, 11, 9)
+
+
+def test_daily_null_metrics_are_not_shifted(client: TwitterAdsClient) -> None:
+ rows = client.stats_rows(
+ {
+ "data": [
+ {"id": "id", "id_data": [{"segment": None, "metrics": {"impressions": [10, None, 30], "clicks": None}}]}
+ ]
+ },
+ date(2025, 1, 1),
+ date(2025, 1, 4),
+ "ALL_ON_TWITTER",
+ {"id": "USD"},
+ "account",
+ )
+ assert [row["impressions"] for row in rows] == [10, None, 30]
+ assert [row["date"] for row in rows] == [date(2025, 1, 1), date(2025, 1, 2), date(2025, 1, 3)]
+ assert all(row["clicks"] is None for row in rows)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads_source.py
new file mode 100644
index 000000000000..9adb5de7f302
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads_source.py
@@ -0,0 +1,132 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+import requests
+
+from posthog.models.integration.model import Integration
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.twitterads import (
+ TwitterAdsSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.settings import (
+ ACCOUNT_ACCESS_DENIED,
+ MISSING_APP,
+ MISSING_INTEGRATION,
+ REVOKED_GRANT,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.source import TwitterAdsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.twitter_ads import (
+ TwitterAdsClient,
+ twitter_ads_source,
+)
+
+
+ "status,message",
+ [
+ (200, None),
+ (401, REVOKED_GRANT),
+ (403, ACCOUNT_ACCESS_DENIED),
+ (503, "X Ads could not validate this ad account. Please try again."),
+ ],
+)
+@override_settings(TWITTER_ADS_CONSUMER_KEY="fake-key", TWITTER_ADS_CONSUMER_SECRET="fake-secret")
+def test_validate_account_access_and_error_mapping(status: int, message: str | None) -> None:
+ integration = Integration(
+ kind="twitter-ads", sensitive_config={"oauth_token": "fake-access", "oauth_token_secret": "fake-secret"}
+ )
+ http_response = requests.Response()
+ http_response.status_code = status
+ http_response._content = b'{"data": {}}'
+ http_response.url = "https://ads-api.x.com/12/accounts/account"
+ source = TwitterAdsSource()
+ with (
+ patch.object(source, "get_oauth_integration", return_value=integration),
+ patch("requests.Session.send", return_value=http_response),
+ ):
+ assert source.validate_credentials(
+ TwitterAdsSourceConfig(account_id="account", twitter_ads_integration_id=1), 1
+ ) == (status == 200, message)
+ if status in (401, 403):
+ with pytest.raises(requests.HTTPError) as error:
+ http_response.raise_for_status()
+ assert any(
+ pattern in str(error.value) and text == message
+ for pattern, text in source.get_non_retryable_errors().items()
+ )
+ with (
+ patch.object(source, "get_oauth_integration", return_value=integration),
+ patch("requests.Session.send", return_value=http_response),
+ pytest.raises(IntegrationAccountListingError, match=message),
+ ):
+ source.get_oauth_accounts(1, 1)
+
+
[email protected]("case", ["missing-integration", "missing-token", "wrong-kind", "missing-app", "network"])
+@override_settings(TWITTER_ADS_CONSUMER_KEY="fake-key", TWITTER_ADS_CONSUMER_SECRET="fake-secret")
+def test_unusable_connection_has_actionable_message(case: str) -> None:
+ integration = Integration(
+ kind="twitter-ads", sensitive_config={"oauth_token": "fake-access", "oauth_token_secret": "fake-secret"}
+ )
+ source = TwitterAdsSource()
+ expected = MISSING_INTEGRATION
+ if case == "missing-token":
+ integration.sensitive_config = {}
+ if case == "wrong-kind":
+ integration.kind = "reddit-ads"
+ if case == "missing-app":
+ expected = MISSING_APP
+ if case == "network":
+ expected = "Could not reach X Ads. Please try again."
+ with (
+ patch.object(
+ source,
+ "get_oauth_integration",
+ return_value=integration,
+ side_effect=ValueError("Integration not found") if case == "missing-integration" else None,
+ ),
+ patch("requests.Session.send", side_effect=requests.ConnectionError("unreachable")),
+ override_settings(TWITTER_ADS_CONSUMER_KEY="" if case == "missing-app" else "fake-key"),
+ ):
+ assert source.validate_credentials(
+ TwitterAdsSourceConfig(account_id="account", twitter_ads_integration_id=1), 1
+ ) == (False, expected)
+ with pytest.raises(IntegrationAccountListingError, match=expected):
+ source.get_oauth_accounts(1, 1)
+
+
+def test_account_listing_preserves_names_and_omits_deleted() -> None:
+ source = TwitterAdsSource()
+ with (
+ patch.object(source, "get_oauth_integration", return_value=MagicMock()),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.source.TwitterAdsClient"
+ ) as client,
+ ):
+ client.return_value.pages.return_value = iter(
+ [
+ {"data": [{"id": "one", "name": "Example Ads"}]},
+ {"data": [{"id": "two", "deleted": True}, {"id": "three"}]},
+ ]
+ )
+ accounts = source.get_oauth_accounts(1, 1)
+ assert [(account.value, account.display_name) for account in accounts] == [
+ ("one", "Example Ads"),
+ ("three", "three"),
+ ]
+
+
+@override_settings(TWITTER_ADS_CONSUMER_KEY="fake-key", TWITTER_ADS_CONSUMER_SECRET="fake-secret")
+def test_unsupported_version_and_unknown_table_fail_before_http() -> None:
+ integration = Integration(
+ kind="twitter-ads", sensitive_config={"oauth_token": "fake-access", "oauth_token_secret": "fake-secret"}
+ )
+ with pytest.raises(ValueError, match="Unsupported X Ads API version"):
+ TwitterAdsClient(integration, "11")
+ with pytest.raises(ValueError, match="Unknown X Ads table"):
+ twitter_ads_source(TwitterAdsClient(integration), "account", "unknown", MagicMock(), None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/twitter_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/twitter_ads.py
new file mode 100644
index 000000000000..c1d395848217
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/twitter_ads.py
@@ -0,0 +1,215 @@
+from collections.abc import Iterator
+from datetime import (
+ UTC,
+ date,
+ datetime,
+ time,
+ timedelta,
+ timezone as fixed_timezone,
+)
+from typing import Any
+from urllib.parse import quote
+from zoneinfo import ZoneInfo
+
+from django.conf import settings
+
+from requests_oauthlib import OAuth1
+
+from posthog.dataclasses import frozen
+from posthog.models.integration.model import Integration
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.settings import (
+ API_VERSION,
+ ENTITY_TABLES,
+ MISSING_APP,
+ MISSING_INTEGRATION,
+ PARTITION_KEYS,
+ PLACEMENTS,
+ PRIMARY_KEYS,
+ STATS_TABLES,
+)
+
+
+@frozen
+class TwitterAdsResumeConfig:
+ cursor: str | None = None
+ next_date: str | None = None
+ end_date: str | None = None
+ complete: bool = False
+
+
+class TwitterAdsClient:
+ def __init__(self, integration: Integration, api_version: str = API_VERSION) -> None:
+ if api_version != API_VERSION:
+ raise ValueError("Unsupported X Ads API version")
+ if integration.kind != "twitter-ads":
+ raise ValueError(MISSING_INTEGRATION)
+ token = integration.sensitive_config.get("oauth_token")
+ secret = integration.sensitive_config.get("oauth_token_secret")
+ if not token or not secret:
+ raise ValueError(MISSING_INTEGRATION)
+ if not settings.TWITTER_ADS_CONSUMER_KEY or not settings.TWITTER_ADS_CONSUMER_SECRET:
+ raise ValueError(MISSING_APP)
+ self.session = make_tracked_session(
+ allow_redirects=False, redact_values=(token, secret, settings.TWITTER_ADS_CONSUMER_SECRET)
+ )
+ self.session.auth = OAuth1(
+ settings.TWITTER_ADS_CONSUMER_KEY, settings.TWITTER_ADS_CONSUMER_SECRET, token, secret
+ )
+ self.base_url = f"https://ads-api.x.com/{api_version}"
+
+ def get(self, path: str, params: dict[str, str | int] | None = None) -> dict[str, Any]:
+ response = self.session.get(f"{self.base_url}/{path}", params=params, timeout=60)
+ response.raise_for_status()
+ if response.status_code != 200:
+ raise ValueError("X Ads returned an unexpected response")
+ return response.json()
+
+ def pages(self, path: str, cursor: str | None = None) -> Iterator[dict[str, Any]]:
+ while True:
+ params: dict[str, str | int] = {"count": 1000, "with_deleted": "true"}
+ if path.rsplit("/", 1)[-1] != "media_creatives":
+ params["sort_by"] = "created_at-asc"
+ if cursor:
+ params["cursor"] = cursor
+ page = self.get(path, params)
+ yield page
+ cursor = page.get("next_cursor")
+ if not cursor:
+ break
+
+ def entities(self, account_id: str, table: str) -> list[dict[str, Any]]:
+ return [row for page in self.pages(f"accounts/{quote(account_id, safe='')}/{table}") for row in page["data"]]
+
+ @staticmethod
+ def stats_rows(
+ payload: dict[str, Any],
+ start: date,
+ end: date,
+ placement: str,
+ currencies: dict[str, str],
+ account_id: str,
+ ) -> list[dict[str, Any]]:
+ rows = []
+ for entity in payload["data"]:
+ entity_id = entity["id"]
+ for daily in entity["id_data"]:
+ if daily.get("segment") is not None:
+ raise ValueError("X Ads returned segmented data for an unsegmented report")
+ metrics = daily["metrics"]
+ for offset in range((end - start).days):
+ row = {
+ key: values[offset] if isinstance(values, list) and offset < len(values) else None
+ for key, values in metrics.items()
+ }
+ for required in ("billed_charge_local_micro", "impressions", "clicks"):
+ row.setdefault(required, None)
+ rows.append(
+ {
+ **row,
+ "entity_id": entity_id,
+ "date": start + timedelta(days=offset),
+ "placement": placement,
+ "currency": currencies[entity_id],
+ "account_id": account_id,
+ }
+ )
+ return rows
+
+ def stats(
+ self,
+ account_id: str,
+ table: str,
+ manager: ResumableSourceManager[TwitterAdsResumeConfig],
+ state: TwitterAdsResumeConfig,
+ incremental_since: str | date | datetime | None,
+ ) -> Iterator[list[dict[str, Any]]]:
+ account_path = f"accounts/{quote(account_id, safe='')}"
+ account = self.get(account_path, {"with_deleted": "true"})["data"]
+ account_timezone = ZoneInfo(account["timezone"])
+ account_now = datetime.now(account_timezone)
+ # X requires the current account UTC offset even when querying historical days.
+ timezone = fixed_timezone(account_now.utcoffset() or timedelta())
+ campaigns = self.entities(account_id, "campaigns")
+ funding = {row["id"]: row["currency"] for row in self.entities(account_id, "funding_instruments")}
+ campaign_currencies = {row["id"]: funding[row["funding_instrument_id"]] for row in campaigns}
+ entities = campaigns if table == "campaign_stats" else self.entities(account_id, "line_items")
+ currencies = (
+ campaign_currencies
+ if table == "campaign_stats"
+ else {row["id"]: campaign_currencies[row["campaign_id"]] for row in entities}
+ )
+ entity_ids = sorted(row["id"] for row in entities)
+ if not entity_ids:
+ return
+ start = (
+ date.fromisoformat(str(incremental_since)[:10])
+ if incremental_since is not None
+ else datetime.fromisoformat(account["created_at"].replace("Z", "+00:00")).astimezone(timezone).date()
+ )
+ if state.next_date:
+ start = date.fromisoformat(state.next_date)
+ end = date.fromisoformat(state.end_date) if state.end_date else account_now.date()
+ while start < end:
+ window_end = min(start + timedelta(days=7), end)
+ start_time = datetime.combine(start, time.min, timezone).astimezone(UTC)
+ end_time = datetime.combine(window_end, time.min, timezone).astimezone(UTC)
+ for batch_start in range(0, len(entity_ids), 20):
+ for placement in PLACEMENTS:
+ payload = self.get(
+ f"stats/{account_path}",
+ {
+ "entity": STATS_TABLES[table],
+ "entity_ids": ",".join(entity_ids[batch_start : batch_start + 20]),
+ "start_time": start_time.isoformat().replace("+00:00", "Z"),
+ "end_time": end_time.isoformat().replace("+00:00", "Z"),
+ "granularity": "DAY",
+ "placement": placement,
+ "metric_groups": "ENGAGEMENT,BILLING",
+ },
+ )
+ rows = self.stats_rows(payload, start, window_end, placement, currencies, account_id)
+ if batch_start + 20 >= len(entity_ids) and placement == PLACEMENTS[-1]:
+ manager.save_state(
+ TwitterAdsResumeConfig(
+ next_date=window_end.isoformat(), end_date=end.isoformat(), complete=window_end == end
+ )
+ )
+ yield rows
+ start = window_end
+
+
+def twitter_ads_source(
+ client: TwitterAdsClient,
+ account_id: str,
+ table: str,
+ manager: ResumableSourceManager[TwitterAdsResumeConfig],
+ incremental_since: str | date | datetime | None,
+) -> SourceResponse:
+ if table not in ENTITY_TABLES and table not in STATS_TABLES:
+ raise ValueError("Unknown X Ads table")
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ state = manager.load_state() or TwitterAdsResumeConfig()
+ if state.complete:
+ return
+ if table in STATS_TABLES:
+ yield from client.stats(account_id, table, manager, state, incremental_since)
+ else:
+ for page in client.pages(f"accounts/{quote(account_id, safe='')}/{table}", state.cursor):
+ cursor = page.get("next_cursor")
+ manager.save_state(TwitterAdsResumeConfig(cursor=cursor, complete=not cursor))
+ yield page["data"]
+
+ return SourceResponse(
+ name=table,
+ items=items,
+ primary_keys=PRIMARY_KEYS[table],
+ partition_keys=PARTITION_KEYS[table],
+ partition_mode="datetime",
+ partition_format="month",
+ sort_mode=None,
+ )
diff --git a/pyproject.toml b/pyproject.toml
index 5473c551a528..63aa534a65a1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -213,6 +213,7 @@ dependencies = [
"limits==5.8.0",
"deltalite==0.1.9",
"posthog-hogland==0.4.1",
+ "requests-oauthlib~=2.0.0",
]
[dependency-groups]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9ca3be02176a..e7e7f5728b68 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8520,6 +8520,7 @@ export namespace Schemas {
S3Compatible: 's3-compatible',
Snowflake: 'snowflake',
YoutubeAnalytics: 'youtube-analytics',
+ TwitterAds: 'twitter-ads',
} as const;
export interface ErrorTrackingExternalReferenceIntegration {
@@ -56659,6 +56660,7 @@ export namespace Schemas {
* * `postgresql` - Postgresql
* * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
+ * * `twitter-ads` - Twitter Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
* * `salesforce` - Salesforce
@@ -56712,6 +56714,7 @@ export namespace Schemas {
Postgresql: 'postgresql',
Posthog: 'posthog',
RedditAds: 'reddit-ads',
+ TwitterAds: 'twitter-ads',
Resend: 'resend',
S3Compatible: 's3-compatible',
Salesforce: 'salesforce',
@@ -56765,6 +56768,7 @@ export namespace Schemas {
* * `postgresql` - Postgresql
* * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
+ * * `twitter-ads` - Twitter Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
* * `salesforce` - Salesforce
@@ -118125,6 +118129,7 @@ export namespace Schemas {
* * `postgresql` - Postgresql
* * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
+ * * `twitter-ads` - Twitter Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
* * `salesforce` - Salesforce
@@ -118199,6 +118204,7 @@ export namespace Schemas {
Stripe: 'stripe',
TiktokAds: 'tiktok-ads',
Twilio: 'twilio',
+ TwitterAds: 'twitter-ads',
Vercel: 'vercel',
YoutubeAnalytics: 'youtube-analytics',
} as const;
diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.ts
index 7610426b126d..bd05f3e40f07 100644
--- a/services/mcp/src/generated/integrations/api.ts
+++ b/services/mcp/src/generated/integrations/api.ts
@@ -65,12 +65,13 @@ export const IntegrationsListQueryParams = () => zod.object({
'stripe',
'tiktok-ads',
'twilio',
+ 'twitter-ads',
'vercel',
'youtube-analytics',
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `helpscout` - Helpscout\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `twitter-ads` - Twitter Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'
),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
index e5e558d0a6a2..b761489d13a0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"kind": {
- "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `helpscout` - Helpscout\n* `hubspot` - Hubspot\n* `instagram` - Instagram\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel\n* `youtube-analytics` - Youtube Analytics",
+ "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `helpscout` - Helpscout\n* `hubspot` - Hubspot\n* `instagram` - Instagram\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `twitter-ads` - Twitter Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel\n* `youtube-analytics` - Youtube Analytics",
"enum": [
"anthropic",
"apns",
@@ -50,6 +50,7 @@
"stripe",
"tiktok-ads",
"twilio",
+ "twitter-ads",
"vercel",
"youtube-analytics"
],
diff --git a/uv.lock b/uv.lock
index 0308bd2002d5..970208ec4069 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5925,6 +5925,7 @@ dependencies = [
{ name = "rapidfuzz" },
{ name = "redis" },
{ name = "requests" },
+ { name = "requests-oauthlib" },
{ name = "retry" },
{ name = "s3fs" },
{ name = "scikit-learn" },
@@ -6214,6 +6215,7 @@ requires-dist = [
{ name = "rapidfuzz", specifier = "==3.14.5" },
{ name = "redis", specifier = "==5.3.1" },
{ name = "requests", specifier = "~=2.33.0" },
+ { name = "requests-oauthlib", specifier = "~=2.0.0" },
{ name = "retry", specifier = "==0.9.2" },
{ name = "s3fs", specifier = "==2025.9.0" },
{ name = "scikit-learn", specifier = "~=1.7.0" },