:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): add an mcp tool and skill for importing push device tokens (#126229)
Daniel Marchuka7cc00fe478f
diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yamlindex 1f275257338b..b573ad669b6f 100644--- a/products/integrations/mcp/tools.yaml+++ b/products/integrations/mcp/tools.yaml@@ -167,6 +167,30 @@ tools:- created_at- created_by- config.verified+ integrations-push-tokens-create:+ operation: integrations_push_tokens_create+ enabled: true+ scopes:+ - integration:write+ - person:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Import push device tokens+ description: >+ Register existing mobile devices, for example exported from another push provider, on an APNs or Firebase+ push channel so workflows can send them push notifications. Find the channel with integrations-list: kind+ apns takes hex APNs device tokens, kind firebase takes FCM registration tokens. Expo push tokens+ (ExponentPushToken[...]) work on neither and are always rejected. Each row pairs a device token with a+ distinct_id, which must be the ID the app passes to identify, so the device lands on the person workflows+ target. A distinct ID with no person fails as unknown_person unless create_missing_persons is true; leave it+ false unless the user confirms those IDs are right. Always call with dry_run=true first: it reports every+ failing row (unknown_person, token_mismatch) without storing anything. Fix or drop those rows, then call+ again without dry_run. Send at most 1000 rows per call and at most 60 calls per minute per project; on HTTP+ 429 wait a minute and retry. Rows that fail as not_stored can be sent again. Importing the same row twice+ stores it once.+ feature_flag: workflows-push-token-import-mcpintegrations-users-retrieve:operation: integrations_users_retrieveenabled: truediff --git a/products/workflows/skills/importing-push-tokens/SKILL.md b/products/workflows/skills/importing-push-tokens/SKILL.mdnew file mode 100644index 000000000000..ff7da84fd4fb--- /dev/null+++ b/products/workflows/skills/importing-push-tokens/SKILL.md@@ -0,0 +1,46 @@+---+name: importing-push-tokens+description: 'Move existing mobile push devices from another platform (OneSignal, Braze, Customer.io, Airship, or your own Firebase backend) into a PostHog workflows push channel, so people who installed the app before the switch still get push notifications. Covers exporting device tokens and user IDs, mapping the old user ID to the PostHog distinct ID, checking the pairing with a dry run, and importing in batches. Use when asked to import, migrate, or backfill push tokens, device tokens, FCM tokens, APNs tokens, or push subscribers.'+---++# Importing push tokens from another platform++A push notification reaches a device only when PostHog knows that device's token and which person it belongs to.+The mobile SDK registers new devices by itself. Devices that installed the app before the switch stay unknown until their token is imported.++The import pairs each **device token** with a **distinct ID**.+The distinct ID has to be the ID the app passes to `identify`, so the device lands on the person a workflow targets.+A pairing that is off by one prefix or uses another platform's internal ID imports fine but never receives a push. Getting the pairing right is most of the job.++## The tools++- `integrations-list`: find the push channel. `kind` is `apns` for iOS and `firebase` for Android (and for iOS apps that send through FCM).+- `integrations-push-tokens-create`: import up to 1000 rows per call, with `dry_run` to check without storing anything.++The same import is in the app under Workflows → Channels → **Import devices**, for a person who has a CSV.++## Which token goes to which channel++| Channel kind | Token it takes | Looks like |+| ------------ | ---------------------------------- | -------------------------------------------------------------------- |+| `apns` | The APNs device token, hex encoded | 64 hex characters, for example `9f2c…e1a0` |+| `firebase` | The FCM registration token | Around 150 characters of letters, digits, `-`, `_`, often with a `:` |++- Expo tokens (`ExponentPushToken[...]`) can't be imported. They address Expo's own push service, not Apple or Google. Ask for the native APNs or FCM token instead: Expo apps can read it with `getDevicePushTokenAsync`, so the app has to start sending it to PostHog first.+- An iOS app that sends through Firebase has FCM tokens, so those go to the `firebase` channel, not `apns`.+- A row with the wrong kind of token fails as `token_mismatch`. The check rejects only shapes that cannot work, so passing it does not prove the token is live.++## Workflow++1. **Find the channel.** Call `integrations-list` and pick the `apns` or `firebase` entry for the app. If there is none, the push channel has to be set up first.+2. **Export devices from the old platform.** You need, for each device: its token, its platform, and the old platform's user ID. See [references/exporting-devices.md](references/exporting-devices.md).+3. **Map the user ID to the PostHog distinct ID.** Usually the old platform's external ID is the same value the app passes to PostHog's `identify`. Confirm it with the user, because some apps prefix IDs or identify by email in one tool and by database ID in the other. Drop devices with no user ID: an anonymous device has no person to land on.+4. **Dry run a sample.** Send 50 to 100 rows with `dry_run: true`. Read `failed`:+ - Many `unknown_person` rows mean the mapping is wrong. Stop and fix the mapping. Don't switch on `create_missing_persons` to make them pass, because that creates people nobody's app identifies.+ - `token_mismatch` rows are on the wrong channel or are Expo tokens. Split iOS and Android rows, and drop Expo tokens.+5. **Dry run everything, then import.** Send the whole set with `dry_run: true` in batches of 1000, then again without it. Keep to 60 calls per minute per project. On HTTP 429, wait a minute and send the same batch again.+6. **Handle what is left.** `not_stored` and `person_processing_disabled` rows were not saved by ingestion. Send `not_stored` rows again later. Use `create_missing_persons: true` only for `unknown_person` rows the user confirms are real people who haven't opened the new app yet.+7. **Check one person.** Look up one imported person and confirm they have a `$device_push_subscription_<app>:<hash>` property. A test push from a workflow to that person is the real proof.++Importing the same row twice stores it once, so a batch can be sent again safely.+Each stored device is one event, so a large import counts toward event usage.diff --git a/products/workflows/skills/importing-push-tokens/references/exporting-devices.md b/products/workflows/skills/importing-push-tokens/references/exporting-devices.mdnew file mode 100644index 000000000000..e3c13b21f7f4--- /dev/null+++ b/products/workflows/skills/importing-push-tokens/references/exporting-devices.md@@ -0,0 +1,24 @@+# Exporting devices from other platforms++Each platform stores the same three facts under different names: the device token, the platform, and the user ID your app gave it.+APIs and export screens change, so check the platform's current docs before relying on a field name.++| Platform | Where the devices are | Token field | User ID field |+| ---------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------ |+| OneSignal | `POST /players/csv_export` (CSV of subscriptions), or the dashboard CSV export | `identifier` (push rows only) | `external_user_id`, which you must request in `extra_fields` |+| Braze | `POST /users/export/ids` or a segment export | `push_tokens[].token`, with `push_tokens[].platform` and `app` | `external_id` |+| Customer.io | People → Export to CSV → Export other → All devices in this workspace | the device `id` | the person's `id` |+| Airship | `GET /api/channels` (paged), or `GET /api/named_users` | `push_address` | `named_user_id` |+| Firebase (own backend) | Your own database. FCM has no API that lists tokens | the token your app saved | the user ID saved next to it |++## Notes per platform++- **OneSignal**: email and SMS subscriptions come out in the same export. Keep the push rows only. Drop unsubscribed rows: `invalid_identifier` is `t`, or `notification_types` is negative. These rows can still carry a token, and an imported token can be sent to again. Also drop rows with a null token. `device_type` tells iOS from Android.+- **Braze**: a profile can hold several tokens for several apps. Keep the ones for this app and platform. An anonymous profile has no `external_id` and cannot be mapped.+- **Customer.io**: devices are listed per person, with a platform. A person identified only by email in Customer.io needs that email mapped to the distinct ID the app identifies with.+- **Airship**: a channel with a null `push_address` or no `named_user_id` cannot be imported. `device_type` is `ios` or `android`.+- **Firebase**: tokens go stale when an app is reinstalled. Prefer tokens your backend saw recently. FCM tokens go to the `firebase` channel even for iOS devices.++## Expo++Expo tokens (`ExponentPushToken[...]`) cannot be imported anywhere. They only work through Expo's push service. The app has to read the native token with `getDevicePushTokenAsync` and register it through the PostHog SDK, which happens as people open the updated app.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 939c438b6761..65c371e15094 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8638,6 +8638,22 @@"readOnlyHint": true}},+ "integrations-push-tokens-create": {+ "description": "Register existing mobile devices, for example exported from another push provider, on an APNs or Firebase push channel so workflows can send them push notifications. Find the channel with integrations-list: kind apns takes hex APNs device tokens, kind firebase takes FCM registration tokens. Expo push tokens (ExponentPushToken[...]) work on neither and are always rejected. Each row pairs a device token with a distinct_id, which must be the ID the app passes to identify, so the device lands on the person workflows target. A distinct ID with no person fails as unknown_person unless create_missing_persons is true; leave it false unless the user confirms those IDs are right. Always call with dry_run=true first: it reports every failing row (unknown_person, token_mismatch) without storing anything. Fix or drop those rows, then call again without dry_run. Send at most 1000 rows per call and at most 60 calls per minute per project; on HTTP 429 wait a minute and retry. Rows that fail as not_stored can be sent again. Importing the same row twice stores it once.",+ "category": "Integrations",+ "feature": "integrations",+ "summary": "Import push device tokens",+ "title": "Import push device tokens",+ "required_scopes": ["integration:write", "person:write"],+ "api_operations": ["POST /api/projects/{project_id}/integrations/{id}/push_tokens/"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "workflows-push-token-import-mcp"+ },"integrations-users-retrieve": {"description": "List the Slack workspace members a Slack integration can send direct messages to. Slack-only — non-Slack integration ids return an error (400 if the integration is otherwise visible, 404 if it isn't). Returns each member's id (e.g. U0123ABC), name (handle without the leading @), and display_name; bots, deactivated accounts, and Slackbot are excluded. Supports `search` (fuzzy match on display name and handle, plus id-contains), `limit`, `offset`, and a `user_id` query parameter for a direct lookup. Results are cached for 1 hour (no force-refresh exposed via MCP). Use this to find member ids when configuring a scout's Slack DM destination — pass them as `output_destinations.slack.users` entries (`member_id|@display-name`) via scout-config-update or scout-create. Requires the Slack integration's id; use integrations-list (filter by kind=slack) to find it.","category": "Integrations",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 37e4eb14d3fb..0162017fbd72 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8904,6 +8904,22 @@"readOnlyHint": true}},+ "integrations-push-tokens-create": {+ "description": "Register existing mobile devices, for example exported from another push provider, on an APNs or Firebase push channel so workflows can send them push notifications. Find the channel with integrations-list: kind apns takes hex APNs device tokens, kind firebase takes FCM registration tokens. Expo push tokens (ExponentPushToken[...]) work on neither and are always rejected. Each row pairs a device token with a distinct_id, which must be the ID the app passes to identify, so the device lands on the person workflows target. A distinct ID with no person fails as unknown_person unless create_missing_persons is true; leave it false unless the user confirms those IDs are right. Always call with dry_run=true first: it reports every failing row (unknown_person, token_mismatch) without storing anything. Fix or drop those rows, then call again without dry_run. Send at most 1000 rows per call and at most 60 calls per minute per project; on HTTP 429 wait a minute and retry. Rows that fail as not_stored can be sent again. Importing the same row twice stores it once.",+ "category": "Integrations",+ "feature": "integrations",+ "summary": "Import push device tokens",+ "title": "Import push device tokens",+ "required_scopes": ["integration:write", "person:write"],+ "api_operations": ["POST /api/projects/{project_id}/integrations/{id}/push_tokens/"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "workflows-push-token-import-mcp"+ },"integrations-users-retrieve": {"description": "List the Slack workspace members a Slack integration can send direct messages to. Slack-only — non-Slack integration ids return an error (400 if the integration is otherwise visible, 404 if it isn't). Returns each member's id (e.g. U0123ABC), name (handle without the leading @), and display_name; bots, deactivated accounts, and Slackbot are excluded. Supports `search` (fuzzy match on display name and handle, plus id-contains), `limit`, `offset`, and a `user_id` query parameter for a direct lookup. Results are cached for 1 hour (no force-refresh exposed via MCP). Use this to find member ids when configuring a scout's Slack DM destination — pass them as `output_destinations.slack.users` entries (`member_id|@display-name`) via scout-config-update or scout-create. Requires the Slack integration's id; use integrations-list (filter by kind=slack) to find it.","category": "Integrations",diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.tsindex 54a64cccccd5..d5f319f6375e 100644--- a/services/mcp/src/generated/integrations/api.ts+++ b/services/mcp/src/generated/integrations/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 11 enabled ops+ * PostHog API - MCP 12 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -240,6 +240,63 @@ export const IntegrationsLinearTeamsRetrieveParams = () => zod.object({),})+/**+ * Register existing device tokens, for example exported from another provider, on this push channel. Each token is stored encrypted on its person, as the mobile SDK stores it. A row fails when no person has its distinct ID, unless create_missing_persons is set, or when the token is the wrong kind for the channel. Send dry_run first to see every failure without storing anything.+ * @summary Import push device tokens+ */+export const IntegrationsPushTokensCreateParams = () => zod.object({+ id: zod.number().describe('A unique integer value identifying this integration.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const integrationsPushTokensCreateBodySubscriptionsItemDistinctIdMax = 200++export const integrationsPushTokensCreateBodySubscriptionsItemDeviceTokenMax = 4096++export const integrationsPushTokensCreateBodyDryRunDefault = false+export const integrationsPushTokensCreateBodyCreateMissingPersonsDefault = false++export const IntegrationsPushTokensCreateBody = () => zod.object({+ subscriptions: zod+ .array(+ zod.object({+ distinct_id: zod+ .string()+ .max(integrationsPushTokensCreateBodySubscriptionsItemDistinctIdMax)+ .describe("The person's distinct ID in this project: the ID your app passes to `identify`."),+ device_token: zod+ .string()+ .max(integrationsPushTokensCreateBodySubscriptionsItemDeviceTokenMax)+ .describe(+ 'The token of one device. An APNs channel takes the hex APNs device token. A Firebase channel takes the FCM registration token. Expo push tokens are not accepted.'+ ),+ })+ )+ .describe('Up to 1000 devices to register on this push channel. List a person once per device.'),+ dry_run: zod+ .boolean()+ .default(integrationsPushTokensCreateBodyDryRunDefault)+ .describe(+ 'Check every row and report what would fail, without storing anything. Run this first and fix the failed rows before importing.'+ ),+ import_id: zod+ .string()+ .nullish()+ .describe(+ 'A new UUID for each batch. Send the same value when you retry that batch, so a retried batch can be recognized as a repeat.'+ ),+ create_missing_persons: zod+ .boolean()+ .default(integrationsPushTokensCreateBodyCreateMissingPersonsDefault)+ .describe(+ "Create a person for a distinct ID that has none. Off by default, because a distinct ID that does not match your app's identify call creates a person that never gets a push."+ ),+})+export const IntegrationsUsersRetrieveParams = () => zod.object({id: zod.number().describe('A unique integer value identifying this integration.'),project_id: zoddiff --git a/services/mcp/src/tools/generated/integrations.ts b/services/mcp/src/tools/generated/integrations.tsindex 3df3230d8dac..77ffb24c1c52 100644--- a/services/mcp/src/tools/generated/integrations.ts+++ b/services/mcp/src/tools/generated/integrations.ts@@ -241,6 +241,42 @@ const integrationsList = (): ToolBase<},})+const IntegrationsPushTokensCreateSchema = () => {+ const IntegrationsPushTokensCreateBody = orvalSchemas.IntegrationsPushTokensCreateBody()+ const IntegrationsPushTokensCreateParams = orvalSchemas.IntegrationsPushTokensCreateParams()+ return IntegrationsPushTokensCreateParams.omit({ project_id: true }).extend(IntegrationsPushTokensCreateBody.shape)+}++const integrationsPushTokensCreate = (): ToolBase<+ ReturnType<typeof IntegrationsPushTokensCreateSchema>,+ Schemas.PushTokenImportResponse+> => ({+ name: 'integrations-push-tokens-create',+ schema: IntegrationsPushTokensCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof IntegrationsPushTokensCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.subscriptions !== undefined) {+ body['subscriptions'] = params.subscriptions+ }+ if (params.dry_run !== undefined) {+ body['dry_run'] = params.dry_run+ }+ if (params.import_id !== undefined) {+ body['import_id'] = params.import_id+ }+ if (params.create_missing_persons !== undefined) {+ body['create_missing_persons'] = params.create_missing_persons+ }+ const result = await context.api.request<Schemas.PushTokenImportResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/integrations/${encodeURIComponent(String(params.id))}/push_tokens/`,+ body,+ })+ return result+ },+})+const IntegrationsUsersRetrieveSchema = () => {const IntegrationsUsersRetrieveParams = orvalSchemas.IntegrationsUsersRetrieveParams()const IntegrationsUsersRetrieveQueryParams = orvalSchemas.IntegrationsUsersRetrieveQueryParams()@@ -318,6 +354,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'integrations-jira-projects-retrieve': integrationsJiraProjectsRetrieve,'integrations-linear-teams-retrieve': integrationsLinearTeamsRetrieve,'integrations-list': integrationsList,+ 'integrations-push-tokens-create': integrationsPushTokensCreate,'integrations-users-retrieve': integrationsUsersRetrieve,'posthog-connection-forward': posthogConnectionForward,}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex d68836bf1583..542cc6011381 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1135,6 +1135,7 @@ describe('Tool Filtering - Feature Flags', () => {'investigate-insight','workflows-customerio-import','mcp-session-recording-console-logs',+ 'workflows-push-token-import-mcp','support-macros',]expect(allFlags).toEqual(expect.arrayContaining(branchFlags))