: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(managed-migrations): staff-only support API and MCP tools (#70120)
Nick Best65f0ccb59cfe
diff --git a/bin/build-mcp-oauth-scopes.py b/bin/build-mcp-oauth-scopes.pyindex d38356d59f36..595c086b7302 100755--- a/bin/build-mcp-oauth-scopes.py+++ b/bin/build-mcp-oauth-scopes.py@@ -1,15 +1,22 @@#!/usr/bin/env python3-"""Generate OAUTH_SCOPES_SUPPORTED for the MCP protected-resource metadata.+"""Generate the MCP server's view of the OAuth scope universe from posthog/scopes.py.-The MCP server publishes RFC 9728 protected-resource metadata at-`/.well-known/oauth-protected-resource`. Spec-compliant clients (e.g. Claude-Code) read `scopes_supported` from there and pass every entry to the-authorization server's `/oauth/authorize`. If the resource list contains a-scope the AS does not recognize, sign-in fails with `?error=invalid_scope`.+Emits two constants into `services/mcp/src/lib/oauth-scopes.generated.ts`:-Both lists derive from `posthog.scopes.get_oauth_scopes_supported()`. This-script generates `services/mcp/src/lib/oauth-scopes.generated.ts` from that-function so the protected resource cannot drift out of subset of the AS.+- OAUTH_SCOPES_SUPPORTED (from `get_oauth_scopes_supported()`): the MCP server+ publishes RFC 9728 protected-resource metadata at+ `/.well-known/oauth-protected-resource`. Spec-compliant clients (e.g. Claude+ Code) read `scopes_supported` from there and pass every entry to the+ authorization server's `/oauth/authorize`. If the resource list contains a+ scope the AS does not recognize, sign-in fails with `?error=invalid_scope`,+ so this list must stay a subset of the AS's.+- OAUTH_SCOPES_HIDDEN: PAT-grantable scopes deliberately excluded from the+ list above (staff-only surfaces like `batch_import_support`). The MCP server+ uses this at runtime to gate tool discovery (`src/lib/staff-only-tools.ts`)+ and in tests to allow tools to require a non-advertised scope on purpose.++Generating both from `posthog/scopes.py` keeps that module the single+authority for scope classification; the TS side is a projection of it.Run via hogli: `hogli build:openapi-mcp-scopes` (also runs as part of`build:openapi`). See `common/hogli/manifest.yaml`.@@ -34,15 +41,17 @@ def main() -> int:# from stdlib will raise ImportError here, failing the build loudly.scopes_globals = runpy.run_path(str(SCOPES_PY))all_scopes: list[str] = scopes_globals["get_oauth_scopes_supported"]()+ hidden_scopes: list[str] = sorted(scopes_globals["OAUTH_SCOPES_HIDDEN"])# oxfmt enforces single quotes; format manually rather than json.dumps so# the generator output is byte-stable regardless of formatter rules. Scope# names are simple snake_case identifiers + colons and never need escaping,# but assert that to fail loudly if a scope ever does.- for s in all_scopes:+ for s in [*all_scopes, *hidden_scopes]:if "'" in s or "\\" in s:raise RuntimeError(f"unexpected character in scope name: {s!r}")body = ",\n".join(f" '{s}'" for s in all_scopes)+ hidden_body = ",\n".join(f" '{s}'" for s in hidden_scopes)output = ("// AUTO-GENERATED by bin/build-mcp-oauth-scopes.py from posthog/scopes.py.\n""// Regenerate with `hogli build:openapi`. Do not edit.\n"@@ -58,6 +67,14 @@ def main() -> int:"] as const\n""\n""export type OAuthScope = (typeof OAUTH_SCOPES_SUPPORTED)[number]\n"+ "\n"+ "// PAT-grantable but deliberately absent from OAUTH_SCOPES_SUPPORTED, so OAuth\n"+ "// clients can never request them (mirrors OAUTH_SCOPES_HIDDEN in posthog/scopes.py).\n"+ "// Tools requiring one of these only surface for staff users whose personal API key\n"+ "// explicitly carries it (plus `user:read` for the staff lookup); `*` does not match.\n"+ "export const OAUTH_SCOPES_HIDDEN = [\n"+ f"{hidden_body},\n"+ "] as const\n")OUTPUT_TS.parent.mkdir(parents=True, exist_ok=True)diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.tsindex 5493674073e3..e51362727d4f 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts@@ -316,6 +316,7 @@ export interface accessControlsLogicActions {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -431,7 +432,7 @@ export interface accessControlsLogicMeta {__keaTypeGenInternalSelectorTypes: {allMembers: (sortedMembers: OrganizationMemberType[] | null) => OrganizationMemberType[]canUseRoles: (- hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean+ hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic) => booleancanEdit: (defaults: AccessControlDefaultsResponse | null) => booleanavailableProjectLevels: (defaults: AccessControlDefaultsResponse | null) => AccessControlLevel[]@@ -450,6 +451,7 @@ export interface accessControlsLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -588,6 +590,7 @@ export interface accessControlsLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -699,6 +702,7 @@ export interface accessControlsLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.tsindex 821cfbac90c3..5fe17c727d40 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts@@ -37,6 +37,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -152,6 +153,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -259,6 +261,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -379,6 +382,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -499,6 +503,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -626,6 +631,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -733,6 +739,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -879,6 +886,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -988,6 +996,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -1096,6 +1105,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -1204,6 +1214,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -1313,6 +1324,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -1421,6 +1433,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -1540,6 +1553,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -1648,6 +1662,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -1895,113 +1910,7 @@ export const groupedAccessControlRuleModalLogic = kea<groupedAccessControlRuleMoresourceInheritedReasonTooltip: [(s) => [s.isResourceLevelShowingInherited, s.entry],(- isResourceLevelShowingInherited: (- resource:- | 'access_control'- | 'account'- | 'action'- | 'activity_log'- | 'agent_approvals'- | 'agents'- | 'alert'- | 'annotation'- | 'approvals'- | 'batch_export'- | 'batch_import'- | 'business_knowledge'- | 'clickhouse_test_cluster_perf'- | 'cohort'- | 'comment'- | 'conversation'- | 'customer_analytics'- | 'customer_journey'- | 'customer_profile_config'- | 'dashboard'- | 'dashboard_template'- | 'data_catalog'- | 'data_catalog_approval'- | 'dataset'- | 'early_access_feature'- | 'element'- | 'endpoint'- | 'engineering_analytics'- | 'error_tracking'- | 'evaluation'- | 'event_definition'- | 'event_filter'- | 'experiment'- | 'experiment_holdout'- | 'experiment_saved_metric'- | 'export'- | 'external_data_schema'- | 'external_data_source'- | 'feature_flag'- | 'field_note'- | 'file_system'- | 'file_system_shortcut'- | 'group'- | 'health_issue'- | 'heatmap'- | 'hog_flow'- | 'hog_function'- | 'ingestion_warning'- | 'insight'- | 'insight_variable'- | 'integration'- | 'internal_run'- | 'legal_document'- | 'link'- | 'live_debugger'- | 'llm_analytics'- | 'llm_gateway'- | 'llm_prompt'- | 'llm_provider_key'- | 'llm_skill'- | 'logs'- | 'marketing_analytics'- | 'mcp_analytics'- | 'metrics'- | 'notebook'- | 'organization'- | 'organization_integration'- | 'organization_member'- | 'person'- | 'plugin'- | 'product_enablement'- | 'product_tour'- | 'project'- | 'property_definition'- | 'query'- | 'query_performance'- | 'replay_scanner'- | 'revenue_analytics'- | 'session_recording'- | 'session_recording_playlist'- | 'sharing_configuration'- | 'signal_scout'- | 'signal_scout_internal'- | 'signal_scout_report'- | 'stamphog'- | 'streamlit_app'- | 'subscription'- | 'survey'- | 'tagger'- | 'task'- | 'ticket'- | 'tracing'- | 'uploaded_media'- | 'usage_metric'- | 'user'- | 'user_interview'- | 'vision_action'- | 'visual_review'- | 'warehouse_objects'- | 'warehouse_table'- | 'warehouse_view'- | 'web_analytics'- | 'webhook'- | 'wizard_session'- ) => boolean,+ isResourceLevelShowingInherited: (resource: APIScopeObject) => boolean,entry: import('./types').AccessControlSettingsEntry) =>(resource: APIScopeObject) =>diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex 762aa1eaf20c..e48ad3bc520d 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -313,6 +313,7 @@ export interface accessControlLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -524,6 +525,7 @@ export interface accessControlLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'@@ -632,6 +634,7 @@ export interface accessControlLogicMeta {| 'approvals'| 'batch_export'| 'batch_import'+ | 'batch_import_support'| 'business_knowledge'| 'clickhouse_test_cluster_perf'| 'cohort'diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 7998616c36ce..89086ef283f9 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -240,6 +240,7 @@ export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, strinsignal_scout_internal: 'Internal: sandbox-only writes for the headless Signals agent.',signal_scout_report: 'Internal: sandbox-only writes for the scout report channel.',// OAUTH_HIDDEN_SCOPE_OBJECTS — pasteable into a PAT, but never advertised via OAuth/CLI/MCP.+ batch_import_support: 'OAuth-hidden: staff-only, pasteable into a PAT but not advertised.',query_performance: 'OAuth-hidden: staff-only, pasteable into a PAT but not advertised.',wizard_session: 'OAuth-hidden: pasteable into a PAT but not advertised.',// Umbrella access-control resource that `warehouse_view`/`warehouse_table` inherit from —diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b48df20481d9..3265b112174e 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5679,6 +5679,7 @@ export const API_SCOPE_OBJECTS = ['approvals','batch_export','batch_import',+ 'batch_import_support','business_knowledge','clickhouse_test_cluster_perf','cohort',diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex fee12fd9e575..9211b51ff9b2 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -36,7 +36,7 @@ from posthog.api.oauth.cimd import ()from posthog.api.oauth.client_name import sanitize_client_namefrom posthog.models.oauth import OAuthApplication, create_cimd_verification_token-from posthog.scopes import OAUTH_HIDDEN_SCOPES, PRIVILEGED_SCOPES+from posthog.scopes import OAUTH_SCOPES_HIDDEN, PRIVILEGED_SCOPESVALID_CIMD_URL = "https://app.example.com/.well-known/oauth-client-metadata.json"@@ -971,7 +971,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):# (c) Only UNPRIVILEGED_SCOPES pass — privileged, hidden, and unknown strings are all dropped.@patch("posthog.api.oauth.cimd.requests.get")def test_non_grantable_scopes_stripped(self, mock_get, _url_mock):- hidden_scope = next(iter(OAUTH_HIDDEN_SCOPES)) if OAUTH_HIDDEN_SCOPES else None+ hidden_scope = next(iter(OAUTH_SCOPES_HIDDEN)) if OAUTH_SCOPES_HIDDEN else Noneinput_scopes = [*sorted(PRIVILEGED_SCOPES),"not_a_real_scope:write", # unknown / garbage string@@ -1080,7 +1080,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):fetch_and_upsert_cimd_application(VALID_CIMD_URL)real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))- hidden_scope = next(iter(OAUTH_HIDDEN_SCOPES)) if OAUTH_HIDDEN_SCOPES else None+ hidden_scope = next(iter(OAUTH_SCOPES_HIDDEN)) if OAUTH_SCOPES_HIDDEN else Noneescalated = [*sorted(PRIVILEGED_SCOPES), "not_a_real_scope:write", "insight:read"]if hidden_scope:escalated.append(hidden_scope)diff --git a/posthog/scopes.py b/posthog/scopes.pyindex c4e02a4e37c2..2ce3a951fef6 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -26,6 +26,7 @@ APIScopeObject = Literal["approvals","batch_export","batch_import",+ "batch_import_support","business_knowledge","clickhouse_test_cluster_perf","cohort",@@ -162,7 +163,16 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(# we don't want OAuth-based clients (the consent screen, MCP, third-party apps)# to discover it — alpha / not-yet-public products, or staff-only debug endpoints# automation reaches with a PAT (e.g. `query_performance`, also gated by `is_staff`).-OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"wizard_session", "query_performance"})+OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(+ {+ "wizard_session",+ "query_performance",+ # Staff-only managed-migrations (batch import) support diagnostics, also gated by+ # `is_staff`. Distinct from the public `batch_import` object on purpose: that one is+ # OAuth-advertised, and a customer-grantable scope must never name a staff surface.+ "batch_import_support",+ }+)# llm_gateway:read is omitted on purpose: it's alpha/privileged and granted only behind the# ai-gateway flag in ProjectSecretAPIKeySerializer, not unconditionally like the entries here.@@ -204,7 +214,7 @@ PRIVILEGED_SCOPES: frozenset[str] = frozenset({"llm_gateway:read", "llm_gateway:# alpha scope never reaches the broad default. Intersected with `ALL_SCOPES`# so a future hidden object whose action set narrows doesn't carry a phantom# string into the set.-OAUTH_HIDDEN_SCOPES: frozenset[str] = (+OAUTH_SCOPES_HIDDEN: frozenset[str] = (frozenset(f"{obj}:{action}" for obj in OAUTH_HIDDEN_SCOPE_OBJECTS for action in API_SCOPE_ACTIONS) & ALL_SCOPES)@@ -213,7 +223,7 @@ OAUTH_HIDDEN_SCOPES: frozenset[str] = (# `/authorize` time. OIDC scopes (openid/profile/email) are NOT in this set —# they live in `OIDC_SCOPES` below and are accepted at `/authorize`# independently of `application.scopes`.-UNPRIVILEGED_SCOPES: frozenset[str] = ALL_SCOPES - PRIVILEGED_SCOPES - OAUTH_HIDDEN_SCOPES+UNPRIVILEGED_SCOPES: frozenset[str] = ALL_SCOPES - PRIVILEGED_SCOPES - OAUTH_SCOPES_HIDDENdef get_scope_descriptions() -> dict[str, str]:@@ -424,7 +434,7 @@ def get_oauth_scopes_supported() -> list[str]:Built from `UNPRIVILEGED_SCOPES`, so it excludes all three non-advertisedclasses: `INTERNAL_API_SCOPE_OBJECTS` (server-mint-only, e.g.- `signal_scout_internal` — never user-grantable), `OAUTH_HIDDEN_SCOPES`+ `signal_scout_internal` — never user-grantable), `OAUTH_SCOPES_HIDDEN`(alpha / PAT-only), and `PRIVILEGED_SCOPES` (`llm_gateway:*`, admin-grantedonly). Discovery metadata shouldn't advertise scopes an OAuth client can'tobtain self-serve. PAT validation uses `get_scope_descriptions()` directlydiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 5c83d78f1f74..6784e9be8bb3 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -562,6 +562,7 @@ SPECTACULAR_SETTINGS = {"EvaluationTargetEnum": "products.ai_observability.backend.models.evaluations.EvaluationTarget","IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind","TicketStatusEnum": "products.conversations.backend.models.constants.Status",+ "BatchImportStatusEnum": "products.managed_migrations.backend.models.batch_imports.BatchImport.Status","HealthIssueStatusEnum": "posthog.models.health_issue.HealthIssue.Status","HealthIssueSeverityEnum": "posthog.models.health_issue.HealthIssue.Severity","IngestionWarningSeverityEnum": "posthog.api.ingestion_warnings_v2.INGESTION_WARNING_SEVERITIES",diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pyindex 422cad47a0b9..1b44b9cd2bc3 100644--- a/posthog/test/test_scopes.py+++ b/posthog/test/test_scopes.py@@ -13,7 +13,7 @@ from posthog.scopes import (API_SCOPE_OBJECTS,INTERNAL_API_SCOPE_OBJECTS,OAUTH_HIDDEN_SCOPE_OBJECTS,- OAUTH_HIDDEN_SCOPES,+ OAUTH_SCOPES_HIDDEN,OIDC_SCOPES,PRIVILEGED_SCOPES,UNPRIVILEGED_SCOPES,@@ -87,7 +87,7 @@ class TestScopeSets(BaseTest):def test_unprivileged_scopes_excludes_privileged_and_hidden(self) -> None:self.assertTrue(UNPRIVILEGED_SCOPES.isdisjoint(PRIVILEGED_SCOPES))- self.assertTrue(UNPRIVILEGED_SCOPES.isdisjoint(OAUTH_HIDDEN_SCOPES))+ self.assertTrue(UNPRIVILEGED_SCOPES.isdisjoint(OAUTH_SCOPES_HIDDEN))@parameterized.expand([("openid",), ("profile",), ("email",)])def test_unprivileged_scopes_excludes_oidc(self, oidc: str) -> None:@@ -122,7 +122,7 @@ class TestScopeSets(BaseTest):# OAUTH_HIDDEN scopes — an OAuth client can't obtain them self-serve.supported = set(get_oauth_scopes_supported())self.assertTrue(supported.isdisjoint(PRIVILEGED_SCOPES))- self.assertTrue(supported.isdisjoint(OAUTH_HIDDEN_SCOPES))+ self.assertTrue(supported.isdisjoint(OAUTH_SCOPES_HIDDEN))self.assertNotIn("llm_gateway:read", supported)self.assertNotIn("llm_gateway:write", supported)diff --git a/products/managed_migrations/backend/api/support_batch_imports.py b/products/managed_migrations/backend/api/support_batch_imports.pynew file mode 100644index 000000000000..db8a6e66e52e--- /dev/null+++ b/products/managed_migrations/backend/api/support_batch_imports.py@@ -0,0 +1,338 @@+from django.utils import timezone++import structlog+from django_filters.rest_framework import DjangoFilterBackend+from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_view+from rest_framework import filters, request, response, serializers, viewsets+from rest_framework.exceptions import AuthenticationFailed+from rest_framework.permissions import BasePermission, IsAuthenticated+from rest_framework.views import APIView++from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.permissions import APIScopePermission, IsStaffUser++from products.managed_migrations.backend.models.batch_import_utils import (+ extract_batch_import_info,+ get_batch_import_created_by_info,+ redact_part_key,+ redact_urls_in_json,+ redact_urls_in_text,+)+from products.managed_migrations.backend.models.batch_imports import BatchImport++logger = structlog.get_logger(__name__)++DISPLAY_STATUSES = ["waiting_to_start", "running", "paused", "failed", "completed"]+++class BatchImportPartsProgressSerializer(serializers.Serializer):+ done = serializers.IntegerField(+ help_text="Number of finished parts (a part is done when its committed byte offset has reached its known total size)."+ )+ total = serializers.IntegerField(help_text="Total number of parts the worker has planned for this import.")+ inflight_key = serializers.CharField(+ allow_null=True,+ help_text="Key (file/date-range identifier) of the first unfinished part - the one in flight or next up. Null when all parts are done or the worker has not started. URL keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.",+ )+ inflight_offset = serializers.IntegerField(+ allow_null=True,+ help_text="Committed byte offset (decompressed) within the in-flight part. Null when there is no in-flight part.",+ )+ inflight_total_size = serializers.IntegerField(+ allow_null=True,+ help_text="Total decompressed size in bytes of the in-flight part, or null if the worker has not measured it yet.",+ )+++class BatchImportSupportListSerializer(serializers.ModelSerializer):+ """Compact cross-team diagnostics view of a batch import job for PostHog support staff.++ Excludes the raw `state` / `import_config` blobs (see the detail serializer) and never+ exposes the encrypted `secrets` column.+ """++ team_id = serializers.IntegerField(help_text="ID of the team (project) the import belongs to.")+ team_name = serializers.CharField(source="team.name", help_text="Name of the team the import belongs to.")+ status_message = serializers.SerializerMethodField(+ help_text="Developer-facing status message written by the worker or an operator - the primary debugging signal. Not shown to the customer. Embedded URLs have their query string and userinfo redacted, since url_list part keys can carry presigned tokens or credentials."+ )+ display_status_message = serializers.SerializerMethodField(+ help_text="Customer-facing status message shown in the PostHog UI. Embedded URLs are redacted the same way as status_message."+ )+ display_status = serializers.SerializerMethodField(+ help_text="Effective status: 'waiting_to_start' when the job is running but no worker has claimed it yet (lease_id is null), otherwise the raw status."+ )+ parts_progress = serializers.SerializerMethodField(+ help_text="Worker part progress summary derived from the raw state blob."+ )+ lease_expired = serializers.SerializerMethodField(+ help_text="True when the job holds a lease whose expiry is in the past. On a running job this means the worker died or the row is claimable again; the next poll can re-claim it."+ )+ source_type = serializers.SerializerMethodField(+ help_text="Source the job imports from (e.g. s3, mixpanel, amplitude, urls, folder), or 'unknown' if unset."+ )+ content_type = serializers.SerializerMethodField(+ help_text="Format of the source events (e.g. mixpanel, amplitude, captured), or 'unknown' if unset."+ )+ source_start_date = serializers.SerializerMethodField(+ help_text="Start of the source date range for date-range sources (Mixpanel/Amplitude), else null."+ )+ source_end_date = serializers.SerializerMethodField(+ help_text="End of the source date range for date-range sources (Mixpanel/Amplitude), else null."+ )+ sink_type = serializers.SerializerMethodField(+ help_text="Where imported events are written (normally 'capture'; 'kafka'/'noop' for internal use), or null if unset."+ )+ sink_send_rate = serializers.SerializerMethodField(+ help_text="Configured sink send rate in events per second, or null if unset."+ )++ class Meta:+ model = BatchImport+ # `secrets` is deliberately absent: an explicit field list is the structural guarantee+ # that the encrypted credentials column can never serialize into a support response.+ fields = [+ "id",+ "team_id",+ "team_name",+ "status",+ "display_status",+ "status_message",+ "display_status_message",+ "parts_progress",+ "source_type",+ "content_type",+ "source_start_date",+ "source_end_date",+ "sink_type",+ "sink_send_rate",+ "lease_id",+ "leased_until",+ "lease_expired",+ "backoff_attempt",+ "backoff_until",+ "created_by_id",+ "created_at",+ "updated_at",+ ]+ extra_kwargs = {+ "id": {"help_text": "UUID of the batch import job."},+ "status": {"help_text": "Raw persisted status of the job."},+ "lease_id": {+ "help_text": "Lease token of the worker currently holding the job, or null when unclaimed. Claims lease for 30 minutes; the running heartbeat renews for 5 minutes."+ },+ "leased_until": {"help_text": "When the current worker lease expires."},+ "backoff_attempt": {"help_text": "Consecutive transient-failure retries so far (0 = healthy)."},+ "backoff_until": {+ "help_text": "When the worker will retry after a transient failure. A future value means the job is in a retry loop, not stuck."+ },+ "created_by_id": {"help_text": "ID of the user who created the import, if any."},+ "created_at": {"help_text": "When the import was created."},+ "updated_at": {"help_text": "Last write to the row - the worker heartbeats this while processing."},+ }++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_status_message(self, obj: BatchImport) -> str | None:+ return redact_urls_in_text(obj.status_message)++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_display_status_message(self, obj: BatchImport) -> str | None:+ return redact_urls_in_text(obj.display_status_message)++ @extend_schema_field(serializers.ChoiceField(choices=DISPLAY_STATUSES))+ def get_display_status(self, obj: BatchImport) -> str:+ if obj.status == BatchImport.Status.RUNNING and obj.lease_id is None:+ return "waiting_to_start"+ return obj.status++ @extend_schema_field(BatchImportPartsProgressSerializer)+ def get_parts_progress(self, obj: BatchImport) -> dict:+ done, total, inflight = obj.parts_progress()+ return {+ "done": done,+ "total": total,+ "inflight_key": redact_part_key(inflight.get("key")) if inflight else None,+ "inflight_offset": inflight.get("current_offset") if inflight else None,+ "inflight_total_size": inflight.get("total_size") if inflight else None,+ }++ def get_lease_expired(self, obj: BatchImport) -> bool:+ return obj.lease_id is not None and obj.leased_until is not None and obj.leased_until < timezone.now()++ def get_source_type(self, obj: BatchImport) -> str:+ source_type, _content_type, _start, _end = extract_batch_import_info(obj)+ return source_type++ def get_content_type(self, obj: BatchImport) -> str:+ _source_type, content_type, _start, _end = extract_batch_import_info(obj)+ return content_type++ def get_source_start_date(self, obj: BatchImport) -> str | None:+ _source_type, _content_type, start, _end = extract_batch_import_info(obj)+ return start++ def get_source_end_date(self, obj: BatchImport) -> str | None:+ _source_type, _content_type, _start, end = extract_batch_import_info(obj)+ return end++ def get_sink_type(self, obj: BatchImport) -> str | None:+ return ((obj.import_config or {}).get("sink") or {}).get("type")++ @extend_schema_field(serializers.IntegerField(allow_null=True))+ def get_sink_send_rate(self, obj: BatchImport) -> int | None:+ return ((obj.import_config or {}).get("sink") or {}).get("send_rate")+++class BatchImportSupportDetailSerializer(BatchImportSupportListSerializer):+ """Full diagnostics view: adds the raw worker `state` and `import_config` blobs.++ `import_config` holds secret key *names* only - secret values live exclusively in the+ encrypted `secrets` column, which no support serializer exposes.+ """++ state = serializers.SerializerMethodField(+ help_text="Raw worker progress blob: {'parts': [{'key', 'current_offset', 'total_size'}]}. A part is done when current_offset >= total_size; parts are processed in order. URL part keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.",+ )+ import_config = serializers.SerializerMethodField(+ help_text="Source/format/sink configuration of the job. References secrets by key name only; secret values are never returned. Embedded URLs (e.g. a custom S3 endpoint_url) have their query string and userinfo redacted.",+ )+ created_by_email = serializers.SerializerMethodField(+ help_text="Email of the user who created the import, if known."+ )++ class Meta(BatchImportSupportListSerializer.Meta):+ fields = [*BatchImportSupportListSerializer.Meta.fields, "state", "import_config", "created_by_email"]++ def get_created_by_email(self, obj: BatchImport) -> str | None:+ _id, email, _name = get_batch_import_created_by_info(obj)+ return email++ @extend_schema_field({"type": "object", "nullable": True})+ def get_state(self, obj: BatchImport) -> object:+ return redact_urls_in_json(obj.state)++ @extend_schema_field({"type": "object", "nullable": True})+ def get_import_config(self, obj: BatchImport) -> object:+ return redact_urls_in_json(obj.import_config)+++class UnscopedPersonalAPIKeyPermission(BasePermission):+ """+ Rejects personal API keys carrying scoped_teams or scoped_organizations.++ This viewset is root-level and cross-team, so APIScopePermission has no routed+ team/org to check scoping against: scoped-team keys already fail closed there,+ but scoped-ORGANIZATION keys fall through its ValueError handler and would+ silently bypass their organization ceiling on this cross-team surface.+ A support key must be unscoped; a scoped one is a misconfiguration either way.+ """++ message = "This endpoint requires an unscoped personal API key (no scoped organizations or projects)."++ def has_permission(self, request: request.Request, view: APIView) -> bool:+ authenticator = request.successful_authenticator+ if not isinstance(authenticator, PersonalAPIKeyAuthentication):+ return True+ key = authenticator.personal_api_key+ return not key.scoped_organizations and not key.scoped_teams+++@extend_schema_view(+ list=extend_schema(+ description="List batch import (managed migration) jobs across all teams. PostHog staff only.",+ ),+ retrieve=extend_schema(+ description="Get one batch import job with its raw worker state and import config. PostHog staff only.",+ ),+)+class BatchImportSupportViewSet(viewsets.ReadOnlyModelViewSet):+ """+ Staff-only, cross-team diagnostics for batch import (managed migration) jobs.++ Unlike BatchImportViewSet (membership-scoped via TeamAndOrgViewSetMixin), support staff+ need to inspect jobs on teams they do not belong to, so this is registered on the root+ router. Read-only on purpose; mutations (resume/pause) stay in Django admin for now.+ Exposes the same data Django admin's BatchImportAdmin already shows staff un-redacted.++ Access requires ALL of:+ - a staff user (`is_staff`) - enforced for both session and personal-API-key auth, since+ PersonalAPIKeyAuthentication authenticates as the key's real user;+ - for token auth, a personal API key explicitly carrying `batch_import_support:read`,+ sent via the Authorization header (query-string keys are rejected in `initial()`:+ the paginator would reflect them into next/previous response links).+ The scope is OAuth-hidden (grantable to a PAT, never via OAuth consent) and+ `scope_object = "INTERNAL"` blocks full-access (`*`) keys, so only a deliberately+ minted key works. Browser sessions bypass the scope layer and rely on `is_staff`.++ To mint a key (the scope is hidden from the PAT UI picker): create a key in the UI+ with `user:read`, then add `batch_import_support:read` to its scopes via Django admin.+ `user:read` is required for MCP use: tool discovery verifies staffness via+ `/api/users/@me/` and hides these tools (fail-closed) when it cannot. The key must be+ unscoped - keys with scoped_teams/scoped_organizations are rejected on root-level+ endpoints (scoped_teams centrally, scoped_organizations via+ UnscopedPersonalAPIKeyPermission below - the central org check cannot anchor on a+ root route and would otherwise fail open).+ Full operator guide: products/managed_migrations/docs/support-mcp-tools.md.+ """++ scope_object = "INTERNAL"+ required_scopes = ["batch_import_support:read"]+ permission_classes = [IsAuthenticated, IsStaffUser, APIScopePermission, UnscopedPersonalAPIKeyPermission]+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication]+ queryset = BatchImport.objects.select_related("team").order_by("-created_at")+ serializer_class = BatchImportSupportListSerializer+ filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]+ filterset_fields = ["status", "team_id"]+ # No `id` search (icontains is unsupported on a native Postgres uuid column) - exact id+ # lookups are what `retrieve` is for.+ search_fields = ["status_message", "team__name"]+ ordering_fields = ["created_at", "updated_at", "status"]+ ordering = ["-created_at"]++ def initial(self, request: request.Request, *args, **kwargs) -> None:+ # PersonalAPIKeyAuthentication also accepts `?personal_api_key=` - but the+ # paginator rebuilds next/previous links from the full request URL, which would+ # reflect the plaintext staff key into the response body. Reject here, before+ # authentication runs, so the gate holds on every auth path (including a+ # logged-in browser session carrying a stray key, which never reaches the PAT+ # authenticator at all). Deliberately NOT enforced in a custom authenticator:+ # anything that raises during DRF's lazy authentication also fires inside+ # finalize_response (the audit logger touches request.user) and escapes as a 500.+ if "personal_api_key" in request.query_params:+ raise AuthenticationFailed(+ "Query-string personal API keys are not accepted on this endpoint - send the key as 'Authorization: Bearer <key>'."+ )+ super().initial(request, *args, **kwargs)++ def get_serializer_class(self) -> type[BatchImportSupportListSerializer]:+ if self.action == "retrieve":+ return BatchImportSupportDetailSerializer+ return BatchImportSupportListSerializer++ # Allowlist of query params safe to audit-log. PersonalAPIKeyAuthentication accepts+ # `?personal_api_key=...`, so logging raw query_params would write plaintext staff+ # keys to centralized logs; an allowlist fails closed for any future secret-bearing+ # param too.+ LOGGED_QUERY_PARAMS = frozenset({"status", "team_id", "search", "ordering", "limit", "offset"})++ def finalize_response(+ self, request: request.Request, response: response.Response, *args, **kwargs+ ) -> response.Response:+ # Staff reads of customer data should leave a trail.+ user = getattr(request, "user", None)+ if user is not None and user.is_authenticated:+ logger.info(+ "batch_import_support_api_request",+ staff_user_id=user.id,+ action=self.action,+ # `search` matches the unredacted status_message column, so a staff+ # search for a full status message can itself carry a credential-bearing+ # URL - redact it like every response surface.+ query_params={+ k: (redact_urls_in_text(v) if k == "search" and isinstance(v, str) else v)+ for k, v in request.query_params.items()+ if k in self.LOGGED_QUERY_PARAMS+ },+ object_id=self.kwargs.get("pk"),+ )+ return super().finalize_response(request, response, *args, **kwargs)diff --git a/products/managed_migrations/backend/api/test/test_batch_imports.py b/products/managed_migrations/backend/api/test/test_batch_imports.pyindex c9127530a96b..542b8714b1b9 100644--- a/products/managed_migrations/backend/api/test/test_batch_imports.py+++ b/products/managed_migrations/backend/api/test/test_batch_imports.py@@ -98,6 +98,27 @@ class TestBatchImportModel(BaseTest):"day-1",[{"key": "day-1", "current_offset": 0, "total_size": None}],),+ (+ # url_list part keys are credential-bearing URLs: the returned key (and the+ # status message built from it) must be redacted, while state keeps the raw+ # URL the worker resolves against.+ "url_key_redacted_in_return_but_not_state",+ [+ {+ "key": "https://u:[email protected]/d.jsonl?X-Amz-Signature=abc",+ "current_offset": 42,+ "total_size": None,+ }+ ],+ "https://example.com/d.jsonl",+ [+ {+ "key": "https://u:[email protected]/d.jsonl?X-Amz-Signature=abc",+ "current_offset": 0,+ "total_size": None,+ }+ ],+ ),])def test_resume_with_inflight_part_reset_resets_first_unfinished_part(@@ -110,6 +131,7 @@ class TestBatchImportModel(BaseTest):self.assertEqual(reset_key, expected_reset_key)batch_import.refresh_from_db()assert batch_import.state is not None+ self.assertNotIn("X-Amz-Signature", batch_import.status_message or "")self.assertEqual(batch_import.state["parts"], expected_parts)self.assertEqual(batch_import.status, BatchImport.Status.RUNNING)self.assertIsNone(batch_import.lease_id)diff --git a/products/managed_migrations/backend/api/test/test_support_batch_imports.py b/products/managed_migrations/backend/api/test/test_support_batch_imports.pynew file mode 100644index 000000000000..ab0c10986a9d--- /dev/null+++ b/products/managed_migrations/backend/api/test/test_support_batch_imports.py@@ -0,0 +1,384 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import APIBaseTest++from django.test import SimpleTestCase++import structlog.testing+from parameterized import parameterized+from rest_framework import status++from posthog.models import Organization, Team+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.managed_migrations.backend.api.support_batch_imports import BatchImportSupportDetailSerializer+from products.managed_migrations.backend.models.batch_import_utils import (+ redact_part_key,+ redact_urls_in_json,+ redact_urls_in_text,+)+from products.managed_migrations.backend.models.batch_imports import BatchImport, ContentType+++class TestRedactPartKey(SimpleTestCase):+ @parameterized.expand(+ [+ ("s3_object_key", "2024/01/events-0001.jsonl.gz", "2024/01/events-0001.jsonl.gz"),+ (+ "date_range_key",+ "2025-01-01T00:00:00Z-2025-01-02T00:00:00Z",+ "2025-01-01T00:00:00Z-2025-01-02T00:00:00Z",+ ),+ (+ "presigned_query_stripped",+ "https://bucket.s3.amazonaws.com/exports/day-1.jsonl?X-Amz-Signature=abc&X-Amz-Credential=AKIA",+ "https://bucket.s3.amazonaws.com/exports/day-1.jsonl",+ ),+ ("basic_auth_stripped", "https://user:[email protected]/d.jsonl", "https://example.com/d.jsonl"),+ ("port_kept", "https://example.com:8443/d.jsonl?token=x", "https://example.com:8443/d.jsonl"),+ ("fragment_stripped", "https://example.com/d.jsonl#frag", "https://example.com/d.jsonl"),+ ("non_string_passthrough", None, None),+ (+ # No netloc means it isn't a remote URL that could carry usable+ # credentials - it must pass through untouched, not get mangled+ # (query stripped) by the redaction path.+ "scheme_without_netloc_passthrough",+ "file:///2024/01/events.jsonl?checksum=abc",+ "file:///2024/01/events.jsonl?checksum=abc",+ ),+ (+ "unparseable_url_fails_closed",+ "https://example.com:99999999999/d.jsonl?token=x",+ "[unparseable-url-redacted]",+ ),+ ]+ )+ def test_redact_part_key(self, _name, key, expected):+ self.assertEqual(redact_part_key(key), expected)++ @parameterized.expand(+ [+ ("none_passthrough", None, None),+ ("empty_passthrough", "", ""),+ ("no_url_unchanged", "Invalid JSON syntax at offset 42", "Invalid JSON syntax at offset 42"),+ (+ # The worker's parse-failure shape: key quoted inside the message.+ "worker_parse_message",+ "Parsing data in file 'https://u:[email protected]/d.jsonl?X-Amz-Signature=abc' failed: bad utf-8",+ "Parsing data in file 'https://example.com/d.jsonl' failed: bad utf-8",+ ),+ (+ "multiple_urls",+ "Failed https://a.com/x?t=1 then https://u:[email protected]/y",+ "Failed https://a.com/x then https://b.com/y",+ ),+ (+ "trailing_punctuation_stays_outside_url",+ "Failed https://u:[email protected]/x?t=1, then https://b.com/y?s=2.",+ "Failed https://a.com/x, then https://b.com/y.",+ ),+ ]+ )+ def test_redact_urls_in_text(self, _name, text, expected):+ self.assertEqual(redact_urls_in_text(text), expected)++ def test_redact_urls_in_json_walks_nested_structures(self):+ blob = {+ "source": {"type": "s3", "endpoint_url": "https://u:[email protected]?token=x", "prefix": "a/b"},+ "parts": [{"key": "https://a.com/x?sig=1", "current_offset": 0}],+ "count": 3,+ "flag": None,+ }+ self.assertEqual(+ redact_urls_in_json(blob),+ {+ "source": {"type": "s3", "endpoint_url": "https://minio.example.com", "prefix": "a/b"},+ "parts": [{"key": "https://a.com/x", "current_offset": 0}],+ "count": 3,+ "flag": None,+ },+ )+++class TestBatchImportSupportAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.user.is_staff = True+ self.user.save()++ def _create_pat(self, scopes: list[str], **kwargs) -> str:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="test",+ secure_value=hash_key_value(token),+ scopes=scopes,+ **kwargs,+ )+ return token++ def _create_import(self, team: Team | None = None, **kwargs) -> BatchImport:+ defaults: dict = {"import_config": {}, "secrets": {"placeholder": "true"}}+ defaults.update(kwargs)+ batch_import = BatchImport(team=team or self.team, **defaults)+ # BatchImport.__init__ resets `secrets` to {} whenever import_config is falsy+ # (BatchImportConfigBuilder initialize_empty), and EncryptedJSONStringField+ # serializes {} to NULL, violating the NOT NULL constraint - so re-apply after+ # init to keep the row insertable while still exercising an empty config.+ batch_import.secrets = defaults["secrets"]+ batch_import.save()+ return batch_import++ @parameterized.expand(+ [+ # The triple gate: PAT auth needs the explicit hidden scope AND is_staff; the+ # public sibling scope and the `*` wildcard must not unlock the staff surface.+ ("staff_pat_with_scope", True, ["batch_import_support:read"], status.HTTP_200_OK),+ ("staff_pat_public_sibling_scope", True, ["batch_import:read"], status.HTTP_403_FORBIDDEN),+ ("staff_pat_wildcard", True, ["*"], status.HTTP_403_FORBIDDEN),+ ("non_staff_pat_with_scope", False, ["batch_import_support:read"], status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_pat_auth_matrix(self, _name, is_staff, scopes, expected_status):+ self.user.is_staff = is_staff+ self.user.save()+ token = self._create_pat(scopes=scopes)+ self.client.logout()++ response = self.client.get("/api/managed_migrations_support/", headers={"authorization": f"Bearer {token}"})+ self.assertEqual(response.status_code, expected_status, response.content)++ @parameterized.expand(+ [+ # Tenant-scoped keys must be rejected even with staff + the exact scope: this+ # root route has no routed team/org for APIScopePermission to anchor on, and+ # an org-scoped key would otherwise fail OPEN and bypass its organization+ # ceiling onto every customer's jobs (team-scoped keys already fail closed+ # centrally; pinned here so this route never regresses either way).+ ("org_scoped", "scoped_organizations"),+ ("team_scoped", "scoped_teams"),+ ]+ )+ def test_tenant_scoped_keys_are_rejected(self, _name, scoped_field):+ scoped_value = [str(self.organization.id)] if scoped_field == "scoped_organizations" else [self.team.pk]+ token = self._create_pat(scopes=["batch_import_support:read"], **{scoped_field: scoped_value})+ self.client.logout()++ response = self.client.get("/api/managed_migrations_support/", headers={"authorization": f"Bearer {token}"})+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)++ @parameterized.expand(+ [+ # Sessions bypass the scope layer; is_staff is the only gate for the browser.+ ("staff_session", True, status.HTTP_200_OK),+ ("non_staff_session", False, status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_session_auth_requires_staff(self, _name, is_staff, expected_status):+ self.user.is_staff = is_staff+ self.user.save()++ response = self.client.get("/api/managed_migrations_support/")+ self.assertEqual(response.status_code, expected_status, response.content)++ def test_staff_can_see_imports_on_teams_they_do_not_belong_to(self):+ # The whole point of this endpoint: support staff must reach jobs on customer teams+ # they aren't members of. Guards against someone reintroducing membership scoping+ # (an org filter or TeamAndOrgViewSetMixin) on the viewset.+ other_org = Organization.objects.create(name="Unrelated Org")+ other_team = Team.objects.create(organization=other_org, name="Cross Org Team")+ self.assertFalse(self.user.organization_memberships.filter(organization=other_org).exists())+ batch_import = self._create_import(team=other_team)++ list_response = self.client.get("/api/managed_migrations_support/")+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)+ returned = next(r for r in list_response.json()["results"] if r["id"] == str(batch_import.id))+ self.assertEqual(returned["team_id"], other_team.id)+ self.assertEqual(returned["team_name"], "Cross Org Team")++ detail_response = self.client.get(f"/api/managed_migrations_support/{batch_import.id}/")+ self.assertEqual(detail_response.status_code, status.HTTP_200_OK)++ @parameterized.expand(+ [+ # The paginator rebuilds next/previous links from the full request URL, so a+ # query-string key would be reflected into the response body - reject it no+ # matter which authenticator would otherwise win: PAT auth via the query+ # string itself, and a logged-in session carrying a stray key (which never+ # reaches the PAT authenticator's own rejection).+ ("pat_auth_via_query_string", False),+ ("session_auth_with_stray_query_key", True),+ ]+ )+ def test_query_string_api_key_is_rejected(self, _name, use_session):+ token = self._create_pat(scopes=["batch_import_support:read"])+ if not use_session:+ self.client.logout()++ response = self.client.get(f"/api/managed_migrations_support/?personal_api_key={token}")+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)++ def test_audit_log_never_contains_credentials(self):+ # The audit log must allowlist query params so credential-bearing params+ # (e.g. `personal_api_key`, which the base auth class reads from the query+ # string) can never reach centralized logs. `search` is allowlisted but matches+ # the unredacted status_message column, so a search for a full status message+ # can quote a credential-bearing URL - it must be logged redacted.+ token = self._create_pat(scopes=["batch_import_support:read"])+ self.client.logout()++ with structlog.testing.capture_logs() as logs:+ response = self.client.get(+ "/api/managed_migrations_support/",+ {+ "status": "paused",+ "unexpected_param": "sensitive",+ "search": "Parsing data in file 'https://u:[email protected]/x?sig=verysecret' failed",+ },+ headers={"authorization": f"Bearer {token}"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ audit_logs = [log for log in logs if log.get("event") == "batch_import_support_api_request"]+ self.assertEqual(len(audit_logs), 1)+ self.assertNotIn(token, str(audit_logs[0]))+ self.assertNotIn("verysecret", str(audit_logs[0]))+ self.assertEqual(+ audit_logs[0]["query_params"],+ {"status": "paused", "search": "Parsing data in file 'https://a.com/x' failed"},+ )++ def test_secret_values_never_appear_in_responses(self):+ # Structural guarantee first: neither serializer declares the field at all+ # (detail inherits list, so this covers both endpoints).+ self.assertNotIn("secrets", BatchImportSupportDetailSerializer().fields)++ batch_import = BatchImport(team=self.team)+ batch_import.config.json_lines(ContentType.CAPTURED).from_s3(+ bucket="customer-bucket",+ prefix="events/",+ region="us-east-1",+ access_key_id="AKIA_SUPER_SECRET_ID",+ secret_access_key="s3cr3t-access-key-value",+ ).to_capture(send_rate=1000)+ batch_import.save()++ for url in ["/api/managed_migrations_support/", f"/api/managed_migrations_support/{batch_import.id}/"]:+ response = self.client.get(url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ content = response.content.decode()+ self.assertNotIn("AKIA_SUPER_SECRET_ID", content)+ self.assertNotIn("s3cr3t-access-key-value", content)+ self.assertNotIn('"secrets"', content)+ # The non-secret config referencing secrets by key name IS expected on detail.+ self.assertNotIn('aws_secret_access_key": "s3cr3t', content)++ def test_derived_diagnostic_fields(self):+ now = datetime.now(UTC)+ batch_import = self._create_import(+ status=BatchImport.Status.RUNNING,+ lease_id="worker-lease",+ leased_until=now - timedelta(minutes=10),+ state={+ "parts": [+ {"key": "day-1", "current_offset": 1000, "total_size": 1000},+ {"key": "day-2", "current_offset": 50, "total_size": 200},+ {"key": "day-3"}, # partially shaped worker dict must not 500+ ]+ },+ import_config={+ "source": {"type": "mixpanel", "start": "2025-01-01", "end": "2025-02-01"},+ "data_format": {"content": {"type": "mixpanel"}},+ "sink": {"type": "capture", "send_rate": 500},+ },+ )++ response = self.client.get(f"/api/managed_migrations_support/{batch_import.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()++ self.assertEqual(data["display_status"], "running") # leased, so not waiting_to_start+ self.assertTrue(data["lease_expired"])+ self.assertEqual(+ data["parts_progress"],+ {+ "done": 1,+ "total": 3,+ "inflight_key": "day-2",+ "inflight_offset": 50,+ "inflight_total_size": 200,+ },+ )+ self.assertEqual(data["source_type"], "mixpanel")+ self.assertEqual(data["content_type"], "mixpanel")+ self.assertEqual(data["source_start_date"], "2025-01-01")+ self.assertEqual(data["source_end_date"], "2025-02-01")+ self.assertEqual(data["sink_type"], "capture")+ self.assertEqual(data["sink_send_rate"], 500)+ self.assertEqual(data["created_by_email"], None)+ self.assertEqual(data["state"], batch_import.state)+ self.assertEqual(data["import_config"], batch_import.import_config)++ def test_unclaimed_running_job_is_waiting_to_start_and_empty_config_does_not_500(self):+ batch_import = self._create_import(status=BatchImport.Status.RUNNING, lease_id=None, state=None)++ response = self.client.get(f"/api/managed_migrations_support/{batch_import.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()++ self.assertEqual(data["display_status"], "waiting_to_start")+ self.assertFalse(data["lease_expired"])+ self.assertEqual(data["parts_progress"]["total"], 0)+ self.assertEqual(data["source_type"], "unknown")+ self.assertIsNone(data["sink_type"])++ def test_url_list_part_keys_are_redacted_in_responses(self):+ # url_list part keys are full source URLs; presigned tokens (query string) and+ # basic-auth credentials (userinfo) must never surface through the support API,+ # while the DB row must keep the raw URL - the worker resolves keys against it.+ secret_url = "https://user:[email protected]/exports/day-1.jsonl?X-Amz-Signature=topsecret"+ batch_import = self._create_import(+ status=BatchImport.Status.RUNNING,+ lease_id="worker-lease",+ state={"parts": [{"key": secret_url, "current_offset": 0, "total_size": None}]},+ import_config={+ "source": {+ "type": "url_list",+ "urls_key": "urls",+ "endpoint_url": "https://cfguser:[email protected]?token=topsecret",+ }+ },+ status_message=f"Parsing data in file '{secret_url}' failed: invalid JSON",+ display_status_message=f"Part {secret_url} begins with gzip-compressed data",+ )++ list_response = self.client.get("/api/managed_migrations_support/")+ detail_response = self.client.get(f"/api/managed_migrations_support/{batch_import.id}/")++ redacted = "https://bucket.s3.amazonaws.com/exports/day-1.jsonl"+ row = next(r for r in list_response.json()["results"] if r["id"] == str(batch_import.id))+ self.assertEqual(row["parts_progress"]["inflight_key"], redacted)+ self.assertEqual(detail_response.json()["state"]["parts"][0]["key"], redacted)+ self.assertEqual(detail_response.json()["import_config"]["source"]["endpoint_url"], "https://minio.example.com")+ for content in (list_response.content, detail_response.content):+ self.assertNotIn(b"secretpass", content)+ self.assertNotIn(b"topsecret", content)+ self.assertNotIn(b"cfgsecret", content)+ batch_import.refresh_from_db()+ assert batch_import.state is not None+ self.assertEqual(batch_import.state["parts"][0]["key"], secret_url)++ def test_list_filters(self):+ other_team = Team.objects.create(organization=self.organization, name="Other Team")+ paused = self._create_import(status=BatchImport.Status.PAUSED, status_message="Invalid JSON syntax")+ running_other_team = self._create_import(team=other_team)++ by_status = self.client.get("/api/managed_migrations_support/", {"status": "paused"})+ self.assertEqual([r["id"] for r in by_status.json()["results"]], [str(paused.id)])++ by_team = self.client.get("/api/managed_migrations_support/", {"team_id": other_team.id})+ self.assertEqual([r["id"] for r in by_team.json()["results"]], [str(running_other_team.id)])++ by_search = self.client.get("/api/managed_migrations_support/", {"search": "Invalid JSON"})+ self.assertEqual([r["id"] for r in by_search.json()["results"]], [str(paused.id)])diff --git a/products/managed_migrations/backend/models/batch_import_utils.py b/products/managed_migrations/backend/models/batch_import_utils.pyindex f502f5d03e53..ae3f701d96ec 100644--- a/products/managed_migrations/backend/models/batch_import_utils.py+++ b/products/managed_migrations/backend/models/batch_import_utils.py@@ -1,7 +1,71 @@+import refrom typing import Optional+from urllib.parse import urlsplit, urlunsplitfrom posthog.models.user import User+# Matches scheme://... up to whitespace or a quote - the delimiters the worker uses+# when interpolating part keys/URLs into error messages. The match must end on a+# non-punctuation character so sentence punctuation after a URL ("<url>, retrying")+# stays in the surrounding text instead of being swallowed with the redacted query.+_URL_IN_TEXT_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://[^\s'\"]*[^\s'\".,;:!?)\]}>]")+++def redact_part_key(key: object) -> object:+ """Strip credential-bearing URL components from a worker part key.++ url_list imports use full source URLs as part keys, and those URLs live in the+ encrypted secrets column precisely because they can embed presigned tokens+ (query string) or basic-auth credentials (userinfo). The worker copies them+ verbatim into the plaintext state blob, so anything that surfaces a part key+ must redact those components. Scheme/host/path are kept so the part stays+ identifiable; non-URL keys (S3 object keys, date ranges, file paths) pass+ through unchanged, as do non-string values from a malformed state blob.+ """+ if not isinstance(key, str) or "://" not in key:+ return key+ try:+ parts = urlsplit(key)+ if not parts.scheme or not parts.netloc:+ return key+ host = parts.hostname or ""+ if parts.port is not None:+ host = f"{host}:{parts.port}"+ return urlunsplit((parts.scheme, host, parts.path, "", ""))+ except ValueError:+ # Unparseable URL-ish key (e.g. bad port/IPv6): fail closed rather than leak.+ return "[unparseable-url-redacted]"+++def redact_urls_in_json(value: object) -> object:+ """Recursively redact credential-bearing URL components in a JSON-shaped value.++ Applies `redact_urls_in_text` to every string leaf. Used on worker/operator-owned+ blobs (state, import_config) before they serialize into support responses, so any+ URL-bearing field - part keys, a custom S3 endpoint_url with userinfo, or fields+ added later - gets the same treatment without per-field allowlisting.+ """+ if isinstance(value, str):+ return redact_urls_in_text(value)+ if isinstance(value, dict):+ return {k: redact_urls_in_json(v) for k, v in value.items()}+ if isinstance(value, list):+ return [redact_urls_in_json(v) for v in value]+ return value+++def redact_urls_in_text(text: Optional[str]) -> Optional[str]:+ """Redact credential-bearing components of any URL embedded in free text.++ The worker interpolates part keys into status/display messages ("Parsing data+ in file '<key>' failed", size/validation errors), so for url_list sources those+ messages can carry the same presigned tokens and basic-auth credentials as the+ keys themselves. Applies `redact_part_key` to every URL-shaped substring.+ """+ if not text:+ return text+ return _URL_IN_TEXT_RE.sub(lambda m: str(redact_part_key(m.group(0))), text)+def extract_batch_import_info(batch_import) -> tuple[str, str, Optional[str], Optional[str]]:"""Extract source type, content type, start date, and end date from BatchImport"""diff --git a/products/managed_migrations/backend/models/batch_imports.py b/products/managed_migrations/backend/models/batch_imports.pyindex 79da32f685f5..dc6aaf0c7985 100644--- a/products/managed_migrations/backend/models/batch_imports.py+++ b/products/managed_migrations/backend/models/batch_imports.py@@ -7,6 +7,8 @@ from posthog.helpers.encrypted_fields import EncryptedJSONStringFieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import UUIDTModel+from products.managed_migrations.backend.models.batch_import_utils import redact_part_key+class DateRangeExportSource(str, Enum):MIXPANEL = "mixpanel"@@ -120,8 +122,11 @@ class BatchImport(ModelActivityMixin, UUIDTModel):# a nondeterministic export can have a different decompressed size.inflight["total_size"] = None- self._flip_to_running(f"Resumed by admin with part {inflight['key']} reset to offset 0")- return inflight["key"]+ # Redacted: url_list part keys are full source URLs whose query string /+ # userinfo can carry credentials, and status_message is broadly visible.+ redacted_key = str(redact_part_key(inflight.get("key")))+ self._flip_to_running(f"Resumed by admin with part {redacted_key} reset to offset 0")+ return redacted_keydef _flip_to_running(self, status_message: str) -> None:self.status = BatchImport.Status.RUNNINGdiff --git a/products/managed_migrations/backend/routes.py b/products/managed_migrations/backend/routes.pyindex c00c9c695b11..4c796309263c 100644--- a/products/managed_migrations/backend/routes.py+++ b/products/managed_migrations/backend/routes.py@@ -1,6 +1,7 @@from posthog.api.routing import RouterRegistryfrom products.managed_migrations.backend.api.batch_imports import BatchImportViewSet+from products.managed_migrations.backend.api.support_batch_imports import BatchImportSupportViewSetdef register_routes(routers: RouterRegistry) -> None:@@ -10,3 +11,9 @@ def register_routes(routers: RouterRegistry) -> None:"project_managed_migrations",["project_id"],)+ # Staff-only cross-team diagnostics: root-level so it is not team-nested.+ routers.root.register(+ r"managed_migrations_support",+ BatchImportSupportViewSet,+ "managed_migrations_support",+ )diff --git a/products/managed_migrations/docs/support-mcp-tools.md b/products/managed_migrations/docs/support-mcp-tools.mdnew file mode 100644index 000000000000..14dd257cd2d3--- /dev/null+++ b/products/managed_migrations/docs/support-mcp-tools.md@@ -0,0 +1,105 @@+# Staff support MCP tools: setup guide++The managed migrations support tools let PostHog staff triage customer batch imports (managed migrations) from any MCP client — Claude Code, Claude Desktop, Cursor — instead of Django admin.++- `managed-migrations-support-list` — list batch import jobs across **all** teams, filterable by `team_id`, `status`, or free-text search+- `managed-migrations-support-get` — one job by UUID, including the raw worker `state` and `import_config` blobs++Both are read-only.+Mutations (resume, pause, in-flight part reset) remain Django admin actions for now.+Credential values (`secrets`) are never returned by any of these surfaces, and every staff read is audit-logged.++## Who can use this++PostHog staff only (`is_staff = True` on your PostHog cloud user).+Everything below fails closed for non-staff users: the tools never appear in their MCP clients, and the API returns 403 even with a correctly-scoped key.++## Step 1: mint the personal API key++The `batch_import_support:read` scope is **hidden from the key-creation UI** and can never be granted through OAuth,+so minting takes two steps — create the key normally, then add the hidden scope via Django admin:++1. In the PostHog UI on the region you want to inspect, go to **Settings → Personal API keys** and create a key with the **User: Read** scope and **no organization/project restriction** (the endpoint rejects scoped keys). Copy the `phx_...` value — it is shown only once.+2. In Django admin (`/admin/posthog/personalapikey/`), open your new key and add `batch_import_support:read` to its `scopes` list, then save. Do this **before** first using the key with MCP — the MCP server caches a token's scopes on first use.++<details>+<summary>Alternative: one-shot mint from the browser console</summary>++While logged in, on any PostHog app page:++```js+await fetch('/api/personal_api_keys/', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-Csrftoken': document.cookie.match(/posthog_csrftoken=([^;]+)/)[1],+ },+ body: JSON.stringify({ label: 'migrations support', scopes: ['batch_import_support:read', 'user:read'] }),+}).then((r) => r.json())+```++The CSRF header is required — session-authenticated POSTs are CSRF-protected.+If you get `sensitive_action_required_reauth`, key creation needs a recently-authenticated session: log out, log back in, retry.++</details>++Rules that will bite you if skipped:++- **Both scopes are required for MCP.** `batch_import_support:read` authorizes the endpoints; `user:read` lets MCP tool discovery confirm you are staff via `/api/users/@me/`. Without `user:read` the tools silently never appear (the check fails closed).+- **`*` (full access) does not work.** The backend rejects wildcard keys on this endpoint, and tool discovery requires the hidden scope to be listed explicitly.+- **The key must be unscoped** — no `scoped_teams` / `scoped_organizations`. The endpoint is root-level and cross-team by design; scoped keys are rejected there.+- **One key per region.** US and EU are separate deployments with separate users and keys — repeat the mint on each region you support. `user:read` also powers the region routing: the MCP server probes both regions with your token via `/api/users/@me/`, so a key missing it misroutes (defaults to US) on top of hiding the tools.++## Step 2: connect your MCP client++Add the PostHog MCP server with the key as a bearer token.+The URL is the same for both regions — the server probes US and EU with your token and routes to the region that recognizes it, so the token itself selects the region.+For Claude Code, one entry per region you support:++```json+{+ "mcpServers": {+ "posthog-us": {+ "type": "http",+ "url": "https://mcp.posthog.com/mcp",+ "headers": { "Authorization": "Bearer ${POSTHOG_SUPPORT_PAT_US}" }+ },+ "posthog-eu": {+ "type": "http",+ "url": "https://mcp.posthog.com/mcp",+ "headers": { "Authorization": "Bearer ${POSTHOG_SUPPORT_PAT_EU}" }+ }+ }+}+```++Keep the tokens in env vars or a secret manager rather than inline.+Both connections can coexist with your everyday PostHog MCP connection — tools are namespaced per server, so the staff tools stay out of your daily driver's tool list.++Do **not** sign in via the OAuth browser flow — OAuth tokens structurally cannot carry the hidden scope, so the support tools will never appear on an OAuth connection.+The bearer-header PAT is the only path.++A note on scoping: a minimal support key (`batch_import_support:read` + `user:read`) surfaces only the two staff tools plus scope-free utilities — every other tool needs scopes the key lacks.+That's the recommended least-privilege setup for a dedicated support connection.+If you want one key that also carries the full normal toolset, mint it with `["*", "batch_import_support:read"]` — the `*` unlocks everything else while the explicit hidden scope satisfies the staff gate — at the cost of a much more powerful credential sitting in your config.++## Step 3: verify++Ask your agent to list managed migration support tools, or search for `managed-migrations-support`.+With the key above you should see both tools; a quick smoke test is listing imports for a known team id.++If the tools don't appear, check in order:++1. Key has `batch_import_support:read` **explicitly** (not via `*`)+2. Key has `user:read` (or `*` alongside the explicit support scope)+3. Your user is staff on that region+4. The key is unscoped and you're connected to the right region+5. Fresh key: the MCP server caches a token's scopes, so a key whose scopes were edited after first use can serve stale results — mint a new one++## How it's enforced (for the curious)++The MCP-side filtering is presentation, not security: it exists so staff-only tools never pollute customer tool lists.+The security boundary is the Django endpoint (`/api/managed_migrations_support/`), which requires an authenticated staff user plus the explicit scope, rejects wildcard keys, and audit-logs every read.+See `products/managed_migrations/backend/api/support_batch_imports.py` and `services/mcp/src/lib/staff-only-tools.ts`.++For testing changes to any of this locally, use the [testing-mcp-tools-locally](../skills/testing-mcp-tools-locally/SKILL.md) skill.diff --git a/products/managed_migrations/frontend/generated/api.schemas.ts b/products/managed_migrations/frontend/generated/api.schemas.tsindex 777ea5db364f..8f437a00d6b5 100644--- a/products/managed_migrations/frontend/generated/api.schemas.ts+++ b/products/managed_migrations/frontend/generated/api.schemas.ts@@ -22,6 +22,262 @@ export const BatchImportStatusEnumApi = {Running: 'running',} as const+export type DisplayStatusEnumApi = (typeof DisplayStatusEnumApi)[keyof typeof DisplayStatusEnumApi]++export const DisplayStatusEnumApi = {+ WaitingToStart: 'waiting_to_start',+ Running: 'running',+ Paused: 'paused',+ Failed: 'failed',+ Completed: 'completed',+} as const++export interface BatchImportPartsProgressApi {+ /** Number of finished parts (a part is done when its committed byte offset has reached its known total size). */+ done: number+ /** Total number of parts the worker has planned for this import. */+ total: number+ /**+ * Key (file/date-range identifier) of the first unfinished part - the one in flight or next up. Null when all parts are done or the worker has not started. URL keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.+ * @nullable+ */+ inflight_key: string | null+ /**+ * Committed byte offset (decompressed) within the in-flight part. Null when there is no in-flight part.+ * @nullable+ */+ inflight_offset: number | null+ /**+ * Total decompressed size in bytes of the in-flight part, or null if the worker has not measured it yet.+ * @nullable+ */+ inflight_total_size: number | null+}++/**+ * Compact cross-team diagnostics view of a batch import job for PostHog support staff.+ *+ * Excludes the raw `state` / `import_config` blobs (see the detail serializer) and never+ * exposes the encrypted `secrets` column.+ */+export interface BatchImportSupportListApi {+ /** UUID of the batch import job. */+ readonly id: string+ /** ID of the team (project) the import belongs to. */+ team_id: number+ /** Name of the team the import belongs to. */+ team_name: string+ /** Raw persisted status of the job.+ *+ * * `completed` - Completed+ * * `failed` - Failed+ * * `paused` - Paused+ * * `running` - Running */+ status?: BatchImportStatusEnumApi+ /** Effective status: 'waiting_to_start' when the job is running but no worker has claimed it yet (lease_id is null), otherwise the raw status. */+ readonly display_status: DisplayStatusEnumApi+ /**+ * Developer-facing status message written by the worker or an operator - the primary debugging signal. Not shown to the customer. Embedded URLs have their query string and userinfo redacted, since url_list part keys can carry presigned tokens or credentials.+ * @nullable+ */+ readonly status_message: string | null+ /**+ * Customer-facing status message shown in the PostHog UI. Embedded URLs are redacted the same way as status_message.+ * @nullable+ */+ readonly display_status_message: string | null+ /** Worker part progress summary derived from the raw state blob. */+ readonly parts_progress: BatchImportPartsProgressApi+ /** Source the job imports from (e.g. s3, mixpanel, amplitude, urls, folder), or 'unknown' if unset. */+ readonly source_type: string+ /** Format of the source events (e.g. mixpanel, amplitude, captured), or 'unknown' if unset. */+ readonly content_type: string+ /**+ * Start of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_start_date: string | null+ /**+ * End of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_end_date: string | null+ /**+ * Where imported events are written (normally 'capture'; 'kafka'/'noop' for internal use), or null if unset.+ * @nullable+ */+ readonly sink_type: string | null+ /**+ * Configured sink send rate in events per second, or null if unset.+ * @nullable+ */+ readonly sink_send_rate: number | null+ /**+ * Lease token of the worker currently holding the job, or null when unclaimed. Claims lease for 30 minutes; the running heartbeat renews for 5 minutes.+ * @nullable+ */+ lease_id?: string | null+ /**+ * When the current worker lease expires.+ * @nullable+ */+ leased_until?: string | null+ /** True when the job holds a lease whose expiry is in the past. On a running job this means the worker died or the row is claimable again; the next poll can re-claim it. */+ readonly lease_expired: boolean+ /**+ * Consecutive transient-failure retries so far (0 = healthy).+ * @minimum -2147483648+ * @maximum 2147483647+ */+ backoff_attempt?: number+ /**+ * When the worker will retry after a transient failure. A future value means the job is in a retry loop, not stuck.+ * @nullable+ */+ backoff_until?: string | null+ /**+ * ID of the user who created the import, if any.+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ created_by_id?: number | null+ /** When the import was created. */+ readonly created_at: string+ /** Last write to the row - the worker heartbeats this while processing. */+ readonly updated_at: string+}++export interface PaginatedBatchImportSupportListListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: BatchImportSupportListApi[]+}++/**+ * Raw worker progress blob: {'parts': [{'key', 'current_offset', 'total_size'}]}. A part is done when current_offset >= total_size; parts are processed in order. URL part keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.+ * @nullable+ */+export type BatchImportSupportDetailApiState = { [key: string]: unknown } | null++/**+ * Source/format/sink configuration of the job. References secrets by key name only; secret values are never returned. Embedded URLs (e.g. a custom S3 endpoint_url) have their query string and userinfo redacted.+ * @nullable+ */+export type BatchImportSupportDetailApiImportConfig = { [key: string]: unknown } | null++/**+ * Full diagnostics view: adds the raw worker `state` and `import_config` blobs.+ *+ * `import_config` holds secret key *names* only - secret values live exclusively in the+ * encrypted `secrets` column, which no support serializer exposes.+ */+export interface BatchImportSupportDetailApi {+ /** UUID of the batch import job. */+ readonly id: string+ /** ID of the team (project) the import belongs to. */+ team_id: number+ /** Name of the team the import belongs to. */+ team_name: string+ /** Raw persisted status of the job.+ *+ * * `completed` - Completed+ * * `failed` - Failed+ * * `paused` - Paused+ * * `running` - Running */+ status?: BatchImportStatusEnumApi+ /** Effective status: 'waiting_to_start' when the job is running but no worker has claimed it yet (lease_id is null), otherwise the raw status. */+ readonly display_status: DisplayStatusEnumApi+ /**+ * Developer-facing status message written by the worker or an operator - the primary debugging signal. Not shown to the customer. Embedded URLs have their query string and userinfo redacted, since url_list part keys can carry presigned tokens or credentials.+ * @nullable+ */+ readonly status_message: string | null+ /**+ * Customer-facing status message shown in the PostHog UI. Embedded URLs are redacted the same way as status_message.+ * @nullable+ */+ readonly display_status_message: string | null+ /** Worker part progress summary derived from the raw state blob. */+ readonly parts_progress: BatchImportPartsProgressApi+ /** Source the job imports from (e.g. s3, mixpanel, amplitude, urls, folder), or 'unknown' if unset. */+ readonly source_type: string+ /** Format of the source events (e.g. mixpanel, amplitude, captured), or 'unknown' if unset. */+ readonly content_type: string+ /**+ * Start of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_start_date: string | null+ /**+ * End of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_end_date: string | null+ /**+ * Where imported events are written (normally 'capture'; 'kafka'/'noop' for internal use), or null if unset.+ * @nullable+ */+ readonly sink_type: string | null+ /**+ * Configured sink send rate in events per second, or null if unset.+ * @nullable+ */+ readonly sink_send_rate: number | null+ /**+ * Lease token of the worker currently holding the job, or null when unclaimed. Claims lease for 30 minutes; the running heartbeat renews for 5 minutes.+ * @nullable+ */+ lease_id?: string | null+ /**+ * When the current worker lease expires.+ * @nullable+ */+ leased_until?: string | null+ /** True when the job holds a lease whose expiry is in the past. On a running job this means the worker died or the row is claimable again; the next poll can re-claim it. */+ readonly lease_expired: boolean+ /**+ * Consecutive transient-failure retries so far (0 = healthy).+ * @minimum -2147483648+ * @maximum 2147483647+ */+ backoff_attempt?: number+ /**+ * When the worker will retry after a transient failure. A future value means the job is in a retry loop, not stuck.+ * @nullable+ */+ backoff_until?: string | null+ /**+ * ID of the user who created the import, if any.+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ created_by_id?: number | null+ /** When the import was created. */+ readonly created_at: string+ /** Last write to the row - the worker heartbeats this while processing. */+ readonly updated_at: string+ /**+ * Raw worker progress blob: {'parts': [{'key', 'current_offset', 'total_size'}]}. A part is done when current_offset >= total_size; parts are processed in order. URL part keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.+ * @nullable+ */+ readonly state: BatchImportSupportDetailApiState+ /**+ * Source/format/sink configuration of the job. References secrets by key name only; secret values are never returned. Embedded URLs (e.g. a custom S3 endpoint_url) have their query string and userinfo redacted.+ * @nullable+ */+ readonly import_config: BatchImportSupportDetailApiImportConfig+ /**+ * Email of the user who created the import, if known.+ * @nullable+ */+ readonly created_by_email: string | null+}+/*** @nullable*/@@ -75,6 +331,43 @@ export interface PatchedBatchImportApi {readonly import_config?: unknown}+export type ManagedMigrationsSupportListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Which field to use when ordering the results.+ */+ ordering?: string+ /**+ * A search term.+ */+ search?: string+ /**+ * * `completed` - Completed+ * * `failed` - Failed+ * * `paused` - Paused+ * * `running` - Running+ */+ status?: ManagedMigrationsSupportListStatus+ team_id?: number+}++export type ManagedMigrationsSupportListStatus =+ (typeof ManagedMigrationsSupportListStatus)[keyof typeof ManagedMigrationsSupportListStatus]++export const ManagedMigrationsSupportListStatus = {+ Completed: 'completed',+ Failed: 'failed',+ Paused: 'paused',+ Running: 'running',+} as const+export type ManagedMigrationsListParams = {/*** Number of results to return per page.diff --git a/products/managed_migrations/frontend/generated/api.ts b/products/managed_migrations/frontend/generated/api.tsindex 752c742cc10f..5242933fdbfe 100644--- a/products/managed_migrations/frontend/generated/api.ts+++ b/products/managed_migrations/frontend/generated/api.ts@@ -10,8 +10,11 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'*/import type {BatchImportApi,+ BatchImportSupportDetailApi,ManagedMigrationsListParams,+ ManagedMigrationsSupportListParams,PaginatedBatchImportListApi,+ PaginatedBatchImportSupportListListApi,PatchedBatchImportApi,} from './api.schemas'@@ -32,6 +35,52 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getManagedMigrationsSupportListUrl = (params?: ManagedMigrationsSupportListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/managed_migrations_support/?${stringifiedParams}`+ : `/api/managed_migrations_support/`+}++/**+ * List batch import (managed migration) jobs across all teams. PostHog staff only.+ */+export const managedMigrationsSupportList = async (+ params?: ManagedMigrationsSupportListParams,+ options?: RequestInit+): Promise<PaginatedBatchImportSupportListListApi> => {+ return apiMutator<PaginatedBatchImportSupportListListApi>(getManagedMigrationsSupportListUrl(params), {+ ...options,+ method: 'GET',+ })+}++export const getManagedMigrationsSupportRetrieveUrl = (id: string) => {+ return `/api/managed_migrations_support/${id}/`+}++/**+ * Get one batch import job with its raw worker state and import config. PostHog staff only.+ */+export const managedMigrationsSupportRetrieve = async (+ id: string,+ options?: RequestInit+): Promise<BatchImportSupportDetailApi> => {+ return apiMutator<BatchImportSupportDetailApi>(getManagedMigrationsSupportRetrieveUrl(id), {+ ...options,+ method: 'GET',+ })+}+export const getManagedMigrationsListUrl = (projectId: string, params?: ManagedMigrationsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/managed_migrations/mcp/prompts/managed-migrations-support-get.md b/products/managed_migrations/mcp/prompts/managed-migrations-support-get.mdnew file mode 100644index 000000000000..42c9436ea942--- /dev/null+++ b/products/managed_migrations/mcp/prompts/managed-migrations-support-get.md@@ -0,0 +1,9 @@+Get one batch import (managed migration) job by id, from any PostHog team, including the raw worker `state` and `import_config` blobs. PostHog staff only: the backend requires a staff user AND a personal API key explicitly carrying the `batch_import_support:read` scope (a full-access `*` key is rejected; OAuth sign-in can never grant it).++Adds to the list fields:++- `state`: the worker-owned progress blob, `{"parts": [{"key", "current_offset", "total_size"}]}`. A part is done when `current_offset >= total_size`; parts are processed in order, so the first unfinished part is the one in flight. `current_offset` is a byte offset into the DECOMPRESSED part - only meaningful against the exact byte stream it was measured on.+- `import_config`: the job's source / data format / sink configuration. It references credentials by secret key NAME only; secret values live in an encrypted column that is never returned by any API.+- `created_by_email`: who started the migration, when known.++Troubleshooting reminders (same semantics as the list tool): `waiting_to_start` = running with no worker lease yet; `lease_expired: true` on a running job = the worker died or the job is about to be re-claimed; a `paused` job keeps its lease and resuming (a Django admin action - this API is read-only) must clear it; `paused` with an invalid-JSON parse error at the resume point usually means the source bytes changed under the committed offset and the in-flight part needs a reset to offset 0 via Django admin's "Resume + re-import in-flight part".diff --git a/products/managed_migrations/mcp/prompts/managed-migrations-support-list.md b/products/managed_migrations/mcp/prompts/managed-migrations-support-list.mdnew file mode 100644index 000000000000..1d2b5159e2f6--- /dev/null+++ b/products/managed_migrations/mcp/prompts/managed-migrations-support-list.md@@ -0,0 +1,15 @@+List batch import (managed migration) jobs across ALL PostHog teams, for troubleshooting customer migrations. PostHog staff only: the backend requires a staff user AND a personal API key explicitly carrying the `batch_import_support:read` scope. A full-access (`*`) key is rejected; OAuth sign-in can never grant this scope.++Filter with `team_id` (the customer's project id) or `status` (`running`, `paused`, `failed`, `completed`), or `search` (matches the developer status message and team name). Results are newest-first.++How to read a job's state:++- `display_status: waiting_to_start` means the job is `running` but no worker has claimed it yet (`lease_id` is null) - it is queued, not stuck.+- Workers hold a lease per job: 30 minutes on initial claim, renewed for 5 minutes on each heartbeat. `lease_expired: true` on a `running` job means the worker died or the row is about to be re-claimed by the next worker poll.+- A `paused` job KEEPS its worker lease; resuming requires clearing the lease (a Django admin action today - this API is read-only).+- `paused` with a `status_message` mentioning invalid JSON syntax at the resume point usually means a poisoned byte offset: the source bytes changed under the committed offset (re-downloaded nondeterministic export or replaced source file). The fix is Django admin's "Resume + re-import in-flight part", which resets the in-flight part to offset 0 (safe for Mixpanel/Amplitude, which dedupe by deterministic event UUID).+- `backoff_until` in the future means the job is in a transient-failure retry loop (`backoff_attempt` counts consecutive retries), not stuck.+- `parts_progress` summarizes the worker's units of work: a part is done when its committed byte offset reaches its total size; parts are processed in order, so the in-flight part is the first unfinished one.+- `status_message` is the developer-facing debugging signal; `display_status_message` is what the customer sees in the PostHog UI.++Use `managed-migrations-support-get` with a job id for the raw worker `state` and `import_config` blobs. Credentials (`secrets`) are never returned.diff --git a/products/managed_migrations/mcp/tools.yaml b/products/managed_migrations/mcp/tools.yamlnew file mode 100644index 000000000000..2b810b360c6a--- /dev/null+++ b/products/managed_migrations/mcp/tools.yaml@@ -0,0 +1,58 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Managed migrations+feature: managed_migrations+url_prefix: /managed_migrations+ui_apps: {}+tools:+ managed-migrations-create:+ operation: managed_migrations_create+ enabled: false+ managed-migrations-destroy:+ operation: managed_migrations_destroy+ enabled: false+ managed-migrations-list:+ operation: managed_migrations_list+ enabled: false+ managed-migrations-partial-update:+ operation: managed_migrations_partial_update+ enabled: false+ managed-migrations-pause-create:+ operation: managed_migrations_pause_create+ enabled: false+ managed-migrations-resume-create:+ operation: managed_migrations_resume_create+ enabled: false+ managed-migrations-retrieve:+ operation: managed_migrations_retrieve+ enabled: false+ managed-migrations-support-get:+ operation: managed_migrations_support_retrieve+ enabled: true+ scopes:+ - batch_import_support:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get one batch import job with raw worker state (PostHog staff only)+ description_file: ./prompts/managed-migrations-support-get.md+ managed-migrations-support-list:+ operation: managed_migrations_support_list+ enabled: true+ scopes:+ - batch_import_support:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List batch import jobs across all teams (PostHog staff only)+ description_file: ./prompts/managed-migrations-support-list.md+ managed-migrations-update:+ operation: managed_migrations_update+ enabled: falsediff --git a/products/managed_migrations/skills/testing-mcp-tools-locally/SKILL.md b/products/managed_migrations/skills/testing-mcp-tools-locally/SKILL.mdnew file mode 100644index 000000000000..0295c0da4ee0--- /dev/null+++ b/products/managed_migrations/skills/testing-mcp-tools-locally/SKILL.md@@ -0,0 +1,218 @@+---+name: testing-mcp-tools-locally+description: >+ Set up the local dev environment, seed data, and API keys to test the staff-only managed migrations+ MCP tools (managed-migrations-support-list, managed-migrations-support-get) end to end.+ Use when testing batch import support tooling, debugging MCP tool responses or discovery+ (tools not appearing), or verifying the support API before deploying.+ Covers the discovery gate: hidden scope, is_staff, user:read, and why wildcard keys and OAuth never work.+---++# Testing managed migrations MCP tools locally++## Prerequisites++The dev environment must be running with Docker services healthy.+The batch import support API and MCP tools require:++- A staff user (`is_staff = True`)+- A Personal API Key carrying **both** `batch_import_support:read` and `user:read`, explicitly+- Postgres migrations applied (ClickHouse not required)++Why both scopes: the backend accepts `batch_import_support:read` alone,+but MCP tool discovery verifies staffness via `/api/users/@me/` and hides the tools (fail-closed) when the key cannot make that call.+A `*` wildcard does **not** substitute for either — the discovery gate requires the hidden scope explicitly, and the backend's `INTERNAL` scope handling rejects wildcard keys outright.+For the production setup flow, see [docs/support-mcp-tools.md](../../docs/support-mcp-tools.md).++## 1. Start the dev environment++```bash+hogli start -d+hogli wait+```++If `hogli wait` fails on `migrate-persons-db` or `migrate-behavioral-cohorts`,+those are optional separate databases — ignore them.+If it fails on `migrate-postgres`, check Docker port forwarding (see troubleshooting below).++## 2. Run Postgres migrations++```bash+hogli migrations:run+```++ClickHouse migration failures are fine — batch imports only need Postgres.++## 3. Verify DB connectivity from the Django shell++```bash+hogli dev:shell-plus -y -- -c "+from posthog.models import Team, User+print(Team.objects.first(), User.objects.first())+"+```++If this fails with `connection refused` on port 5432, see troubleshooting below.++## 4. Seed batch import test data++Use `hogli dev:shell-plus` to create `BatchImport` records in various states.+The `secrets` field is an `EncryptedJSONStringField` — empty `{}` serializes to null+and violates the NOT NULL constraint; always pass a non-empty dict.++```python+from products.managed_migrations.backend.models.batch_imports import BatchImport++BatchImport.objects.create(+ team=team,+ created_by_id=user.id,+ status=BatchImport.Status.PAUSED,+ import_config={+ 'source': {'type': 's3', 'bucket': 'test', 'region': 'us-east-1', 'prefix': 'data/'},+ 'data_format': {'type': 'json_lines', 'skip_blanks': True, 'content': {'type': 'mixpanel'}},+ 'sink': {'type': 'capture'},+ },+ secrets={'access_key': 'test', 'secret_key': 'test'},+ state={'parts': [+ {'key': 'part-1', 'current_offset': 50000, 'total_size': 50000},+ {'key': 'part-2', 'current_offset': 10000, 'total_size': 50000},+ {'key': 'part-3'},+ ]},+)+```++See `references/seed-data.md` for a full seeding script covering all statuses.++**Important:** the local `batch-import-worker` process will pick up `RUNNING` records+and may modify their status (e.g. pausing them due to config validation errors).+To keep records stable for testing, either stop the worker or use `COMPLETED`/`FAILED`/`PAUSED` statuses.++## 5. Make your user staff and mint test keys++Mint **fresh** keys rather than editing scopes on an existing one —+the MCP server caches a key's scopes per token, so edited scopes can serve stale results.++```python+from posthog.models import User+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value++me = User.objects.first()+me.is_staff = True; me.save()++def mint(user, scopes):+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(user=user, label=str(scopes)[:40], secure_value=hash_key_value(token), scopes=scopes)+ return token++print(mint(me, ["batch_import_support:read", "user:read"]))+```++To test the negative cases of the discovery gate, also mint:+a `["*"]` key (tools must NOT appear),+a `["batch_import_support:read"]` key without `user:read` (tools must NOT appear — staff lookup fails closed),+and the full pair on a non-staff user (tools must NOT appear).++## 6. Test the API directly++```bash+# List all batch imports+curl -H "Authorization: Bearer <token>" \+ http://localhost:8010/api/managed_migrations_support/ | jq++# Get detail for a specific import+curl -H "Authorization: Bearer <token>" \+ http://localhost:8010/api/managed_migrations_support/<uuid>/ | jq+```++## 7. Test via MCP++**Run the Hono server, not `pnpm run dev`.**+The wrangler worker (`pnpm run dev`, port 8787) proxies `/mcp` to **production** `mcp.us.posthog.com` unless `MCP_HONO_URL` is set,+so local keys get `401 Invalid API key`.+The Hono server serves MCP directly against the local API:++```bash+cd services/mcp+cp .dev.vars.example .dev.vars # POSTHOG_API_BASE_URL=http://localhost:8010+pnpm run dev:hono # serves http://localhost:3001/mcp+```++**Authenticate with the PAT as a Bearer header, never the OAuth flow.**+The hidden scope is structurally absent from OAuth — signing in through the inspector's OAuth login can never surface these tools.++The Hono server runs exec mode: `tools/list` returns a single `exec` tool,+and real tools are discovered and invoked through it.+Test with the MCP Inspector CLI:++```bash+# Discovery — should list both support tools for the staff key, none for the others+npx @modelcontextprotocol/inspector --cli http://localhost:3001/mcp \+ --header "Authorization: Bearer <token>" \+ --method tools/call --tool-name exec --tool-arg "command=search managed-migrations-support"++# Invocation — end-to-end through Django+npx @modelcontextprotocol/inspector --cli http://localhost:3001/mcp \+ --header "Authorization: Bearer <token>" \+ --method tools/call --tool-name exec --tool-arg "command=call managed-migrations-support-list {}"+```++Expected discovery matrix:++| key | tools visible |+| ----------------------------------------------------------- | -------------------------------- |+| staff user, `batch_import_support:read` + `user:read` | both |+| staff user, `*` only | none |+| staff user, `batch_import_support:read` without `user:read` | none (staff lookup fails closed) |+| non-staff user, both scopes | none (and direct API calls 403) |++The interactive Inspector UI (`http://localhost:6274`) also works —+paste the PAT as the Bearer token in connection settings instead of using its OAuth login.++## Troubleshooting++### 401 "Invalid API key" from localhost:8787++You're talking to the wrangler worker, which proxies `/mcp` to production — your local key is invalid there.+Use the Hono server on port 3001 (see step 7), or set `MCP_HONO_URL=http://localhost:3001` in `.dev.vars`.++### Tools don't appear for a key that should see them++Check, in order:++1. The key carries `batch_import_support:read` **explicitly** — `*` does not match hidden scopes.+2. The key also carries `user:read` (or `*`) — the discovery staff check reads `/api/users/@me/` and fails closed.+3. The key's user has `is_staff = True`.+4. The key was minted with those scopes from the start — the MCP server caches scopes per token, so mint a fresh key instead of editing an existing one.++### Port 5432 not reachable from host++The `posthog-db-1` Docker container may have stale port mappings+(container created days ago without the current port binding config).+Fix by force-recreating:++```bash+docker compose -f docker-compose.dev.yml -f docker-compose.profiles.yml \+ up -d --force-recreate db+```++Verify: `nc -z 127.0.0.1 5432` should succeed.++### `secrets={}` causes NOT NULL violation++`EncryptedJSONStringField` encrypts the value — an empty dict serializes to null.+Always pass a non-empty dict: `secrets={'placeholder': 'true'}`.++### Batch import worker modifies seeded records++The local `batch-import-worker` process automatically claims `RUNNING` records.+If it encounters a config validation error (e.g. missing `skip_blanks`),+it will pause the import with a detailed Rust backtrace in `status_message`.+Stop the worker or seed with non-`RUNNING` statuses to prevent this.++### The gates, end to end++A request passes through two independent layers:++1. **MCP discovery** (presentation): a tool requiring an OAuth-hidden scope surfaces only when the key explicitly carries the scope AND `/api/users/@me/` confirms `is_staff` — otherwise it is hidden, fail-closed (`services/mcp/src/lib/staff-only-tools.ts`).+2. **Django enforcement** (the security boundary): `IsAuthenticated` + `IsStaffUser` + `APIScopePermission` with `scope_object = "INTERNAL"` and `batch_import_support:read`. Sessions need staffness only; PATs need staffness plus the explicit scope; `*`-only keys always 403.diff --git a/products/managed_migrations/skills/testing-mcp-tools-locally/references/seed-data.md b/products/managed_migrations/skills/testing-mcp-tools-locally/references/seed-data.mdnew file mode 100644index 000000000000..8fc4f919204b--- /dev/null+++ b/products/managed_migrations/skills/testing-mcp-tools-locally/references/seed-data.md@@ -0,0 +1,169 @@+# Seed data script++Run this via `hogli dev:shell-plus -y -- -c "<script>"`.+It creates 6 batch imports covering all statuses and edge cases.++```python+from products.managed_migrations.backend.models.batch_imports import BatchImport+from posthog.models import Team, User+from datetime import timedelta+from django.utils.timezone import now++team = Team.objects.first()+team2 = Team.objects.all()[1] if Team.objects.count() > 1 else team+user = User.objects.first()++# 1. Running — actively processing with progress+BatchImport.objects.create(+ team=team,+ created_by_id=user.id,+ status=BatchImport.Status.RUNNING,+ lease_id='worker-abc123',+ leased_until=now() + timedelta(minutes=25),+ status_message='Processing S3 files from mixpanel export',+ display_status_message='Import in progress',+ import_config={+ 'source': {'type': 's3', 'bucket': 'acme-mixpanel-export', 'region': 'us-east-1', 'prefix': 'events/2024/'},+ 'data_format': {'type': 'json_lines', 'skip_blanks': True, 'content': {'type': 'mixpanel'}},+ 'sink': {'type': 'capture'},+ 'import_events': True,+ 'generate_identify_events': True,+ },+ secrets={'access_key': 'test-key', 'secret_key': 'test-secret'},+ state={+ 'parts': [+ {'key': 'events/2024/01/', 'current_offset': 50000, 'total_size': 50000},+ {'key': 'events/2024/02/', 'current_offset': 50000, 'total_size': 50000},+ {'key': 'events/2024/03/', 'current_offset': 32000, 'total_size': 50000},+ {'key': 'events/2024/04/', 'current_offset': 0, 'total_size': 50000},+ {'key': 'events/2024/05/'},+ ]+ },+)++# 2. Completed+BatchImport.objects.create(+ team=team,+ created_by_id=user.id,+ status=BatchImport.Status.COMPLETED,+ status_message='Successfully imported 1.2M events',+ display_status_message='Import completed successfully',+ import_config={+ 'source': {'type': 's3', 'bucket': 'acme-amplitude-data', 'region': 'eu-west-1', 'prefix': 'export/'},+ 'data_format': {'type': 'json_lines', 'skip_blanks': True, 'content': {'type': 'amplitude'}},+ 'sink': {'type': 'capture'},+ 'import_events': True,+ },+ secrets={'access_key': 'test-key', 'secret_key': 'test-secret'},+ state={+ 'parts': [+ {'key': 'export/part-001.jsonl', 'current_offset': 100000, 'total_size': 100000},+ {'key': 'export/part-002.jsonl', 'current_offset': 100000, 'total_size': 100000},+ {'key': 'export/part-003.jsonl', 'current_offset': 100000, 'total_size': 100000},+ ]+ },+)++# 3. Failed — parse error+BatchImport.objects.create(+ team=team2,+ created_by_id=user.id,+ status=BatchImport.Status.FAILED,+ status_message='JSONDecodeError at offset 45232 in part events/march.jsonl',+ display_status_message='Import failed due to invalid data format',+ import_config={+ 'source': {'type': 's3', 'bucket': 'customer-events-bucket', 'region': 'us-west-2', 'prefix': 'events/'},+ 'data_format': {'type': 'json_lines', 'skip_blanks': False, 'content': {'type': 'captured'}},+ 'sink': {'type': 'capture'},+ },+ secrets={'access_key': 'test-key', 'secret_key': 'test-secret'},+ state={+ 'parts': [+ {'key': 'events/january.jsonl', 'current_offset': 80000, 'total_size': 80000},+ {'key': 'events/february.jsonl', 'current_offset': 80000, 'total_size': 80000},+ {'key': 'events/march.jsonl', 'current_offset': 45232, 'total_size': 80000},+ ]+ },+ backoff_attempt=5,+ backoff_until=now() + timedelta(hours=1),+)++# 4. Paused — with expired lease+BatchImport.objects.create(+ team=team2,+ created_by_id=user.id,+ status=BatchImport.Status.PAUSED,+ status_message='Paused by support staff for investigation',+ display_status_message='Import paused',+ lease_id='worker-xyz789',+ leased_until=now() - timedelta(hours=2),+ import_config={+ 'source': {'type': 's3_gzip', 'bucket': 'big-data-import', 'region': 'ap-southeast-1', 'prefix': 'compressed/'},+ 'data_format': {'type': 'json_lines', 'skip_blanks': True, 'content': {'type': 'mixpanel'}},+ 'sink': {'type': 'capture'},+ },+ secrets={'access_key': 'test-key', 'secret_key': 'test-secret'},+ state={+ 'parts': [+ {'key': 'compressed/batch-001.jsonl.gz', 'current_offset': 25000, 'total_size': 100000},+ ]+ },+)++# 5. Waiting to start — running status but no lease+BatchImport.objects.create(+ team=team,+ created_by_id=user.id,+ status=BatchImport.Status.RUNNING,+ status_message='Queued for processing',+ display_status_message='Waiting to start',+ import_config={+ 'source': {'type': 'url_list'},+ 'data_format': {'type': 'json_lines', 'skip_blanks': True, 'content': {'type': 'captured'}},+ 'sink': {'type': 'capture'},+ },+ secrets={'placeholder': 'true'},+)++# 6. Retrying — running with backoff+BatchImport.objects.create(+ team=team,+ created_by_id=user.id,+ status=BatchImport.Status.RUNNING,+ status_message='Retrying after transient S3 error: SlowDown',+ display_status_message='Import temporarily paused, retrying soon',+ lease_id='worker-retry-001',+ leased_until=now() + timedelta(minutes=10),+ import_config={+ 'source': {'type': 's3', 'bucket': 'massive-import', 'region': 'us-east-1', 'prefix': 'data/'},+ 'data_format': {'type': 'json_lines', 'skip_blanks': True, 'content': {'type': 'captured'}},+ 'sink': {'type': 'capture'},+ },+ secrets={'access_key': 'test-key', 'secret_key': 'test-secret'},+ state={+ 'parts': [+ {'key': 'data/chunk-1.jsonl', 'current_offset': 500000, 'total_size': 500000},+ {'key': 'data/chunk-2.jsonl', 'current_offset': 500000, 'total_size': 500000},+ {'key': 'data/chunk-3.jsonl', 'current_offset': 120000, 'total_size': 500000},+ {'key': 'data/chunk-4.jsonl', 'current_offset': 0, 'total_size': 500000},+ {'key': 'data/chunk-5.jsonl'},+ {'key': 'data/chunk-6.jsonl'},+ ]+ },+ backoff_attempt=2,+ backoff_until=now() + timedelta(minutes=3),+)++print(f'Seeded {BatchImport.objects.count()} batch imports')+```++## Edge cases covered++| Record | Status | Key diagnostic signal |+| ------ | ------------------ | ------------------------------------------------- |+| 1 | Running | Active lease, partial progress (2/5 parts done) |+| 2 | Completed | All parts done, no lease |+| 3 | Failed | Parse error, high backoff attempt |+| 4 | Paused | Expired lease (leased_until in past) |+| 5 | Running (no lease) | `display_status` derived as `waiting_to_start` |+| 6 | Running (backoff) | Active backoff, partial progress (2/6 parts done) |diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 98e7244188a8..a52946a97844 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5792,6 +5792,34 @@"readOnlyHint": true}},+ "managed-migrations-support-get": {+ "description": "Get one batch import (managed migration) job by id, from any PostHog team, including the raw worker `state` and `import_config` blobs. PostHog staff only: the backend requires a staff user AND a personal API key explicitly carrying the `batch_import_support:read` scope (a full-access `*` key is rejected; OAuth sign-in can never grant it).\n\nAdds to the list fields:\n\n- `state`: the worker-owned progress blob, `{\"parts\": [{\"key\", \"current_offset\", \"total_size\"}]}`. A part is done when `current_offset >= total_size`; parts are processed in order, so the first unfinished part is the one in flight. `current_offset` is a byte offset into the DECOMPRESSED part - only meaningful against the exact byte stream it was measured on.\n- `import_config`: the job's source / data format / sink configuration. It references credentials by secret key NAME only; secret values live in an encrypted column that is never returned by any API.\n- `created_by_email`: who started the migration, when known.\n\nTroubleshooting reminders (same semantics as the list tool): `waiting_to_start` = running with no worker lease yet; `lease_expired: true` on a running job = the worker died or the job is about to be re-claimed; a `paused` job keeps its lease and resuming (a Django admin action - this API is read-only) must clear it; `paused` with an invalid-JSON parse error at the resume point usually means the source bytes changed under the committed offset and the in-flight part needs a reset to offset 0 via Django admin's \"Resume + re-import in-flight part\".",+ "category": "Managed migrations",+ "feature": "managed_migrations",+ "summary": "Get one batch import job with raw worker state (PostHog staff only)",+ "title": "Get one batch import job with raw worker state (PostHog staff only)",+ "required_scopes": ["batch_import_support:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "managed-migrations-support-list": {+ "description": "List batch import (managed migration) jobs across ALL PostHog teams, for troubleshooting customer migrations. PostHog staff only: the backend requires a staff user AND a personal API key explicitly carrying the `batch_import_support:read` scope. A full-access (`*`) key is rejected; OAuth sign-in can never grant this scope.\n\nFilter with `team_id` (the customer's project id) or `status` (`running`, `paused`, `failed`, `completed`), or `search` (matches the developer status message and team name). Results are newest-first.\n\nHow to read a job's state:\n\n- `display_status: waiting_to_start` means the job is `running` but no worker has claimed it yet (`lease_id` is null) - it is queued, not stuck.\n- Workers hold a lease per job: 30 minutes on initial claim, renewed for 5 minutes on each heartbeat. `lease_expired: true` on a `running` job means the worker died or the row is about to be re-claimed by the next worker poll.\n- A `paused` job KEEPS its worker lease; resuming requires clearing the lease (a Django admin action today - this API is read-only).\n- `paused` with a `status_message` mentioning invalid JSON syntax at the resume point usually means a poisoned byte offset: the source bytes changed under the committed offset (re-downloaded nondeterministic export or replaced source file). The fix is Django admin's \"Resume + re-import in-flight part\", which resets the in-flight part to offset 0 (safe for Mixpanel/Amplitude, which dedupe by deterministic event UUID).\n- `backoff_until` in the future means the job is in a transient-failure retry loop (`backoff_attempt` counts consecutive retries), not stuck.\n- `parts_progress` summarizes the worker's units of work: a part is done when its committed byte offset reaches its total size; parts are processed in order, so the in-flight part is the first unfinished one.\n- `status_message` is the developer-facing debugging signal; `display_status_message` is what the customer sees in the PostHog UI.\n\nUse `managed-migrations-support-get` with a job id for the raw worker `state` and `import_config` blobs. Credentials (`secrets`) are never returned.",+ "category": "Managed migrations",+ "feature": "managed_migrations",+ "summary": "List batch import jobs across all teams (PostHog staff only)",+ "title": "List batch import jobs across all teams (PostHog staff only)",+ "required_scopes": ["batch_import_support:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"marketing-analytics-conversion-goals": {"description": "List the configured marketing conversion goals for the current project. Each goal returns its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.","category": "Marketing analytics",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex c8b8316f6e33..4347f3f71096 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6227,6 +6227,34 @@"readOnlyHint": true}},+ "managed-migrations-support-get": {+ "description": "Get one batch import (managed migration) job by id, from any PostHog team, including the raw worker `state` and `import_config` blobs. PostHog staff only: the backend requires a staff user AND a personal API key explicitly carrying the `batch_import_support:read` scope (a full-access `*` key is rejected; OAuth sign-in can never grant it).\n\nAdds to the list fields:\n\n- `state`: the worker-owned progress blob, `{\"parts\": [{\"key\", \"current_offset\", \"total_size\"}]}`. A part is done when `current_offset >= total_size`; parts are processed in order, so the first unfinished part is the one in flight. `current_offset` is a byte offset into the DECOMPRESSED part - only meaningful against the exact byte stream it was measured on.\n- `import_config`: the job's source / data format / sink configuration. It references credentials by secret key NAME only; secret values live in an encrypted column that is never returned by any API.\n- `created_by_email`: who started the migration, when known.\n\nTroubleshooting reminders (same semantics as the list tool): `waiting_to_start` = running with no worker lease yet; `lease_expired: true` on a running job = the worker died or the job is about to be re-claimed; a `paused` job keeps its lease and resuming (a Django admin action - this API is read-only) must clear it; `paused` with an invalid-JSON parse error at the resume point usually means the source bytes changed under the committed offset and the in-flight part needs a reset to offset 0 via Django admin's \"Resume + re-import in-flight part\".",+ "category": "Managed migrations",+ "feature": "managed_migrations",+ "summary": "Get one batch import job with raw worker state (PostHog staff only)",+ "title": "Get one batch import job with raw worker state (PostHog staff only)",+ "required_scopes": ["batch_import_support:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "managed-migrations-support-list": {+ "description": "List batch import (managed migration) jobs across ALL PostHog teams, for troubleshooting customer migrations. PostHog staff only: the backend requires a staff user AND a personal API key explicitly carrying the `batch_import_support:read` scope. A full-access (`*`) key is rejected; OAuth sign-in can never grant this scope.\n\nFilter with `team_id` (the customer's project id) or `status` (`running`, `paused`, `failed`, `completed`), or `search` (matches the developer status message and team name). Results are newest-first.\n\nHow to read a job's state:\n\n- `display_status: waiting_to_start` means the job is `running` but no worker has claimed it yet (`lease_id` is null) - it is queued, not stuck.\n- Workers hold a lease per job: 30 minutes on initial claim, renewed for 5 minutes on each heartbeat. `lease_expired: true` on a `running` job means the worker died or the row is about to be re-claimed by the next worker poll.\n- A `paused` job KEEPS its worker lease; resuming requires clearing the lease (a Django admin action today - this API is read-only).\n- `paused` with a `status_message` mentioning invalid JSON syntax at the resume point usually means a poisoned byte offset: the source bytes changed under the committed offset (re-downloaded nondeterministic export or replaced source file). The fix is Django admin's \"Resume + re-import in-flight part\", which resets the in-flight part to offset 0 (safe for Mixpanel/Amplitude, which dedupe by deterministic event UUID).\n- `backoff_until` in the future means the job is in a transient-failure retry loop (`backoff_attempt` counts consecutive retries), not stuck.\n- `parts_progress` summarizes the worker's units of work: a part is done when its committed byte offset reaches its total size; parts are processed in order, so the in-flight part is the first unfinished one.\n- `status_message` is the developer-facing debugging signal; `display_status_message` is what the customer sees in the PostHog UI.\n\nUse `managed-migrations-support-get` with a job id for the raw worker `state` and `import_config` blobs. Credentials (`secrets`) are never returned.",+ "category": "Managed migrations",+ "feature": "managed_migrations",+ "summary": "List batch import jobs across all teams (PostHog staff only)",+ "title": "List batch import jobs across all teams (PostHog staff only)",+ "required_scopes": ["batch_import_support:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"marketing-analytics-conversion-goals": {"description": "List the configured marketing conversion goals for the current project. Each goal returns its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.","category": "Marketing analytics",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 266e9061717f..7992bea53721 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12281,6 +12281,254 @@ export namespace Schemas {readonly import_config: unknown;}+ export interface BatchImportPartsProgress {+ /** Number of finished parts (a part is done when its committed byte offset has reached its known total size). */+ done: number;+ /** Total number of parts the worker has planned for this import. */+ total: number;+ /**+ * Key (file/date-range identifier) of the first unfinished part - the one in flight or next up. Null when all parts are done or the worker has not started. URL keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.+ * @nullable+ */+ inflight_key: string | null;+ /**+ * Committed byte offset (decompressed) within the in-flight part. Null when there is no in-flight part.+ * @nullable+ */+ inflight_offset: number | null;+ /**+ * Total decompressed size in bytes of the in-flight part, or null if the worker has not measured it yet.+ * @nullable+ */+ inflight_total_size: number | null;+ }++ /**+ * Raw worker progress blob: {'parts': [{'key', 'current_offset', 'total_size'}]}. A part is done when current_offset >= total_size; parts are processed in order. URL part keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.+ * @nullable+ */+ export type BatchImportSupportDetailState = { [key: string]: unknown } | null;++ /**+ * Source/format/sink configuration of the job. References secrets by key name only; secret values are never returned. Embedded URLs (e.g. a custom S3 endpoint_url) have their query string and userinfo redacted.+ * @nullable+ */+ export type BatchImportSupportDetailImportConfig = { [key: string]: unknown } | null;++ export type DisplayStatusEnum = typeof DisplayStatusEnum[keyof typeof DisplayStatusEnum];+++ export const DisplayStatusEnum = {+ WaitingToStart: 'waiting_to_start',+ Running: 'running',+ Paused: 'paused',+ Failed: 'failed',+ Completed: 'completed',+ } as const;++ /**+ * Full diagnostics view: adds the raw worker `state` and `import_config` blobs.+ *+ * `import_config` holds secret key *names* only - secret values live exclusively in the+ * encrypted `secrets` column, which no support serializer exposes.+ */+ export interface BatchImportSupportDetail {+ /** UUID of the batch import job. */+ readonly id: string;+ /** ID of the team (project) the import belongs to. */+ team_id: number;+ /** Name of the team the import belongs to. */+ team_name: string;+ /** Raw persisted status of the job.+ *+ * * `completed` - Completed+ * * `failed` - Failed+ * * `paused` - Paused+ * * `running` - Running */+ status?: BatchImportStatusEnum;+ /** Effective status: 'waiting_to_start' when the job is running but no worker has claimed it yet (lease_id is null), otherwise the raw status. */+ readonly display_status: DisplayStatusEnum;+ /**+ * Developer-facing status message written by the worker or an operator - the primary debugging signal. Not shown to the customer. Embedded URLs have their query string and userinfo redacted, since url_list part keys can carry presigned tokens or credentials.+ * @nullable+ */+ readonly status_message: string | null;+ /**+ * Customer-facing status message shown in the PostHog UI. Embedded URLs are redacted the same way as status_message.+ * @nullable+ */+ readonly display_status_message: string | null;+ /** Worker part progress summary derived from the raw state blob. */+ readonly parts_progress: BatchImportPartsProgress;+ /** Source the job imports from (e.g. s3, mixpanel, amplitude, urls, folder), or 'unknown' if unset. */+ readonly source_type: string;+ /** Format of the source events (e.g. mixpanel, amplitude, captured), or 'unknown' if unset. */+ readonly content_type: string;+ /**+ * Start of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_start_date: string | null;+ /**+ * End of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_end_date: string | null;+ /**+ * Where imported events are written (normally 'capture'; 'kafka'/'noop' for internal use), or null if unset.+ * @nullable+ */+ readonly sink_type: string | null;+ /**+ * Configured sink send rate in events per second, or null if unset.+ * @nullable+ */+ readonly sink_send_rate: number | null;+ /**+ * Lease token of the worker currently holding the job, or null when unclaimed. Claims lease for 30 minutes; the running heartbeat renews for 5 minutes.+ * @nullable+ */+ lease_id?: string | null;+ /**+ * When the current worker lease expires.+ * @nullable+ */+ leased_until?: string | null;+ /** True when the job holds a lease whose expiry is in the past. On a running job this means the worker died or the row is claimable again; the next poll can re-claim it. */+ readonly lease_expired: boolean;+ /**+ * Consecutive transient-failure retries so far (0 = healthy).+ * @minimum -2147483648+ * @maximum 2147483647+ */+ backoff_attempt?: number;+ /**+ * When the worker will retry after a transient failure. A future value means the job is in a retry loop, not stuck.+ * @nullable+ */+ backoff_until?: string | null;+ /**+ * ID of the user who created the import, if any.+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ created_by_id?: number | null;+ /** When the import was created. */+ readonly created_at: string;+ /** Last write to the row - the worker heartbeats this while processing. */+ readonly updated_at: string;+ /**+ * Raw worker progress blob: {'parts': [{'key', 'current_offset', 'total_size'}]}. A part is done when current_offset >= total_size; parts are processed in order. URL part keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.+ * @nullable+ */+ readonly state: BatchImportSupportDetailState;+ /**+ * Source/format/sink configuration of the job. References secrets by key name only; secret values are never returned. Embedded URLs (e.g. a custom S3 endpoint_url) have their query string and userinfo redacted.+ * @nullable+ */+ readonly import_config: BatchImportSupportDetailImportConfig;+ /**+ * Email of the user who created the import, if known.+ * @nullable+ */+ readonly created_by_email: string | null;+ }++ /**+ * Compact cross-team diagnostics view of a batch import job for PostHog support staff.+ *+ * Excludes the raw `state` / `import_config` blobs (see the detail serializer) and never+ * exposes the encrypted `secrets` column.+ */+ export interface BatchImportSupportList {+ /** UUID of the batch import job. */+ readonly id: string;+ /** ID of the team (project) the import belongs to. */+ team_id: number;+ /** Name of the team the import belongs to. */+ team_name: string;+ /** Raw persisted status of the job.+ *+ * * `completed` - Completed+ * * `failed` - Failed+ * * `paused` - Paused+ * * `running` - Running */+ status?: BatchImportStatusEnum;+ /** Effective status: 'waiting_to_start' when the job is running but no worker has claimed it yet (lease_id is null), otherwise the raw status. */+ readonly display_status: DisplayStatusEnum;+ /**+ * Developer-facing status message written by the worker or an operator - the primary debugging signal. Not shown to the customer. Embedded URLs have their query string and userinfo redacted, since url_list part keys can carry presigned tokens or credentials.+ * @nullable+ */+ readonly status_message: string | null;+ /**+ * Customer-facing status message shown in the PostHog UI. Embedded URLs are redacted the same way as status_message.+ * @nullable+ */+ readonly display_status_message: string | null;+ /** Worker part progress summary derived from the raw state blob. */+ readonly parts_progress: BatchImportPartsProgress;+ /** Source the job imports from (e.g. s3, mixpanel, amplitude, urls, folder), or 'unknown' if unset. */+ readonly source_type: string;+ /** Format of the source events (e.g. mixpanel, amplitude, captured), or 'unknown' if unset. */+ readonly content_type: string;+ /**+ * Start of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_start_date: string | null;+ /**+ * End of the source date range for date-range sources (Mixpanel/Amplitude), else null.+ * @nullable+ */+ readonly source_end_date: string | null;+ /**+ * Where imported events are written (normally 'capture'; 'kafka'/'noop' for internal use), or null if unset.+ * @nullable+ */+ readonly sink_type: string | null;+ /**+ * Configured sink send rate in events per second, or null if unset.+ * @nullable+ */+ readonly sink_send_rate: number | null;+ /**+ * Lease token of the worker currently holding the job, or null when unclaimed. Claims lease for 30 minutes; the running heartbeat renews for 5 minutes.+ * @nullable+ */+ lease_id?: string | null;+ /**+ * When the current worker lease expires.+ * @nullable+ */+ leased_until?: string | null;+ /** True when the job holds a lease whose expiry is in the past. On a running job this means the worker died or the row is claimable again; the next poll can re-claim it. */+ readonly lease_expired: boolean;+ /**+ * Consecutive transient-failure retries so far (0 = healthy).+ * @minimum -2147483648+ * @maximum 2147483647+ */+ backoff_attempt?: number;+ /**+ * When the worker will retry after a transient failure. A future value means the job is in a retry loop, not stuck.+ * @nullable+ */+ backoff_until?: string | null;+ /**+ * ID of the user who created the import, if any.+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ created_by_id?: number | null;+ /** When the import was created. */+ readonly created_at: string;+ /** Last write to the row - the worker heartbeats this while processing. */+ readonly updated_at: string;+ }+export type EventPropFilterTypeEnum = typeof EventPropFilterTypeEnum[keyof typeof EventPropFilterTypeEnum];@@ -36949,6 +37197,15 @@ export namespace Schemas {results: BatchImport[];}+ export interface PaginatedBatchImportSupportListList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: BatchImportSupportList[];+ }+export interface PaginatedBriefConfigList {count: number;/** @nullable */@@ -70175,6 +70432,43 @@ export namespace Schemas {Number60: 60,} as const;+ export type ManagedMigrationsSupportListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Which field to use when ordering the results.+ */+ ordering?: string;+ /**+ * A search term.+ */+ search?: string;+ /**+ * * `completed` - Completed+ * * `failed` - Failed+ * * `paused` - Paused+ * * `running` - Running+ */+ status?: ManagedMigrationsSupportListStatus;+ team_id?: number;+ };++ export type ManagedMigrationsSupportListStatus = typeof ManagedMigrationsSupportListStatus[keyof typeof ManagedMigrationsSupportListStatus];+++ export const ManagedMigrationsSupportListStatus = {+ Completed: 'completed',+ Failed: 'failed',+ Paused: 'paused',+ Running: 'running',+ } as const;+export type ListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/managed_migrations/api.ts b/services/mcp/src/generated/managed_migrations/api.tsnew file mode 100644index 000000000000..0d2b19adef4e--- /dev/null+++ b/services/mcp/src/generated/managed_migrations/api.ts@@ -0,0 +1,31 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 2 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * List batch import (managed migration) jobs across all teams. PostHog staff only.+ */+export const ManagedMigrationsSupportListQueryParams = /* @__PURE__ */ zod.object({+ 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.'),+ ordering: zod.string().optional().describe('Which field to use when ordering the results.'),+ search: zod.string().optional().describe('A search term.'),+ status: zod+ .enum(['completed', 'failed', 'paused', 'running'])+ .optional()+ .describe('* `completed` - Completed\n* `failed` - Failed\n* `paused` - Paused\n* `running` - Running'),+ team_id: zod.number().optional(),+})++/**+ * Get one batch import job with its raw worker state and import config. PostHog staff only.+ */+export const ManagedMigrationsSupportRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this batch import.'),+})diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 8727f883166d..2dd0901e78e5 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -10,6 +10,7 @@ import {resolveFeatureFlagOverrides,} from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'+import { filterStaffOnlyTools } from '@/lib/staff-only-tools'import type { McpMode } from '@/lib/utils'import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'import type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'@@ -176,7 +177,13 @@ export class RequestStateResolver {availableFeatures,isCloud,}- const allTools = this.catalog.getFilteredTools({ ...filterOptions, scopes: apiKeyScopes })+ // Staff-only tools (OAuth-hidden scopes) need the extra explicit-scope ++ // is_staff gate on top of the catalog's plain scope filter.+ const allTools = await filterStaffOnlyTools(+ this.catalog.getFilteredTools({ ...filterOptions, scopes: apiKeyScopes }),+ _apiKey ?? { scopes: [] },+ () => context.stateManager.getUser()+ )// Scope-gated hints are only consumed by the exec `search` command, which// only exists in single-exec mode — skip the extra scan otherwise.const scopeGatedTools = useSingleExec ? getScopeGatedTools(apiKeyScopes, filterOptions) : []diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.tsindex 08073e0bee16..ca1eec471280 100644--- a/services/mcp/src/lib/constants.ts+++ b/services/mcp/src/lib/constants.ts@@ -11,6 +11,7 @@ export {isCloudApi,isLocalApi,MCP_DOCS_URL,+ OAUTH_SCOPES_HIDDEN,OAUTH_SCOPES_SUPPORTED,} from './oauth-constants'diff --git a/services/mcp/src/lib/oauth-constants.ts b/services/mcp/src/lib/oauth-constants.tsindex fba3a557070c..68beffa9b4a0 100644--- a/services/mcp/src/lib/oauth-constants.ts+++ b/services/mcp/src/lib/oauth-constants.ts@@ -94,4 +94,4 @@ export const resolveAuthorizationServerUrl = (): string => {}// Generated from `posthog/scopes.py` — keep in sync with `hogli build:openapi`.-export { OAUTH_SCOPES_SUPPORTED, type OAuthScope } from './oauth-scopes.generated'+export { OAUTH_SCOPES_HIDDEN, OAUTH_SCOPES_SUPPORTED, type OAuthScope } from './oauth-scopes.generated'diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex e899d511827e..a641a4fd9f1f 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -208,3 +208,16 @@ export const OAUTH_SCOPES_SUPPORTED = [] as constexport type OAuthScope = (typeof OAUTH_SCOPES_SUPPORTED)[number]++// PAT-grantable but deliberately absent from OAUTH_SCOPES_SUPPORTED, so OAuth+// clients can never request them (mirrors OAUTH_SCOPES_HIDDEN in posthog/scopes.py).+// Tools requiring one of these only surface for staff users whose personal API key+// explicitly carries it (plus `user:read` for the staff lookup); `*` does not match.+export const OAUTH_SCOPES_HIDDEN = [+ 'batch_import_support:read',+ 'batch_import_support:write',+ 'query_performance:read',+ 'query_performance:write',+ 'wizard_session:read',+ 'wizard_session:write',+] as constdiff --git a/services/mcp/src/lib/staff-only-tools.ts b/services/mcp/src/lib/staff-only-tools.tsnew file mode 100644index 000000000000..f34550ec9328--- /dev/null+++ b/services/mcp/src/lib/staff-only-tools.ts@@ -0,0 +1,56 @@+// Imported from the generated file rather than `@/lib/oauth-constants` (which+// re-exports it) so this module stays importable from plain Node — the constants+// module reaches `cloudflare:workers` via `@/lib/env`.+import { OAUTH_SCOPES_HIDDEN } from '@/lib/oauth-scopes.generated'++const HIDDEN_SCOPES = new Set<string>(OAUTH_SCOPES_HIDDEN)++/** A tool requiring an OAuth-hidden scope is a staff-only surface. */+export const isStaffOnlyTool = (requiredScopes: string[]): boolean =>+ requiredScopes.some((scope) => HIDDEN_SCOPES.has(scope))++/**+ * Hidden scopes must be explicitly minted on the key — a full-access `*` key+ * must not match, mirroring the backend's INTERNAL scope handling, which+ * rejects wildcard keys on staff endpoints.+ */+export const keyExplicitlyGrantsHiddenScopes = (requiredScopes: string[], keyScopes: string[]): boolean =>+ requiredScopes.every((scope) => !HIDDEN_SCOPES.has(scope) || keyScopes.includes(scope))++/**+ * Drop staff-only tools unless the key explicitly carries their hidden scope+ * AND the authed user is staff (the backend enforces `is_staff` on every call;+ * this keeps the tools out of customers' tool lists entirely). The staff+ * lookup needs `user:read` on the key and fails closed, hiding the tools+ * whenever staffness cannot be confirmed. The lookup only runs when a+ * staff-only tool would otherwise surface, so customer sessions never pay it.+ *+ * Tenant-scoped keys (scoped_teams/scoped_organizations) never surface staff+ * tools either: the staff endpoints reject scoped keys outright, so showing+ * the tools would only advertise calls that always 403.+ */+export async function filterStaffOnlyTools<T extends { scopes: string[] }>(+ tools: T[],+ key: { scopes: string[]; scoped_teams?: number[]; scoped_organizations?: string[] },+ getUser: () => Promise<{ is_staff?: boolean }>+): Promise<T[]> {+ const keyScopes = key.scopes+ const keyIsTenantScoped = (key.scoped_teams?.length ?? 0) > 0 || (key.scoped_organizations?.length ?? 0) > 0+ if (keyIsTenantScoped) {+ return tools.filter((tool) => !isStaffOnlyTool(tool.scopes))+ }++ let userIsStaff = false+ if (tools.some((tool) => isStaffOnlyTool(tool.scopes) && keyExplicitlyGrantsHiddenScopes(tool.scopes, keyScopes))) {+ try {+ userIsStaff = (await getUser()).is_staff === true+ } catch {+ userIsStaff = false+ }+ }++ return tools.filter(+ (tool) =>+ !isStaffOnlyTool(tool.scopes) || (keyExplicitlyGrantsHiddenScopes(tool.scopes, keyScopes) && userIsStaff)+ )+}diff --git a/services/mcp/src/schema/api.ts b/services/mcp/src/schema/api.tsindex 85099fce07bf..df48e990075d 100644--- a/services/mcp/src/schema/api.ts+++ b/services/mcp/src/schema/api.ts@@ -8,6 +8,10 @@ export interface ApiUser {first_name?: stringlast_name?: stringemail: string+ // Gates discovery of staff-only tools (those requiring an OAUTH_SCOPES_HIDDEN+ // scope). Optional because some tests construct partial users; treat absence+ // as not staff.+ is_staff?: booleanorganizations: Array<{ id: string; name: string }>// `team` and `organization` mirror the Django User's nullable `current_team`// / `current_organization` FKs — the `/api/users/@me/` serializer returnsdiff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex dd80b4fd1a04..a771e2752b80 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -30,6 +30,7 @@ import { GENERATED_TOOLS as field_notes } from './field_notes'import { GENERATED_TOOLS as health_issues } from './health_issues'import { GENERATED_TOOLS as integrations } from './integrations'import { GENERATED_TOOLS as logs } from './logs'+import { GENERATED_TOOLS as managed_migrations } from './managed_migrations'import { GENERATED_TOOLS as marketing_analytics } from './marketing_analytics'import { GENERATED_TOOLS as mcp_analytics } from './mcp_analytics'import { GENERATED_TOOLS as mcp_store } from './mcp_store'@@ -86,6 +87,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...health_issues,...integrations,...logs,+ ...managed_migrations,...marketing_analytics,...mcp_analytics,...mcp_store,diff --git a/services/mcp/src/tools/generated/managed_migrations.ts b/services/mcp/src/tools/generated/managed_migrations.tsnew file mode 100644index 000000000000..2444f8505b3d--- /dev/null+++ b/services/mcp/src/tools/generated/managed_migrations.ts@@ -0,0 +1,57 @@+// AUTO-GENERATED from products/managed_migrations/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import {+ ManagedMigrationsSupportListQueryParams,+ ManagedMigrationsSupportRetrieveParams,+} from '@/generated/managed_migrations/api'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const ManagedMigrationsSupportGetSchema = ManagedMigrationsSupportRetrieveParams++const managedMigrationsSupportGet = (): ToolBase<+ typeof ManagedMigrationsSupportGetSchema,+ Schemas.BatchImportSupportDetail+> => ({+ name: 'managed-migrations-support-get',+ schema: ManagedMigrationsSupportGetSchema,+ handler: async (context: Context, params: z.infer<typeof ManagedMigrationsSupportGetSchema>) => {+ const result = await context.api.request<Schemas.BatchImportSupportDetail>({+ method: 'GET',+ path: `/api/managed_migrations_support/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const ManagedMigrationsSupportListSchema = ManagedMigrationsSupportListQueryParams++const managedMigrationsSupportList = (): ToolBase<+ typeof ManagedMigrationsSupportListSchema,+ WithPostHogUrl<Schemas.PaginatedBatchImportSupportListList>+> => ({+ name: 'managed-migrations-support-list',+ schema: ManagedMigrationsSupportListSchema,+ handler: async (context: Context, params: z.infer<typeof ManagedMigrationsSupportListSchema>) => {+ const result = await context.api.request<Schemas.PaginatedBatchImportSupportListList>({+ method: 'GET',+ path: `/api/managed_migrations_support/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ ordering: params.ordering,+ search: params.search,+ status: params.status,+ team_id: params.team_id,+ },+ })+ return await withPostHogUrl(context, result, '/managed_migrations')+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'managed-migrations-support-get': managedMigrationsSupportGet,+ 'managed-migrations-support-list': managedMigrationsSupportList,+}diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex 14c0453e6727..33d00b689a6c 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -1,4 +1,5 @@import { hasScopes } from '@/lib/api'+import { filterStaffOnlyTools } from '@/lib/staff-only-tools'// Agent platform (hand-written — CRUD is codegen in generated/agent_platform.ts)import resolveResource from './agentPlatform/resolveResource'@@ -152,5 +153,7 @@ export const getToolsFromContext = async (const apiKey = await context.stateManager.getApiKey()const scopes = apiKey?.scopes ?? []- return tools.filter((tool) => hasScopes(scopes, tool.scopes))+ const candidates = tools.filter((tool) => hasScopes(scopes, tool.scopes))++ return filterStaffOnlyTools(candidates, apiKey ?? { scopes: [] }, () => context.stateManager.getUser())}diff --git a/services/mcp/src/tools/toolDefinitions.ts b/services/mcp/src/tools/toolDefinitions.tsindex b24329e1417d..2971e4fcbf07 100644--- a/services/mcp/src/tools/toolDefinitions.ts+++ b/services/mcp/src/tools/toolDefinitions.ts@@ -3,6 +3,7 @@ import z from 'zod'import { hasScope, hasScopes } from '@/lib/api'import { OAUTH_SCOPES_SUPPORTED } from '@/lib/oauth-scopes.generated'import type { EvaluatedFlags } from '@/lib/posthog/flags'+import { isStaffOnlyTool } from '@/lib/staff-only-tools'import generatedToolDefinitionsJson from '../../schema/generated-tool-definitions.json'import toolDefinitionsJson from '../../schema/tool-definitions.json'@@ -298,6 +299,11 @@ export function getScopeGatedTools(scopes: string[], options?: ToolFilterOptionsif (!definition || required.length === 0 || hasScopes(scopes, required)) {continue}+ // Never hint at staff-only tools — an "add this scope" nudge would+ // advertise a staff surface to customers who can never call it.+ if (isStaffOnlyTool(required)) {+ continue+ }gated.push({name,title: definition.title,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/managed-migrations-support-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/managed-migrations-support-get.jsonnew file mode 100644index 000000000000..f53eec8ac44d--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/managed-migrations-support-get.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this batch import.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/managed-migrations-support-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/managed-migrations-support-list.jsonnew file mode 100644index 000000000000..41bf1035aaee--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/managed-migrations-support-list.json@@ -0,0 +1,30 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "limit": {+ "description": "Number of results to return per page.",+ "type": "number"+ },+ "offset": {+ "description": "The initial index from which to return the results.",+ "type": "number"+ },+ "ordering": {+ "description": "Which field to use when ordering the results.",+ "type": "string"+ },+ "search": {+ "description": "A search term.",+ "type": "string"+ },+ "status": {+ "description": "* `completed` - Completed\n* `failed` - Failed\n* `paused` - Paused\n* `running` - Running",+ "enum": ["completed", "failed", "paused", "running"],+ "type": "string"+ },+ "team_id": {+ "type": "number"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 479ee75ff398..5e1d972bb23f 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { OAUTH_SCOPES_SUPPORTED } from '@/lib/constants'+import { OAUTH_SCOPES_HIDDEN, OAUTH_SCOPES_SUPPORTED } from '@/lib/constants'import type { EvaluatedFlags } from '@/lib/posthog/flags'import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'@@ -235,7 +235,11 @@ describe('Tool Filtering - Tools Allowlist', () => {})})-const createMockContext = (scopes: string[]): Context => ({+const createMockContext = (+ scopes: string[],+ getUser?: () => Promise<{ is_staff?: boolean }>,+ apiKeyExtra?: { scoped_teams?: number[]; scoped_organizations?: string[] }+): Context => ({api: {} as any,cache: {} as any,env: {@@ -248,8 +252,13 @@ const createMockContext = (scopes: string[]): Context => ({POSTHOG_UI_APPS_TOKEN: undefined,},stateManager: {- getApiKey: async () => ({ scopes }),+ getApiKey: async () => ({ scopes, ...apiKeyExtra }),getAiConsentGiven: async () => undefined,+ getUser:+ getUser ??+ (async () => {+ throw new Error('users/@me not available')+ }),} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',@@ -340,6 +349,59 @@ describe('Tool Filtering - API Scopes', () => {})})+describe('Tool Filtering - Staff-only (OAuth-hidden scope) tools', () => {+ const STAFF_TOOLS = ['managed-migrations-support-list', 'managed-migrations-support-get']++ it.each([+ {+ description: 'hidden from a full-access `*` key even for a staff user',+ scopes: ['*'],+ getUser: async () => ({ is_staff: true }),+ visible: false,+ },+ {+ description: 'visible for a staff user whose key explicitly carries the hidden scope',+ scopes: ['batch_import_support:read', 'user:read'],+ getUser: async () => ({ is_staff: true }),+ visible: true,+ },+ {+ description: 'hidden from a non-staff user even when the key carries the hidden scope',+ scopes: ['batch_import_support:read', 'user:read'],+ getUser: async () => ({ is_staff: false }),+ visible: false,+ },+ {+ // Default mock getUser rejects, like a key minted without `user:read`.+ description: 'hidden (fail closed) when staffness cannot be determined',+ scopes: ['batch_import_support:read'],+ getUser: undefined,+ visible: false,+ },+ {+ // The staff endpoints reject tenant-scoped keys, so discovery must not+ // advertise tools whose every call would 403.+ description: 'hidden for a tenant-scoped key even with staff + explicit scope',+ scopes: ['batch_import_support:read', 'user:read'],+ getUser: async () => ({ is_staff: true }),+ apiKeyExtra: { scoped_organizations: ['0195b1a0-0000-0000-0000-000000000000'] },+ visible: false,+ },+ ])('$description', async ({ scopes, getUser, visible, apiKeyExtra }) => {+ const context = createMockContext(scopes, getUser, apiKeyExtra)+ const tools = await getToolsFromContext(context)+ const toolNames = tools.map((t) => t.name)++ for (const tool of STAFF_TOOLS) {+ if (visible) {+ expect(toolNames).toContain(tool)+ } else {+ expect(toolNames).not.toContain(tool)+ }+ }+ })+})+/*** Asserts that every tool in `toolNames` has an empty `required_scopes` array* in its definition. Used by the "user has no scopes" tests so they don't@@ -369,6 +431,11 @@ describe('OAUTH_SCOPES_SUPPORTED completeness', () => {'signal_scout_report:write',])+ // OAuth-hidden scopes (generated from OAUTH_HIDDEN_SCOPE_OBJECTS in posthog/scopes.py)+ // are PAT-grantable but never OAuth-advertised: tools requiring one (e.g. the staff-only+ // managed-migrations support tools) only surface for personal API keys carrying it.+ const oauthHiddenScopes = new Set<string>(OAUTH_SCOPES_HIDDEN)+it('should include every scope referenced in tool definitions', () => {const supportedScopes = new Set<string>(OAUTH_SCOPES_SUPPORTED)@@ -382,7 +449,7 @@ describe('OAUTH_SCOPES_SUPPORTED completeness', () => {}const missing = [...scopesFromTools]- .filter((s) => !supportedScopes.has(s) && !SERVER_MINT_ONLY_SCOPES.has(s))+ .filter((s) => !supportedScopes.has(s) && !SERVER_MINT_ONLY_SCOPES.has(s) && !oauthHiddenScopes.has(s)).sort()expect(diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex b6fc989e36e6..96023d49880c 100644--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts@@ -5,6 +5,7 @@ import { format } from 'oxfmt'import { describe, expect, it } from 'vitest'import { z } from 'zod'+import { OAUTH_SCOPES_HIDDEN } from '@/lib/constants'import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'import type { Context } from '@/tools/types'@@ -23,8 +24,12 @@ function createMockContext(): Context {POSTHOG_UI_APPS_TOKEN: undefined,},stateManager: {- getApiKey: async () => ({ scopes: ['*'] }),+ // Staff-only tools require their OAuth-hidden scope explicitly on the key+ // (`*` alone does not match) plus a staff user, so grant both here to keep+ // their schemas in the snapshot surface.+ getApiKey: async () => ({ scopes: ['*', ...OAUTH_SCOPES_HIDDEN] }),getAiConsentGiven: async () => true,+ getUser: async () => ({ is_staff: true }),} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',