Skip to content

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

feat(insights): require opt-in for deprecated dashboards field on token auth (#69922)

Paul D'Ambra1af4d72b2811
diff --git a/frontend/src/queries/nodes/InsightViz/utils.test.ts b/frontend/src/queries/nodes/InsightViz/utils.test.ts
index d73f974206c2..d254d44d2cce 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.test.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.test.ts
@@ -1,4 +1,6 @@
-import { extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'
+import { InsightModel } from '~/types'
+
+import { extractValidationErrorCode, getQueryBasedInsightModel } from './utils'
describe('extractValidationErrorCode', () => {
test.each([
@@ -15,3 +17,42 @@ describe('extractValidationErrorCode', () => {
expect(extractValidationErrorCode(error)).toBe(expected)
})
})
+
+describe('getQueryBasedInsightModel', () => {
+ it.each([
+ [
+ 'derives dashboards from dashboard_tiles when the response omits the deprecated field',
+ {
+ dashboard_tiles: [
+ { id: 10, dashboard_id: 1 },
+ { id: 11, dashboard_id: 2 },
+ ],
+ },
+ [1, 2],
+ ],
+ [
+ 'keeps the server-provided dashboards value when present',
+ { dashboards: [3], dashboard_tiles: [{ id: 10, dashboard_id: 1 }] },
+ [3],
+ ],
+ ['leaves dashboards undefined when neither field is present', {}, undefined],
+ [
+ 'derives dashboards from dashboard_tiles when dashboards is null',
+ { dashboards: null, dashboard_tiles: [{ id: 10, dashboard_id: 1 }] },
+ [1],
+ ],
+ [
+ 'excludes soft-deleted tiles when deriving dashboards',
+ {
+ dashboard_tiles: [
+ { id: 10, dashboard_id: 1 },
+ { id: 11, dashboard_id: 2, deleted: true },
+ ],
+ },
+ [1],
+ ],
+ ])('%s', (_name, input, expected) => {
+ const result = getQueryBasedInsightModel(input as Partial<InsightModel>)
+ expect(result.dashboards).toEqual(expected)
+ })
+})
diff --git a/frontend/src/queries/nodes/InsightViz/utils.ts b/frontend/src/queries/nodes/InsightViz/utils.ts
index 5575e911a7bf..d5b9c03d405a 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.ts
@@ -90,7 +90,16 @@ type ReturnInsightModel<T> = T extends InsightModel
/** Get an insight with `query` only. Eventual `filters` will be converted. */
export function getQueryBasedInsightModel<T extends InputInsightModel>(insight: T): ReturnInsightModel<T> {
const { filters, ...baseInsight } = insight
- return { ...baseInsight, query: getQueryFromInsightLike(insight) } as unknown as ReturnInsightModel<T>
+ // The API is phasing out the deprecated `dashboards` field (already omitted for token
+ // callers, eventually for all); derive it from `dashboard_tiles` so remaining readers
+ // keep working regardless of whether the response still carries it.
+ const dashboards =
+ insight.dashboards ?? insight.dashboard_tiles?.filter((tile) => !tile.deleted).map((tile) => tile.dashboard_id)
+ return {
+ ...baseInsight,
+ ...(dashboards ? { dashboards } : {}),
+ query: getQueryFromInsightLike(insight),
+ } as unknown as ReturnInsightModel<T>
}
/** Get a `query` from an object that potentially has `filters` instead of a `query`. */
diff --git a/posthog/api/documentation.py b/posthog/api/documentation.py
index 4b9aa6780ed5..7e9a2a2b6dec 100644
--- a/posthog/api/documentation.py
+++ b/posthog/api/documentation.py
@@ -928,6 +928,22 @@ def _fix_pydantic_schema_for_openapi(schema):
return schema
+def _unrequire_deprecated_dashboards_field(schema):
+ """
+ The deprecated insight `dashboards` field is gated behind an opt-in query parameter, so it
+ can be absent from any insight payload — but drf-spectacular always marks read-only fields
+ as required, which would make strict generated clients reject gated responses. Un-require
+ it wherever it appears alongside its replacement, `dashboard_tiles`.
+ """
+ properties = schema.get("properties") if isinstance(schema, dict) else None
+ if not isinstance(properties, dict) or not {"dashboards", "dashboard_tiles"} <= properties.keys():
+ return schema
+ required = schema.get("required")
+ if isinstance(required, list) and "dashboards" in required:
+ schema["required"] = [field for field in required if field != "dashboards"]
+ return schema
+
+
def lint_spec_consistency_hook(result, generator, request, public):
"""Postprocessing hook that emits drf-spectacular warnings for spec self-inconsistencies.
@@ -1179,7 +1195,8 @@ def custom_postprocessing_hook(result, generator, request, public):
# Apply OpenAPI 3.1 schema cleanup to all component schemas.
if "components" in result and "schemas" in result["components"]:
result["components"]["schemas"] = {
- name: _fix_pydantic_schema_for_openapi(schema) for name, schema in result["components"]["schemas"].items()
+ name: _unrequire_deprecated_dashboards_field(_fix_pydantic_schema_for_openapi(schema))
+ for name, schema in result["components"]["schemas"].items()
}
# Apply the same cleanup to parameter, requestBody, and response schemas at the operation
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 39654d602d3a..5c83d78f1f74 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -13,6 +13,13 @@ from posthog.utils_cors import CORS_ALLOWED_TRACING_HEADERS
logger = structlog.get_logger(__name__)
+####
+# Deprecated insight `dashboards` field: two-phase removal. While False (phase 1), every caller
+# still receives the field and usage is metered by access method; flipping to True (phase 2)
+# enforces the `include_dashboards` opt-in for non-first-party callers. Env-toggleable so the
+# enforcement can be reverted without a code change.
+INSIGHT_DASHBOARDS_OPT_IN_ENFORCED = get_from_env("INSIGHT_DASHBOARDS_OPT_IN_ENFORCED", False, type_cast=str_to_bool)
+
####
# django-axes
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index a9196c5f6f19..3dbd39bbd7d3 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -141,6 +141,7 @@ from products.notifications.backend.facade.api import (
has_been_dispatched,
)
from products.product_analytics.backend.api.insight import (
+ INCLUDE_DASHBOARDS_PARAMETER,
DashboardTileBasicSerializer,
InsightSerializer,
InsightViewSet,
@@ -2114,7 +2115,12 @@ class DashboardSubscribeNudgeResponseSerializer(serializers.Serializer):
),
],
),
- partial_update=extend_schema(request=PatchedDashboardOpenApiSerializer),
+ # Dashboards nest insight payloads via `tiles[].insight`, so the deprecated-`dashboards`-field
+ # opt-in applies here too — on every action whose response uses DashboardSerializer.
+ create=extend_schema(parameters=[INCLUDE_DASHBOARDS_PARAMETER]),
+ retrieve=extend_schema(parameters=[INCLUDE_DASHBOARDS_PARAMETER]),
+ update=extend_schema(parameters=[INCLUDE_DASHBOARDS_PARAMETER]),
+ partial_update=extend_schema(request=PatchedDashboardOpenApiSerializer, parameters=[INCLUDE_DASHBOARDS_PARAMETER]),
)
class DashboardsViewSet(
TeamAndOrgViewSetMixin,
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 327b7c114231..5ffbb8311b7c 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -8207,9 +8207,15 @@ export interface InsightApi {
order?: number | null
deleted?: boolean
/**
+ *
* DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.
* A dashboard ID for each of the dashboards that this insight is displayed on.
- * */
+ * This field may be omitted from responses: once opt-in enforcement is enabled, API-token
+ * callers (personal API keys, OAuth) only receive it when passing the
+ * `include_dashboards=true` query parameter. Do not rely on it being present.
+ *
+ * @deprecated
+ */
dashboards?: number[]
/**
* A dashboard tile ID and dashboard_id for each of the dashboards that this insight is displayed on.
@@ -9262,6 +9268,10 @@ export const DashboardsListFormat = {
export type DashboardsCreateParams = {
format?: DashboardsCreateFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
}
export type DashboardsCreateFormat = (typeof DashboardsCreateFormat)[keyof typeof DashboardsCreateFormat]
@@ -9277,6 +9287,10 @@ export type DashboardsRetrieveParams = {
*/
filters_override?: string
format?: DashboardsRetrieveFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
/**
* Object (or pre-encoded JSON string) to override dashboard variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `dashboard-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.
*/
@@ -9292,6 +9306,10 @@ export const DashboardsRetrieveFormat = {
export type DashboardsUpdateParams = {
format?: DashboardsUpdateFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
}
export type DashboardsUpdateFormat = (typeof DashboardsUpdateFormat)[keyof typeof DashboardsUpdateFormat]
@@ -9303,6 +9321,10 @@ export const DashboardsUpdateFormat = {
export type DashboardsPartialUpdateParams = {
format?: DashboardsPartialUpdateFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
}
export type DashboardsPartialUpdateFormat =
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index c40cc3118b78..5ad6a1a8b5e5 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -5,6 +5,7 @@ from datetime import timedelta
from functools import lru_cache
from typing import Any, Union, cast
+from django.conf import settings
from django.db import transaction
from django.db.models import Count, Exists, F, Max, OuterRef, Prefetch, QuerySet, Subquery
from django.db.models.query_utils import Q
@@ -52,7 +53,12 @@ from posthog.api.services.query import process_query_dict, process_query_model
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action, format_paginated_url
-from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication
+from posthog.auth import (
+ PersonalAPIKeyAuthentication,
+ SessionAuthentication,
+ SharingAccessTokenAuthentication,
+ SharingPasswordProtectedAuthentication,
+)
from posthog.caching.fetch_from_cache import InsightResult, fetch_cached_response_by_key
from posthog.clickhouse.cancel import cancel_query_on_cluster
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
@@ -326,7 +332,76 @@ class DashboardTileBasicSerializer(serializers.ModelSerializer):
fields = ["id", "dashboard_id", "deleted"]
-@extend_schema_serializer(exclude_fields=["filters", "saved"])
+INCLUDE_DASHBOARDS_PARAM = "include_dashboards"
+
+DEPRECATED_DASHBOARDS_FIELD_USED_COUNTER = Counter(
+ "posthog_api_insight_deprecated_dashboards_field_used_total",
+ "Times the deprecated insight `dashboards` field was served in an insight payload (usage=read) "
+ "or accepted as write input on a permitted create/update (usage=write, including no-op writes), "
+ "by authentication method. Rejected requests are not counted.",
+ labelnames=["usage", "access_method"],
+)
+
+
+# Access methods that are our own surfaces (web app, shared/exporter frontend) rather than
+# external integrations. Unresolved auth ("no_authenticator") comes from the web app too. These
+# keep receiving the deprecated `dashboards` field until the frontend fully migrates to
+# dashboard_tiles, regardless of opt-in enforcement.
+_FIRST_PARTY_ACCESS_METHODS = frozenset({"no_authenticator", "session", "sharing_token"})
+
+
+def _dashboards_field_access_method(request: Request | None) -> str:
+ authenticator = getattr(request, "successful_authenticator", None)
+ # An unresolved authenticator (no DRF auth ran) is treated as session below: it's not a
+ # token caller we're trying to migrate off the field, so keep serving it.
+ if authenticator is None:
+ return "no_authenticator"
+ if isinstance(authenticator, SessionAuthentication):
+ return "session"
+ if isinstance(authenticator, SharingAccessTokenAuthentication | SharingPasswordProtectedAuthentication):
+ return "sharing_token"
+ if isinstance(authenticator, PersonalAPIKeyAuthentication):
+ return "personal_api_key"
+ return type(authenticator).__name__
+
+
+def _is_internal_serialization_context(context: dict) -> bool:
+ # Internal serialization (exports, subscriptions, my_last_viewed) has no requesting client to
+ # migrate, so it's exempt from both the opt-in gate and the deprecation-usage counter.
+ return context.get("request") is None
+
+
+def _is_first_party_request(request: Request | None) -> bool:
+ return _dashboards_field_access_method(request) in _FIRST_PARTY_ACCESS_METHODS
+
+
+def should_serve_deprecated_dashboards_field(context: dict) -> bool:
+ """
+ The insight `dashboards` field is deprecated in favor of `dashboard_tiles`. Removal is
+ two-phase: while INSIGHT_DASHBOARDS_OPT_IN_ENFORCED is off, every caller still receives the
+ field and reads are metered by access method so remaining usage can drain; once enforced,
+ non-first-party callers must opt in with `?include_dashboards=true`.
+ """
+ if _is_internal_serialization_context(context):
+ return True
+ request = context["request"]
+ if _is_first_party_request(request):
+ return True
+ query_params = getattr(request, "query_params", None)
+ if query_params is not None and str_to_bool(query_params.get(INCLUDE_DASHBOARDS_PARAM, "0")):
+ return True
+ return not settings.INSIGHT_DASHBOARDS_OPT_IN_ENFORCED
+
+
+def _record_deprecated_dashboards_field_used(context: dict, usage: str) -> None:
+ if _is_internal_serialization_context(context):
+ return
+ DEPRECATED_DASHBOARDS_FIELD_USED_COUNTER.labels(
+ usage=usage, access_method=_dashboards_field_access_method(context["request"])
+ ).inc()
+
+
+@extend_schema_serializer(exclude_fields=["filters", "saved"], deprecate_fields=["dashboards"])
class InsightBasicSerializer(
SearchMatchTypeSerializerMixin,
TaggedItemSerializerMixin,
@@ -375,7 +450,12 @@ class InsightBasicSerializer(
@extend_schema_field(serializers.ListField(child=serializers.IntegerField()))
def get_dashboards(self, instance: Insight) -> list[int]:
- return [tile.dashboard_id for tile in instance.dashboard_tiles.all()]
+ # `to_representation` below always recomputes this field when serving it, so this only
+ # backs schema generation and any other caller of the method field directly. Excludes
+ # soft-deleted tiles to match that recomputation — filtered in Python, not with
+ # .exclude(), since a chained queryset bypasses the dashboard_tiles prefetch cache and
+ # reintroduces a per-insight query.
+ return [tile.dashboard_id for tile in instance.dashboard_tiles.all() if not tile.deleted]
@extend_schema_field(serializers.DateTimeField(allow_null=True))
def get_last_viewed_at(self, instance: Insight):
@@ -385,7 +465,15 @@ class InsightBasicSerializer(
def to_representation(self, instance):
representation = super().to_representation(instance)
- representation["dashboards"] = [tile["dashboard_id"] for tile in representation["dashboard_tiles"]]
+ if should_serve_deprecated_dashboards_field(self.context):
+ _record_deprecated_dashboards_field_used(self.context, usage="read")
+ # Exclude soft-deleted tiles, matching the write-echo correction and the frontend's
+ # dashboard_tiles-based derivation.
+ representation["dashboards"] = [
+ tile["dashboard_id"] for tile in representation["dashboard_tiles"] if not tile.get("deleted")
+ ]
+ else:
+ representation.pop("dashboards", None)
if instance.query is not None or instance.query_from_filters is not None:
representation["filters"] = {}
@@ -466,6 +554,7 @@ class InsightFilterOverrideContext(BaseModel):
)
+@extend_schema_serializer(deprecate_fields=["dashboards"])
class InsightSerializer(InsightBasicSerializer):
result = serializers.SerializerMethodField()
hasMore = serializers.SerializerMethodField()
@@ -501,6 +590,9 @@ class InsightSerializer(InsightBasicSerializer):
help_text="""
DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.
A dashboard ID for each of the dashboards that this insight is displayed on.
+ This field may be omitted from responses: once opt-in enforcement is enabled, API-token
+ callers (personal API keys, OAuth) only receive it when passing the
+ `include_dashboards=true` query parameter. Do not rely on it being present.
""",
many=True,
required=False,
@@ -645,6 +737,10 @@ class InsightSerializer(InsightBasicSerializer):
if dashboard.team_id != team_id:
raise serializers.ValidationError("Dashboard not found")
+ # Counts the field being accepted as write input (even an empty list), after
+ # permission checks so rejected requests don't inflate the metric.
+ _record_deprecated_dashboards_field_used(self.context, usage="write")
+
insight = Insight.objects.create(
team_id=team_id,
created_by=created_by,
@@ -802,6 +898,10 @@ class InsightSerializer(InsightBasicSerializer):
return []
def _update_insight_dashboards(self, dashboards: list[Dashboard], instance: Insight) -> None:
+ # Counts the field being accepted as write input — before the no-op early return, so
+ # integrations that round-trip an unchanged dashboards list still register as writers.
+ _record_deprecated_dashboards_field_used(self.context, usage="write")
+
old_dashboard_ids = [tile.dashboard_id for tile in instance.dashboard_tiles.all()]
new_dashboard_ids = [d.id for d in dashboards if not d.deleted]
@@ -1014,7 +1114,12 @@ class InsightSerializer(InsightBasicSerializer):
# when they have just been updated
# we store them and can use that list to correct the response
# and avoid refreshing from the DB
- if self.context.get("after_dashboard_changes"):
+ #
+ # `after_dashboard_changes` is only set (even to an empty list) when this request itself
+ # wrote `dashboards` (see _update_insight_dashboards), so a caller that isn't opted into
+ # the deprecated field for reads still needs to see the corrected value for the write it
+ # just made — including the "removed from all dashboards" case.
+ if "after_dashboard_changes" in self.context:
representation["dashboards"] = [
described_dashboard["id"] for described_dashboard in self.context["after_dashboard_changes"]
]
@@ -1315,6 +1420,16 @@ INSIGHT_ID_PATH_PARAMETER = OpenApiParameter(
description="Numeric primary key or 8-character `short_id` (for example `AaVQ8Ijw`) identifying the insight.",
)
+INCLUDE_DASHBOARDS_PARAMETER = OpenApiParameter(
+ name=INCLUDE_DASHBOARDS_PARAM,
+ type=OpenApiTypes.BOOL,
+ description=(
+ "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in "
+ "enforcement is enabled, API-token callers stop receiving it by default; use "
+ "`dashboard_tiles` instead."
+ ),
+)
+
INSIGHT_VIEWED_MAX_IDS = 2500
@@ -1398,6 +1513,7 @@ Background calculation can be tracked using the `query_status` response field.""
type=OpenApiTypes.BOOL,
description="Return basic insight metadata only (no results, faster).",
),
+ INCLUDE_DASHBOARDS_PARAMETER,
OpenApiParameter(
name="search",
type=OpenApiTypes.STR,
@@ -1474,8 +1590,10 @@ Background calculation can be tracked using the `query_status` response field.""
),
]
),
- update=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER]),
- partial_update=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER]),
+ create=extend_schema(parameters=[INCLUDE_DASHBOARDS_PARAMETER]),
+ retrieve=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER, INCLUDE_DASHBOARDS_PARAMETER]),
+ update=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER, INCLUDE_DASHBOARDS_PARAMETER]),
+ partial_update=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER, INCLUDE_DASHBOARDS_PARAMETER]),
destroy=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER]),
)
class InsightViewSet(
@@ -1719,6 +1837,7 @@ class InsightViewSet(
description="Maximum number of insights to return. Defaults to 10. Capped at 100.",
required=False,
),
+ INCLUDE_DASHBOARDS_PARAMETER,
],
responses={200: TrendingInsightSerializer(many=True)},
description=(
diff --git a/products/product_analytics/backend/api/test/test_deprecated_dashboards_field.py b/products/product_analytics/backend/api/test/test_deprecated_dashboards_field.py
new file mode 100644
index 000000000000..22894e743d1d
--- /dev/null
+++ b/products/product_analytics/backend/api/test/test_deprecated_dashboards_field.py
@@ -0,0 +1,92 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication, SharingAccessTokenAuthentication
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.api.insight import should_serve_deprecated_dashboards_field
+from products.product_analytics.backend.models.insight import Insight
+
+
+def _fake_request(authenticator: object | None, query_params: dict[str, str] | None = None) -> MagicMock:
+ request = MagicMock()
+ request.successful_authenticator = authenticator
+ request.query_params = query_params or {}
+ return request
+
+
+class TestShouldServeDeprecatedDashboardsField(SimpleTestCase):
+ def test_serves_when_no_request_in_context(self):
+ assert should_serve_deprecated_dashboards_field({}) is True
+
+ @parameterized.expand(
+ [
+ ("session_auth", SessionAuthentication(), {}, False, True),
+ ("no_authenticator_is_first_party", None, {}, True, True),
+ ("sharing_token_is_first_party", SharingAccessTokenAuthentication(), {}, True, True),
+ ("personal_api_key_unenforced_phase", PersonalAPIKeyAuthentication(), {}, False, True),
+ ("personal_api_key_enforced_without_opt_in", PersonalAPIKeyAuthentication(), {}, True, False),
+ (
+ "personal_api_key_enforced_with_opt_in",
+ PersonalAPIKeyAuthentication(),
+ {"include_dashboards": "true"},
+ True,
+ True,
+ ),
+ ]
+ )
+ def test_serving_by_access_method_opt_in_and_enforcement(
+ self, _name, authenticator, query_params, enforced, expected
+ ):
+ context = {"request": _fake_request(authenticator, query_params)}
+ with override_settings(INSIGHT_DASHBOARDS_OPT_IN_ENFORCED=enforced):
+ assert should_serve_deprecated_dashboards_field(context) is expected
+
+
+class TestDeprecatedDashboardsFieldAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.dashboard = Dashboard.objects.create(team=self.team, name="dash")
+ self.insight = Insight.objects.create(team=self.team, name="insight", saved=True)
+ DashboardTile.objects.create(insight=self.insight, dashboard=self.dashboard)
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="test",
+ secure_value=hash_key_value(token),
+ scopes=["insight:read"],
+ )
+ self.bearer = f"Bearer {token}"
+
+ @override_settings(INSIGHT_DASHBOARDS_OPT_IN_ENFORCED=True)
+ def test_enforced_personal_api_key_must_opt_in_to_deprecated_dashboards_field(self):
+ url = f"/api/projects/{self.team.id}/insights/{self.insight.id}/"
+
+ default_response = self.client.get(url, HTTP_AUTHORIZATION=self.bearer)
+ assert default_response.status_code == status.HTTP_200_OK
+ assert "dashboards" not in default_response.json()
+ assert [tile["dashboard_id"] for tile in default_response.json()["dashboard_tiles"]] == [self.dashboard.id]
+
+ opted_in_response = self.client.get(url, {"include_dashboards": "true"}, HTTP_AUTHORIZATION=self.bearer)
+ assert opted_in_response.status_code == status.HTTP_200_OK
+ assert opted_in_response.json()["dashboards"] == [self.dashboard.id]
+
+ def test_unenforced_personal_api_key_still_receives_deprecated_dashboards_field(self):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/insights/{self.insight.id}/", HTTP_AUTHORIZATION=self.bearer
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["dashboards"] == [self.dashboard.id]
+
+ def test_session_auth_still_receives_deprecated_dashboards_field(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/insights/{self.insight.id}/")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["dashboards"] == [self.dashboard.id]
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 73b7845293f5..9fded72c09f6 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -7608,9 +7608,15 @@ export interface InsightApi {
order?: number | null
deleted?: boolean
/**
+ *
* DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.
* A dashboard ID for each of the dashboards that this insight is displayed on.
- * */
+ * This field may be omitted from responses: once opt-in enforcement is enabled, API-token
+ * callers (personal API keys, OAuth) only receive it when passing the
+ * `include_dashboards=true` query parameter. Do not rely on it being present.
+ *
+ * @deprecated
+ */
dashboards?: number[]
/**
* A dashboard tile ID and dashboard_id for each of the dashboards that this insight is displayed on.
@@ -7730,9 +7736,15 @@ export interface PatchedInsightApi {
order?: number | null
deleted?: boolean
/**
+ *
* DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.
* A dashboard ID for each of the dashboards that this insight is displayed on.
- * */
+ * This field may be omitted from responses: once opt-in enforcement is enabled, API-token
+ * callers (personal API keys, OAuth) only receive it when passing the
+ * `include_dashboards=true` query parameter. Do not rely on it being present.
+ *
+ * @deprecated
+ */
dashboards?: number[]
/**
* A dashboard tile ID and dashboard_id for each of the dashboards that this insight is displayed on.
@@ -7969,7 +7981,8 @@ export interface TrendingInsightApi {
*/
derived_name?: string | null
query?: unknown
- readonly dashboards: readonly number[]
+ /** @deprecated */
+ readonly dashboards?: readonly number[]
readonly dashboard_tiles: readonly DashboardTileBasicApi[]
/**
* @maxLength 400
@@ -8126,6 +8139,10 @@ export type InsightsListParams = {
*/
favorited?: boolean
format?: InsightsListFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
/**
* Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.
*/
@@ -8211,6 +8228,10 @@ export const InsightsListRefresh = {
export type InsightsCreateParams = {
format?: InsightsCreateFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
}
export type InsightsCreateFormat = (typeof InsightsCreateFormat)[keyof typeof InsightsCreateFormat]
@@ -8232,6 +8253,10 @@ export type InsightsRetrieveParams = {
* When set, the specified dashboard's filters and date range override will be applied.
*/
from_dashboard?: number
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
/**
*
* Whether to refresh the insight, how aggresively, and if sync or async:
@@ -8271,6 +8296,10 @@ export const InsightsRetrieveRefresh = {
export type InsightsUpdateParams = {
format?: InsightsUpdateFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
}
export type InsightsUpdateFormat = (typeof InsightsUpdateFormat)[keyof typeof InsightsUpdateFormat]
@@ -8282,6 +8311,10 @@ export const InsightsUpdateFormat = {
export type InsightsPartialUpdateParams = {
format?: InsightsPartialUpdateFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
}
export type InsightsPartialUpdateFormat = (typeof InsightsPartialUpdateFormat)[keyof typeof InsightsPartialUpdateFormat]
@@ -8455,6 +8488,10 @@ export type InsightsTrendingRetrieveParams = {
*/
days?: number
format?: InsightsTrendingRetrieveFormat
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean
/**
* Maximum number of insights to return. Defaults to 10. Capped at 100.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c277bffe2193..bdab5d8b4577 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7805,9 +7805,15 @@ export namespace Schemas {
order?: number | null;
deleted?: boolean;
/**
+ *
* DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.
* A dashboard ID for each of the dashboards that this insight is displayed on.
- * */
+ * This field may be omitted from responses: once opt-in enforcement is enabled, API-token
+ * callers (personal API keys, OAuth) only receive it when passing the
+ * `include_dashboards=true` query parameter. Do not rely on it being present.
+ *
+ * @deprecated
+ */
dashboards?: number[];
/**
* A dashboard tile ID and dashboard_id for each of the dashboards that this insight is displayed on.
@@ -41228,7 +41234,8 @@ export namespace Schemas {
*/
derived_name?: string | null;
query?: unknown;
- readonly dashboards: readonly number[];
+ /** @deprecated */
+ readonly dashboards?: readonly number[];
readonly dashboard_tiles: readonly DashboardTileBasic[];
/**
* @maxLength 400
@@ -44905,9 +44912,15 @@ export namespace Schemas {
order?: number | null;
deleted?: boolean;
/**
+ *
* DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.
* A dashboard ID for each of the dashboards that this insight is displayed on.
- * */
+ * This field may be omitted from responses: once opt-in enforcement is enabled, API-token
+ * callers (personal API keys, OAuth) only receive it when passing the
+ * `include_dashboards=true` query parameter. Do not rely on it being present.
+ *
+ * @deprecated
+ */
dashboards?: number[];
/**
* A dashboard tile ID and dashboard_id for each of the dashboards that this insight is displayed on.
@@ -65250,6 +65263,10 @@ export namespace Schemas {
export type EnvironmentsDashboardsCreateParams = {
format?: EnvironmentsDashboardsCreateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type EnvironmentsDashboardsCreateFormat = typeof EnvironmentsDashboardsCreateFormat[keyof typeof EnvironmentsDashboardsCreateFormat];
@@ -65266,6 +65283,10 @@ export namespace Schemas {
*/
filters_override?: string;
format?: EnvironmentsDashboardsRetrieveFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
* Object (or pre-encoded JSON string) to override dashboard variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `dashboard-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.
*/
@@ -65282,6 +65303,10 @@ export namespace Schemas {
export type EnvironmentsDashboardsUpdateParams = {
format?: EnvironmentsDashboardsUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type EnvironmentsDashboardsUpdateFormat = typeof EnvironmentsDashboardsUpdateFormat[keyof typeof EnvironmentsDashboardsUpdateFormat];
@@ -65294,6 +65319,10 @@ export namespace Schemas {
export type EnvironmentsDashboardsPartialUpdateParams = {
format?: EnvironmentsDashboardsPartialUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type EnvironmentsDashboardsPartialUpdateFormat = typeof EnvironmentsDashboardsPartialUpdateFormat[keyof typeof EnvironmentsDashboardsPartialUpdateFormat];
@@ -67218,6 +67247,10 @@ export namespace Schemas {
*/
favorited?: boolean;
format?: EnvironmentsInsightsListFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
* Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.
*/
@@ -67306,6 +67339,10 @@ export namespace Schemas {
export type EnvironmentsInsightsCreateParams = {
format?: EnvironmentsInsightsCreateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type EnvironmentsInsightsCreateFormat = typeof EnvironmentsInsightsCreateFormat[keyof typeof EnvironmentsInsightsCreateFormat];
@@ -67339,6 +67376,10 @@ export namespace Schemas {
* When set, the specified dashboard's filters and date range override will be applied.
*/
from_dashboard?: number;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
*
* Whether to refresh the insight, how aggresively, and if sync or async:
@@ -67380,6 +67421,10 @@ export namespace Schemas {
export type EnvironmentsInsightsUpdateParams = {
format?: EnvironmentsInsightsUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type EnvironmentsInsightsUpdateFormat = typeof EnvironmentsInsightsUpdateFormat[keyof typeof EnvironmentsInsightsUpdateFormat];
@@ -67392,6 +67437,10 @@ export namespace Schemas {
export type EnvironmentsInsightsPartialUpdateParams = {
format?: EnvironmentsInsightsPartialUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type EnvironmentsInsightsPartialUpdateFormat = typeof EnvironmentsInsightsPartialUpdateFormat[keyof typeof EnvironmentsInsightsPartialUpdateFormat];
@@ -67568,6 +67617,10 @@ export namespace Schemas {
*/
days?: number;
format?: EnvironmentsInsightsTrendingRetrieveFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
* Maximum number of insights to return. Defaults to 10. Capped at 100.
*/
@@ -71732,6 +71785,10 @@ export namespace Schemas {
export type DashboardsCreateParams = {
format?: DashboardsCreateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type DashboardsCreateFormat = typeof DashboardsCreateFormat[keyof typeof DashboardsCreateFormat];
@@ -71748,6 +71805,10 @@ export namespace Schemas {
*/
filters_override?: string;
format?: DashboardsRetrieveFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
* Object (or pre-encoded JSON string) to override dashboard variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `dashboard-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.
*/
@@ -71764,6 +71825,10 @@ export namespace Schemas {
export type DashboardsUpdateParams = {
format?: DashboardsUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type DashboardsUpdateFormat = typeof DashboardsUpdateFormat[keyof typeof DashboardsUpdateFormat];
@@ -71776,6 +71841,10 @@ export namespace Schemas {
export type DashboardsPartialUpdateParams = {
format?: DashboardsPartialUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type DashboardsPartialUpdateFormat = typeof DashboardsPartialUpdateFormat[keyof typeof DashboardsPartialUpdateFormat];
@@ -74801,6 +74870,10 @@ export namespace Schemas {
*/
favorited?: boolean;
format?: InsightsListFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
* Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.
*/
@@ -74889,6 +74962,10 @@ export namespace Schemas {
export type InsightsCreateParams = {
format?: InsightsCreateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type InsightsCreateFormat = typeof InsightsCreateFormat[keyof typeof InsightsCreateFormat];
@@ -74922,6 +74999,10 @@ export namespace Schemas {
* When set, the specified dashboard's filters and date range override will be applied.
*/
from_dashboard?: number;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
*
* Whether to refresh the insight, how aggresively, and if sync or async:
@@ -74963,6 +75044,10 @@ export namespace Schemas {
export type InsightsUpdateParams = {
format?: InsightsUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type InsightsUpdateFormat = typeof InsightsUpdateFormat[keyof typeof InsightsUpdateFormat];
@@ -74975,6 +75060,10 @@ export namespace Schemas {
export type InsightsPartialUpdateParams = {
format?: InsightsPartialUpdateFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
};
export type InsightsPartialUpdateFormat = typeof InsightsPartialUpdateFormat[keyof typeof InsightsPartialUpdateFormat];
@@ -75151,6 +75240,10 @@ export namespace Schemas {
*/
days?: number;
format?: InsightsTrendingRetrieveFormat;
+ /**
+ * Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.
+ */
+ include_dashboards?: boolean;
/**
* Maximum number of insights to return. Defaults to 10. Capped at 100.
*/
diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.ts
index 0b5cee44eb9c..04ffef2025b6 100644
--- a/services/mcp/src/generated/dashboards/api.ts
+++ b/services/mcp/src/generated/dashboards/api.ts
@@ -44,6 +44,12 @@ export const DashboardsCreateParams = /* @__PURE__ */ zod.object({
export const DashboardsCreateQueryParams = /* @__PURE__ */ zod.object({
format: zod.enum(['json', 'txt']).optional(),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
})
export const dashboardsCreateBodyNameMax = 400
@@ -97,6 +103,12 @@ export const DashboardsRetrieveQueryParams = /* @__PURE__ */ zod.object({
'Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.'
),
format: zod.enum(['json', 'txt']).optional(),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
variables_override: zod
.string()
.optional()
@@ -116,6 +128,12 @@ export const DashboardsPartialUpdateParams = /* @__PURE__ */ zod.object({
export const DashboardsPartialUpdateQueryParams = /* @__PURE__ */ zod.object({
format: zod.enum(['json', 'txt']).optional(),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
})
export const dashboardsPartialUpdateBodyNameMax = 400
diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.ts
index 67b2ffd7d06a..0021360b1f54 100644
--- a/services/mcp/src/generated/product_analytics/api.ts
+++ b/services/mcp/src/generated/product_analytics/api.ts
@@ -109,6 +109,12 @@ export const InsightsListQueryParams = /* @__PURE__ */ zod.object({
.optional()
.describe('Include this parameter (any value) to restrict results to insights marked as favorited.'),
format: zod.enum(['csv', 'json']).optional(),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
insight: zod
.enum(['FUNNELS', 'JSON', 'LIFECYCLE', 'PATHS', 'RETENTION', 'SQL', 'STICKINESS', 'TRENDS'])
.optional()
@@ -182,6 +188,12 @@ export const InsightsCreateParams = /* @__PURE__ */ zod.object({
export const InsightsCreateQueryParams = /* @__PURE__ */ zod.object({
format: zod.enum(['csv', 'json']).optional(),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
})
export const insightsCreateBodyNameMax = 400
@@ -203,7 +215,7 @@ export const InsightsCreateBody = /* @__PURE__ */ zod
.array(zod.number())
.optional()
.describe(
- '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n '
+ '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n This field may be omitted from responses: once opt-in enforcement is enabled, API-token\n callers (personal API keys, OAuth) only receive it when passing the\n `include_dashboards=true` query parameter. Do not rely on it being present.\n '
),
description: zod.string().max(insightsCreateBodyDescriptionMax).nullish(),
tags: zod.array(zod.unknown()).optional(),
@@ -247,6 +259,12 @@ export const InsightsRetrieveQueryParams = /* @__PURE__ */ zod.object({
.describe(
"\nOnly if loading an insight in the context of a dashboard: The relevant dashboard's ID.\nWhen set, the specified dashboard's filters and date range override will be applied."
),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
refresh: zod
.enum([
'async',
@@ -290,6 +308,12 @@ export const InsightsPartialUpdateParams = /* @__PURE__ */ zod.object({
export const InsightsPartialUpdateQueryParams = /* @__PURE__ */ zod.object({
format: zod.enum(['csv', 'json']).optional(),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
})
export const insightsPartialUpdateBodyNameMax = 400
@@ -311,7 +335,7 @@ export const InsightsPartialUpdateBody = /* @__PURE__ */ zod
.array(zod.number())
.optional()
.describe(
- '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n '
+ '\n DEPRECATED. Will be removed in a future release. Use dashboard_tiles instead.\n A dashboard ID for each of the dashboards that this insight is displayed on.\n This field may be omitted from responses: once opt-in enforcement is enabled, API-token\n callers (personal API keys, OAuth) only receive it when passing the\n `include_dashboards=true` query parameter. Do not rely on it being present.\n '
),
description: zod.string().max(insightsPartialUpdateBodyDescriptionMax).nullish(),
tags: zod.array(zod.unknown()).optional(),
@@ -392,6 +416,12 @@ export const InsightsTrendingRetrieveQueryParams = /* @__PURE__ */ zod.object({
"Time window in days to compute view counts over. Defaults to 7. Larger windows surface consistently popular insights; smaller windows surface what's hot right now."
),
format: zod.enum(['csv', 'json']).optional(),
+ include_dashboards: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
+ ),
limit: zod.number().optional().describe('Maximum number of insights to return. Defaults to 10. Capped at 100.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.ts
index 7b370e653b4f..9876d59a2e72 100644
--- a/services/mcp/src/tools/generated/dashboards.ts
+++ b/services/mcp/src/tools/generated/dashboards.ts
@@ -6,6 +6,7 @@ import {
DashboardsCopyTileCreateBody,
DashboardsCopyTileCreateParams,
DashboardsCreateBody,
+ DashboardsCreateQueryParams,
DashboardsCreateTextTileCreateBody,
DashboardsCreateTextTileCreateParams,
DashboardsDeleteTileBody,
@@ -16,6 +17,7 @@ import {
DashboardsMoveTilePartialUpdateParams,
DashboardsPartialUpdateBody,
DashboardsPartialUpdateParams,
+ DashboardsPartialUpdateQueryParams,
DashboardsReorderTilesCreateBody,
DashboardsReorderTilesCreateParams,
DashboardsRetrieveParams,
@@ -35,7 +37,7 @@ import { castStringToInt } from '@/tools/cast-helpers'
import { withPostHogUrl, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-const DashboardCreateSchema = DashboardsCreateBody
+const DashboardCreateSchema = DashboardsCreateQueryParams.omit({ format: true }).extend(DashboardsCreateBody.shape)
const dashboardCreate = (): ToolBase<typeof DashboardCreateSchema, WithPostHogUrl<Schemas.Dashboard>> => ({
name: 'dashboard-create',
@@ -80,6 +82,9 @@ const dashboardCreate = (): ToolBase<typeof DashboardCreateSchema, WithPostHogUr
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/`,
body,
+ query: {
+ include_dashboards: params.include_dashboards,
+ },
})
const filtered = omitResponseFields(result, [
'effective_restriction_level',
@@ -223,6 +228,7 @@ const dashboardGet = (): ToolBase<typeof DashboardGetSchema, WithPostHogUrl<Sche
path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/${encodeURIComponent(String(params.id))}/`,
query: {
filters_override: params.filters_override,
+ include_dashboards: params.include_dashboards,
variables_override: params.variables_override,
},
})
@@ -358,6 +364,7 @@ const dashboardTileCopy = (): ToolBase<typeof DashboardTileCopySchema, WithPostH
})
const DashboardUpdateSchema = DashboardsPartialUpdateParams.omit({ project_id: true })
+ .extend(DashboardsPartialUpdateQueryParams.omit({ format: true }).shape)
.extend(DashboardsPartialUpdateBody.shape)
.extend({ id: z.preprocess(castStringToInt, DashboardsPartialUpdateParams.shape['id']) })
@@ -410,6 +417,9 @@ const dashboardUpdate = (): ToolBase<typeof DashboardUpdateSchema, WithPostHogUr
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/${encodeURIComponent(String(params.id))}/`,
body,
+ query: {
+ include_dashboards: params.include_dashboards,
+ },
})
const filtered = omitResponseFields(result, [
'effective_restriction_level',
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index 8554841a7d93..df29e1b74c86 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -288,6 +288,7 @@ const insightGet = (): ToolBase<typeof InsightGetSchema, WithPostHogUrl<Schemas.
path: `/api/projects/${encodeURIComponent(String(projectId))}/insights/${encodeURIComponent(String(params.id))}/`,
query: {
filters_override: params.filters_override,
+ include_dashboards: params.include_dashboards,
variables_override: params.variables_override,
},
})
@@ -447,6 +448,7 @@ const insightsList = (): ToolBase<typeof InsightsListSchema, WithPostHogUrl<Sche
date_from: params.date_from,
date_to: params.date_to,
favorited: params.favorited,
+ include_dashboards: params.include_dashboards,
insight: params.insight,
last_viewed_date_from: params.last_viewed_date_from,
last_viewed_date_to: params.last_viewed_date_to,
@@ -508,6 +510,7 @@ const insightsTrendingRetrieve = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/insights/trending/`,
query: {
days: params.days,
+ include_dashboards: params.include_dashboards,
limit: params.limit,
offset: params.offset,
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json
index f1d422edb809..acda1e859417 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json
@@ -1,6 +1,5 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
- "description": "Serializer mixin that handles tags for objects.",
"properties": {
"breakdown_colors": {
"description": "Custom color mapping for breakdown values."
@@ -24,6 +23,10 @@
"description": {
"type": "string"
},
+ "include_dashboards": {
+ "description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
+ "type": "boolean"
+ },
"name": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-get.json
index 3a65c2914419..8c6e3380c0a1 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-get.json
@@ -20,6 +20,10 @@
"description": "A unique integer value identifying this dashboard.",
"type": "number"
},
+ "include_dashboards": {
+ "description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
+ "type": "boolean"
+ },
"variables_override": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
index 49fd1130a241..85dfef2c9e07 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
@@ -57,6 +57,10 @@
"description": "A unique integer value identifying this dashboard.",
"type": "number"
},
+ "include_dashboards": {
+ "description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
+ "type": "boolean"
+ },
"name": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-get.json
index 2ac444800948..7137abe114ba 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-get.json
@@ -27,6 +27,10 @@
],
"description": "Numeric primary key or 8-character `short_id` (for example `AaVQ8Ijw`) identifying the insight."
},
+ "include_dashboards": {
+ "description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
+ "type": "boolean"
+ },
"variables_override": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
index 494569e6de0d..7992d5d10f3a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
@@ -29,6 +29,10 @@
"description": "Include this parameter (any value) to restrict results to insights marked as favorited.",
"type": "boolean"
},
+ "include_dashboards": {
+ "description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
+ "type": "boolean"
+ },
"insight": {
"description": "Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.",
"enum": ["FUNNELS", "JSON", "LIFECYCLE", "PATHS", "RETENTION", "SQL", "STICKINESS", "TRENDS"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-trending-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-trending-retrieve.json
index 79b9abe12acc..d6bf15229ce3 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-trending-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-trending-retrieve.json
@@ -5,6 +5,10 @@
"description": "Time window in days to compute view counts over. Defaults to 7. Larger windows surface consistently popular insights; smaller windows surface what's hot right now.",
"type": "number"
},
+ "include_dashboards": {
+ "description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
+ "type": "boolean"
+ },
"limit": {
"description": "Maximum number of insights to return. Defaults to 10. Capped at 100.",
"type": "number"