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(warehouse-suggestions): show open suggestions on mcp view reads (#114374)

Thiago Salvatore96fab92724a1
diff --git a/products/data_catalog/skills/setting-up-data-catalog/SKILL.md b/products/data_catalog/skills/setting-up-data-catalog/SKILL.md
index 3403b8a86751..630d214ef5da 100644
--- a/products/data_catalog/skills/setting-up-data-catalog/SKILL.md
+++ b/products/data_catalog/skills/setting-up-data-catalog/SKILL.md
@@ -76,6 +76,13 @@ Work top-down, stopping at `proposed` for everything (a human promotes later):
physical table the mark applies to when two live tables share a name, and `proposed_status` tells you
whether the row asks to certify the source or to deprecate it.
+ If the `warehouse-suggestions-*` tools are available, also call `warehouse-suggestions-list` with
+ `status=proposed`. A `certify` suggestion names a view or table that read usage says to certify. A
+ `deprecate` suggestion names a materialized view that nobody reads. Neither is in `certifications` until
+ someone accepts it: accept with
+ `posthog:warehouse-suggestions-accept-prepare` / `-execute`, or dismiss with
+ `posthog:warehouse-suggestions-dismiss`.
+
Each entity type keeps its pending queue separate from its usable/verified surface, so an agent
without this skill never mistakes an unreviewed item for an approved one:
`information_schema.relationships` lists only real joins (a proposal shows up there **only after**
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yaml
index 20ae4ec3202b..2ddcf47d20c2 100644
--- a/products/data_warehouse/mcp/tools.yaml
+++ b/products/data_warehouse/mcp/tools.yaml
@@ -187,6 +187,7 @@ tools:
query, column schema, materialization status, sync frequency, and run history metadata. Also returns the
view's semantic `description` and a `description` on each entry of `columns` when set — use this to see what
a view and its columns mean.
+ hooks: dataWarehouse/viewGetHooks
view-list:
operation: warehouse_saved_queries_list
enabled: true
diff --git a/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.md b/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.md
index 2c890b250059..4a31ebc8aff1 100644
--- a/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.md
+++ b/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.md
@@ -27,11 +27,12 @@ relevant team rather than diagnosing here.
## Available tools
-| Tool | Purpose |
-| -------------------------------------------- | ------------------------------------------------------------------- |
-| `data-warehouse-data-health-issues-retrieve` | One-shot: all failed/degraded items across the whole pipeline |
-| `view-list` | All saved queries / materialized views with status and latest_error |
-| `view-run-history` | Run history for a specific materialized view |
+| Tool | Purpose |
+| -------------------------------------------- | -------------------------------------------------------------------- |
+| `data-warehouse-data-health-issues-retrieve` | One-shot: all failed/degraded items across the whole pipeline |
+| `view-list` | All saved queries / materialized views with status and latest_error |
+| `view-run-history` | Run history for a specific materialized view |
+| `warehouse-suggestions-list` | PostHog's open deprecate / materialize / certify suggestions, if any |
Filter the `data-health-issues` results to the `materialized_view` type for this audit. Use `view-list` when you need
more than the active-failure summary (non-failing views, materialization flags, last-queried info) and
@@ -91,6 +92,19 @@ Both are HogQL issues in the view definitions — independent of your sources. W
### Step 4 — Go beyond active failures (when asked)
+**Start from PostHog's suggestions** if the `warehouse-suggestions-*` tools are available. Call
+`warehouse-suggestions-list` with `status=proposed`. PostHog computes these from read usage:
+
+- A `deprecate` suggestion names a materialized view that nobody reads. Accepting it marks the view deprecated in the
+ data catalog. The view keeps refreshing, so it still costs compute. To stop that cost, unmaterialize the view with
+ `view-unmaterialize`, after the user confirms.
+- A `materialize` suggestion names a view that is read often enough that materializing it saves compute. Accepting it
+ turns on materialization with the proposed refresh interval.
+
+Present them before any hand audit. Accept one with `warehouse-suggestions-accept-prepare` / `-execute` after the user
+types `confirm`, or dismiss it with `warehouse-suggestions-dismiss`. If the list is empty, `warehouse-suggestions-status`
+tells you whether suggestions are still warming up, not eligible, or turned off.
+
**Unused materialized views:**
Call `view-list`. Materialized views cost storage and compute every run. If any are marked materialized but haven't
been queried lately, surface them as cleanup candidates (the data is available via `view-list`; unmaterialize via
diff --git a/products/warehouse_suggestions/backend/facade/api.py b/products/warehouse_suggestions/backend/facade/api.py
index 9838df86c8d9..0ec7539244a1 100644
--- a/products/warehouse_suggestions/backend/facade/api.py
+++ b/products/warehouse_suggestions/backend/facade/api.py
@@ -15,6 +15,7 @@ from ..models import WarehouseSuggestion, WarehouseSuggestionTeamConfig
from .contracts import (
CatalogEditAccessRequiredError,
SubjectEditAccessRequiredError,
+ SubjectKinds,
Suggestion,
SuggestionDraft,
SuggestionNotFoundError,
@@ -60,10 +61,14 @@ def list_suggestions(
*,
kind: WarehouseSuggestionKind | None,
status: WarehouseSuggestionStatus | None,
+ subject_id: UUID | None,
+ subject_kinds: SubjectKinds,
limit: int,
offset: int,
) -> SuggestionPage:
- visible, access = visible_suggestions(team_id, user_access_control, kind=kind, status=status)
+ visible, access = visible_suggestions(
+ team_id, user_access_control, kind=kind, status=status, subject_id=subject_id, subject_kinds=subject_kinds
+ )
page = list(visible[offset : offset + limit])
return SuggestionPage(count=visible.count(), results=_to_contracts(team_id, user_access_control, page, access))
@@ -80,8 +85,14 @@ def suggestion_status(team_id: int) -> SuggestionStatus:
)
-def get_suggestion(team_id: int, user_access_control: "UserAccessControl", suggestion_id: UUID) -> Suggestion:
- row, access = _visible_suggestion(team_id, user_access_control, suggestion_id)
+def get_suggestion(
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ suggestion_id: UUID,
+ *,
+ subject_kinds: SubjectKinds,
+) -> Suggestion:
+ row, access = _visible_suggestion(team_id, user_access_control, suggestion_id, subject_kinds)
return _single_contract(team_id, user_access_control, row, access)
@@ -93,8 +104,9 @@ def dismiss_suggestion(
user: "User",
reason: WarehouseSuggestionDismissalReason,
note: str | None,
+ subject_kinds: SubjectKinds,
) -> Suggestion:
- row, access = _actionable_suggestion(team.pk, user_access_control, suggestion_id)
+ row, access = _actionable_suggestion(team.pk, user_access_control, suggestion_id, subject_kinds)
dismissed = suggestions.transition_to(
row.id,
team.pk,
@@ -109,9 +121,14 @@ def dismiss_suggestion(
def resume_suggestion(
- team: "Team", user_access_control: "UserAccessControl", suggestion_id: UUID, *, user: "User"
+ team: "Team",
+ user_access_control: "UserAccessControl",
+ suggestion_id: UUID,
+ *,
+ user: "User",
+ subject_kinds: SubjectKinds,
) -> Suggestion:
- row, access = _actionable_suggestion(team.pk, user_access_control, suggestion_id)
+ row, access = _actionable_suggestion(team.pk, user_access_control, suggestion_id, subject_kinds)
resumed = suggestions.transition_to(
row.id, team.pk, WarehouseSuggestionStatus.PROPOSED, user_id=user.id, transitions=suggestions.HUMAN_TRANSITIONS
)
@@ -127,8 +144,9 @@ def accept_suggestion(
user: "User",
refresh_interval: timedelta | None,
was_impersonated: bool,
+ subject_kinds: SubjectKinds,
) -> Suggestion:
- row, access = _actionable_suggestion(team.pk, user_access_control, suggestion_id)
+ row, access = _actionable_suggestion(team.pk, user_access_control, suggestion_id, subject_kinds)
_require_catalog_edit_access(row, user_access_control)
outcome = accept.accept(
team.pk,
@@ -143,9 +161,12 @@ def accept_suggestion(
def _actionable_suggestion(
- team_id: int, user_access_control: "UserAccessControl", suggestion_id: UUID
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ suggestion_id: UUID,
+ subject_kinds: SubjectKinds,
) -> tuple[WarehouseSuggestion, SubjectAccess]:
- row, access = _visible_suggestion(team_id, user_access_control, suggestion_id)
+ row, access = _visible_suggestion(team_id, user_access_control, suggestion_id, subject_kinds)
if not access.can_act_on(row):
raise SubjectEditAccessRequiredError(WarehouseSuggestionSubjectKind(row.subject_kind))
return row, access
@@ -166,9 +187,14 @@ def _single_contract(
def _visible_suggestion(
- team_id: int, user_access_control: "UserAccessControl", suggestion_id: UUID
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ suggestion_id: UUID,
+ subject_kinds: SubjectKinds,
) -> tuple[WarehouseSuggestion, SubjectAccess]:
- visible, access = visible_suggestions(team_id, user_access_control, suggestion_id=suggestion_id)
+ visible, access = visible_suggestions(
+ team_id, user_access_control, suggestion_id=suggestion_id, subject_kinds=subject_kinds
+ )
row = visible.first()
if row is None:
raise SuggestionNotFoundError(suggestion_id)
diff --git a/products/warehouse_suggestions/backend/facade/contracts.py b/products/warehouse_suggestions/backend/facade/contracts.py
index c2eaa3e7b226..cf1f04222044 100644
--- a/products/warehouse_suggestions/backend/facade/contracts.py
+++ b/products/warehouse_suggestions/backend/facade/contracts.py
@@ -17,6 +17,12 @@ from .enums import (
PAYLOAD_VERSION = 1
+@frozen
+class SubjectKinds:
+ readable: frozenset[WarehouseSuggestionSubjectKind]
+ actionable: frozenset[WarehouseSuggestionSubjectKind]
+
+
@frozen
class SourceRef:
name: str
diff --git a/products/warehouse_suggestions/backend/logic/access.py b/products/warehouse_suggestions/backend/logic/access.py
index 7e882a83ad73..8dca2a9995f8 100644
--- a/products/warehouse_suggestions/backend/logic/access.py
+++ b/products/warehouse_suggestions/backend/logic/access.py
@@ -10,6 +10,7 @@ from posthog.dataclasses import frozen
from products.data_modeling.backend.facade.api import allowed_saved_query_ids, backing_table_ids_by_saved_query
from products.warehouse_sources.backend.facade.api import allowed_table_ids
+from ..facade.contracts import SubjectKinds
from ..facade.enums import WarehouseSuggestionKind, WarehouseSuggestionStatus, WarehouseSuggestionSubjectKind
from ..models import WarehouseSuggestion
from .rules import RULES
@@ -59,9 +60,13 @@ def visible_suggestions(
suggestion_id: UUID | None = None,
kind: WarehouseSuggestionKind | None = None,
status: WarehouseSuggestionStatus | None = None,
+ subject_id: UUID | None = None,
+ subject_kinds: SubjectKinds,
) -> tuple[QuerySet[WarehouseSuggestion], SubjectAccess]:
- suggestions = WarehouseSuggestion.objects.for_team(team_id).exclude(
- status=WarehouseSuggestionStatus.PROPOSED, surfaced_at__isnull=True
+ suggestions = (
+ WarehouseSuggestion.objects.for_team(team_id)
+ .filter(subject_kind__in=subject_kinds.readable)
+ .exclude(status=WarehouseSuggestionStatus.PROPOSED, surfaced_at__isnull=True)
)
if suggestion_id is not None:
suggestions = suggestions.filter(id=suggestion_id)
@@ -69,7 +74,9 @@ def visible_suggestions(
suggestions = suggestions.filter(kind=kind)
if status is not None:
suggestions = suggestions.filter(status=status)
- access = subject_access(team_id, user_access_control, suggestions)
+ if subject_id is not None:
+ suggestions = suggestions.filter(subject_id=subject_id)
+ access = subject_access(team_id, user_access_control, suggestions, actionable_kinds=subject_kinds.actionable)
visible = (
suggestions.filter(access.readable_q())
.select_related("reviewed_by")
@@ -80,7 +87,11 @@ def visible_suggestions(
def subject_access(
- team_id: int, user_access_control: "UserAccessControl", suggestions: QuerySet[WarehouseSuggestion]
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ suggestions: QuerySet[WarehouseSuggestion],
+ *,
+ actionable_kinds: Collection[WarehouseSuggestionSubjectKind],
) -> SubjectAccess:
subject_ids: defaultdict[WarehouseSuggestionSubjectKind, set[UUID]] = defaultdict(set)
for subject_kind, subject_id in suggestions.order_by().values_list("subject_kind", "subject_id").distinct():
@@ -88,7 +99,8 @@ def subject_access(
table_ids = subject_ids[WarehouseSuggestionSubjectKind.TABLE]
table_ids.difference_update(backing_table_ids_by_saved_query(team_id, table_ids=table_ids))
readable = _allowed(team_id, user_access_control, "viewer", subject_ids)
- editable = _allowed(team_id, user_access_control, "editor", readable)
+ actionable = {subject_kind: ids for subject_kind, ids in readable.items() if subject_kind in actionable_kinds}
+ editable = _allowed(team_id, user_access_control, "editor", actionable)
return SubjectAccess(readable=readable, editable=editable)
diff --git a/products/warehouse_suggestions/backend/presentation/serializers.py b/products/warehouse_suggestions/backend/presentation/serializers.py
index 6a965474e2b4..0797f4a6e168 100644
--- a/products/warehouse_suggestions/backend/presentation/serializers.py
+++ b/products/warehouse_suggestions/backend/presentation/serializers.py
@@ -189,6 +189,9 @@ class WarehouseSuggestionListQuerySerializer(serializers.Serializer):
status = serializers.ChoiceField(
choices=WarehouseSuggestionStatus.choices, required=False, help_text="Only return suggestions in this status."
)
+ subject_id = serializers.UUIDField(
+ required=False, help_text="Only return suggestions about the view or table with this ID."
+ )
class DismissWarehouseSuggestionSerializer(serializers.Serializer):
diff --git a/products/warehouse_suggestions/backend/presentation/views.py b/products/warehouse_suggestions/backend/presentation/views.py
index 39f001ecf279..942f77b37abc 100644
--- a/products/warehouse_suggestions/backend/presentation/views.py
+++ b/products/warehouse_suggestions/backend/presentation/views.py
@@ -2,7 +2,8 @@
from collections.abc import Callable
from datetime import timedelta
-from typing import Any, cast
+from functools import cached_property
+from typing import Any, Literal, cast
from uuid import UUID
from drf_spectacular.utils import OpenApiResponse, extend_schema
@@ -20,7 +21,8 @@ from posthog.api.utils import action
from posthog.exceptions import Conflict
from posthog.helpers.impersonation import is_impersonated
from posthog.models import User
-from posthog.permissions import APIScopePermission, TeamMemberAccessPermission
+from posthog.permissions import APIScopePermission, TeamMemberAccessPermission, get_authenticator_scopes
+from posthog.scopes import scopes_not_covered
from posthog.utils import UUID_REGEX
from ..facade import api
@@ -31,6 +33,7 @@ from ..facade.contracts import (
RefreshIntervalRefusedError,
SubjectAlreadyCertifiedError,
SubjectEditAccessRequiredError,
+ SubjectKinds,
Suggestion,
SuggestionAlreadyDecidedError,
SuggestionNotFoundError,
@@ -62,7 +65,12 @@ ALREADY_CERTIFIED = {
WarehouseSuggestionSubjectKind.TABLE: "This table already has a certification.",
}
CATALOG_EDIT_ACCESS_REQUIRED = "You need edit access to the data catalog to accept this suggestion."
-ACCEPT_SCOPES = ["warehouse_objects:write", "data_catalog_approval:write", "warehouse_view:write"]
+ACCEPT_SCOPES = ["data_catalog_approval:write", "warehouse_view:write"]
+ScopeLevel = Literal["read", "write"]
+SUBJECT_SCOPE_OBJECTS = {
+ WarehouseSuggestionSubjectKind.SAVED_QUERY: "warehouse_view",
+ WarehouseSuggestionSubjectKind.TABLE: "warehouse_table",
+}
class SuggestionPagination(LimitOffsetPagination):
@@ -99,6 +107,36 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
if not is_warehouse_suggestions_enabled(self.team):
raise PermissionDenied("Warehouse suggestions are not enabled for this project.")
+ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:
+ level = self._scope_level
+ fallback = f"{SUBJECT_SCOPE_OBJECTS[WarehouseSuggestionSubjectKind.SAVED_QUERY]}:{level}"
+ subject_scope = next(iter(self._token_scopes_by_kind(level).values()), fallback)
+ return [subject_scope, *ACCEPT_SCOPES] if self.action == "accept" else [subject_scope]
+
+ @property
+ def _scope_level(self) -> ScopeLevel:
+ return "write" if self.action in self.scope_object_write_actions else "read"
+
+ def _token_scopes_by_kind(self, level: ScopeLevel) -> dict[WarehouseSuggestionSubjectKind, str]:
+ held = get_authenticator_scopes(self.request.successful_authenticator) or ()
+ reaching: dict[WarehouseSuggestionSubjectKind, str] = {}
+ for subject_kind, scope_object in SUBJECT_SCOPE_OBJECTS.items():
+ candidates = (f"{self.scope_object}:{level}", f"{scope_object}:{level}")
+ held_scope = next((scope for scope in candidates if not scopes_not_covered(held, [scope])), None)
+ if held_scope is not None:
+ reaching[subject_kind] = held_scope
+ return reaching
+
+ def _kinds_reached(self, level: ScopeLevel) -> frozenset[WarehouseSuggestionSubjectKind]:
+ held = get_authenticator_scopes(self.request.successful_authenticator)
+ if held is None or "*" in held:
+ return frozenset(WarehouseSuggestionSubjectKind)
+ return frozenset(self._token_scopes_by_kind(level))
+
+ @cached_property
+ def _subject_kinds(self) -> SubjectKinds:
+ return SubjectKinds(readable=self._kinds_reached("read"), actionable=self._kinds_reached("write"))
+
@validated_request(
query_serializer=WarehouseSuggestionListQuerySerializer,
responses={200: OpenApiResponse(response=WarehouseSuggestionSerializer(many=True))},
@@ -113,6 +151,8 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
self.user_access_control,
kind=WarehouseSuggestionKind(kind) if kind else None,
status=WarehouseSuggestionStatus(status) if status else None,
+ subject_id=request.validated_query_data.get("subject_id"),
+ subject_kinds=self._subject_kinds,
limit=limit,
offset=offset,
),
@@ -125,7 +165,11 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
@extend_schema(responses={200: WarehouseSuggestionSerializer})
def retrieve(self, request: Request, pk: str, **kwargs: Any) -> Response:
- return self._respond(lambda: api.get_suggestion(self.team_id, self.user_access_control, UUID(pk)))
+ return self._respond(
+ lambda: api.get_suggestion(
+ self.team_id, self.user_access_control, UUID(pk), subject_kinds=self._subject_kinds
+ )
+ )
@validated_request(
request_serializer=DismissWarehouseSuggestionSerializer,
@@ -141,6 +185,7 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
user=cast(User, request.user),
reason=request.validated_data["reason"],
note=request.validated_data.get("note") or None,
+ subject_kinds=self._subject_kinds,
)
)
@@ -148,7 +193,7 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
request_serializer=AcceptWarehouseSuggestionSerializer,
responses={200: OpenApiResponse(response=WarehouseSuggestionSerializer)},
)
- @action(detail=True, methods=["post"], required_scopes=ACCEPT_SCOPES)
+ @action(detail=True, methods=["post"])
def accept(self, request: ValidatedRequest, pk: str, **kwargs: Any) -> Response:
interval_seconds = request.validated_data.get("refresh_interval_seconds")
return self._respond(
@@ -159,6 +204,7 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
user=cast(User, request.user),
refresh_interval=timedelta(seconds=interval_seconds) if interval_seconds else None,
was_impersonated=is_impersonated(request),
+ subject_kinds=self._subject_kinds,
)
)
@@ -166,7 +212,13 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
@action(detail=True, methods=["post"])
def resume(self, request: Request, pk: str, **kwargs: Any) -> Response:
return self._respond(
- lambda: api.resume_suggestion(self.team, self.user_access_control, UUID(pk), user=cast(User, request.user))
+ lambda: api.resume_suggestion(
+ self.team,
+ self.user_access_control,
+ UUID(pk),
+ user=cast(User, request.user),
+ subject_kinds=self._subject_kinds,
+ )
)
def _respond(self, decide_or_read: Callable[[], Suggestion]) -> Response:
diff --git a/products/warehouse_suggestions/backend/tests/test_accept.py b/products/warehouse_suggestions/backend/tests/test_accept.py
index 2d021d8af305..ba4045605160 100644
--- a/products/warehouse_suggestions/backend/tests/test_accept.py
+++ b/products/warehouse_suggestions/backend/tests/test_accept.py
@@ -196,6 +196,11 @@ class TestAcceptSuggestion(APIBaseTest):
["warehouse_objects:write", "data_catalog_approval:write", "warehouse_view:write"],
status.HTTP_200_OK,
),
+ (
+ "per_kind_scopes_a_cli_key_carries",
+ ["data_catalog_approval:write", "warehouse_view:write"],
+ status.HTTP_200_OK,
+ ),
(
"no_view_write_scope",
["warehouse_objects:write", "data_catalog_approval:write"],
diff --git a/products/warehouse_suggestions/backend/tests/test_api.py b/products/warehouse_suggestions/backend/tests/test_api.py
index 0f923cb3579a..f9b74f60ac23 100644
--- a/products/warehouse_suggestions/backend/tests/test_api.py
+++ b/products/warehouse_suggestions/backend/tests/test_api.py
@@ -14,6 +14,8 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.models.access_control import AccessControl
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
@@ -182,6 +184,7 @@ class TestWarehouseSuggestionAPI(APIBaseTest):
("by_kind", "kind=deprecate", status.HTTP_200_OK, ["table"]),
("by_status", "status=dismissed", status.HTTP_200_OK, ["table"]),
("by_kind_and_status", "kind=certify&status=dismissed", status.HTTP_200_OK, []),
+ ("by_subject", "subject_id={view_id}", status.HTTP_200_OK, ["view"]),
("unknown_status", "status=bogus", status.HTTP_400_BAD_REQUEST, None),
]
)
@@ -198,13 +201,72 @@ class TestWarehouseSuggestionAPI(APIBaseTest):
),
)
- response = self.client.get(f"{self.url}/?{query}")
+ response = self.client.get(f"{self.url}/?{query.format(view_id=self.view.id)}")
assert response.status_code == expected_status, response.json()
if expected is not None:
assert response.json()["count"] == len(expected)
assert [row["id"] for row in response.json()["results"]] == [str(ids[name]) for name in expected]
+ def _bearer(self, scopes: list[str]) -> str:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="k", user=self.user, secure_value=hash_key_value(token), scopes=scopes)
+ self.client.logout()
+ return f"Bearer {token}"
+
+ @parameterized.expand(
+ [
+ ("view_scope", ["warehouse_view:write"], {"view": True}, {"view": 200, "table": 404}),
+ ("table_scope", ["warehouse_table:write"], {"table": True}, {"view": 404, "table": 200}),
+ ("umbrella_scope", ["warehouse_objects:write"], {"view": True, "table": True}, {"view": 200, "table": 200}),
+ (
+ "view_read_and_table_write",
+ ["warehouse_view:read", "warehouse_table:write"],
+ {"view": False, "table": True},
+ {"view": 403, "table": 200},
+ ),
+ ("no_warehouse_scope", ["insight:write"], None, {"view": 403, "table": 403}),
+ ]
+ )
+ def test_a_token_reaches_only_the_subject_kinds_its_scopes_name(
+ self, _name: str, scopes: list[str], expected_can_act: dict[str, bool] | None, expected_dismiss: dict[str, int]
+ ) -> None:
+ ids = {
+ "view": self._suggest(self.view.id).id,
+ "table": self._suggest(self.table.id, subject_kind=WarehouseSuggestionSubjectKind.TABLE).id,
+ }
+ bearer = self._bearer(scopes)
+
+ listed = self.client.get(f"{self.url}/", HTTP_AUTHORIZATION=bearer)
+ dismissed = {
+ name: self.client.post(
+ f"{self.url}/{suggestion_id}/dismiss/",
+ {"reason": WarehouseSuggestionDismissalReason.NOT_NOW},
+ HTTP_AUTHORIZATION=bearer,
+ ).status_code
+ for name, suggestion_id in ids.items()
+ }
+
+ if expected_can_act is None:
+ assert listed.status_code == status.HTTP_403_FORBIDDEN, listed.json()
+ else:
+ names_by_id = {str(suggestion_id): name for name, suggestion_id in ids.items()}
+ listed_can_act = {names_by_id[row["id"]]: row["can_act"] for row in listed.json()["results"]}
+ assert listed_can_act == expected_can_act
+ assert dismissed == expected_dismiss
+
+ def test_a_token_without_a_write_scope_is_told_which_one_to_add(self) -> None:
+ suggestion = self._suggest(self.view.id)
+
+ response = self.client.post(
+ f"{self.url}/{suggestion.id}/dismiss/",
+ {"reason": WarehouseSuggestionDismissalReason.NOT_NOW},
+ HTTP_AUTHORIZATION=self._bearer(["warehouse_view:read"]),
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert "warehouse_view:write" in response.json()["detail"]
+
def test_the_flag_off_forbids_the_endpoint(self) -> None:
with patch(FLAG, return_value=False):
response = self.client.get(f"{self.url}/")
diff --git a/products/warehouse_suggestions/frontend/generated/api.schemas.ts b/products/warehouse_suggestions/frontend/generated/api.schemas.ts
index 61a1810263c5..254204d2ea7d 100644
--- a/products/warehouse_suggestions/frontend/generated/api.schemas.ts
+++ b/products/warehouse_suggestions/frontend/generated/api.schemas.ts
@@ -305,6 +305,10 @@ export type WarehouseSuggestionsListParams = {
* @minLength 1
*/
status?: WarehouseSuggestionsListStatus
+ /**
+ * Only return suggestions about the view or table with this ID.
+ */
+ subject_id?: string
}
export type WarehouseSuggestionsListKind =
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 836ba7153c06..86ed88119e58 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -127801,6 +127801,10 @@ export namespace Schemas {
* @minLength 1
*/
status?: WarehouseSuggestionsListStatus;
+ /**
+ * Only return suggestions about the view or table with this ID.
+ */
+ subject_id?: string;
};
export type WarehouseSuggestionsListKind = typeof WarehouseSuggestionsListKind[keyof typeof WarehouseSuggestionsListKind];
diff --git a/services/mcp/src/tools/dataWarehouse/viewGetHooks.ts b/services/mcp/src/tools/dataWarehouse/viewGetHooks.ts
new file mode 100644
index 000000000000..b12d6ae3a872
--- /dev/null
+++ b/services/mcp/src/tools/dataWarehouse/viewGetHooks.ts
@@ -0,0 +1,55 @@
+import type { Schemas } from '@/api/generated'
+import type { ToolHooks } from '@/tools/tool-hooks'
+import type { Context } from '@/tools/types'
+
+export const SUGGESTIONS_TIMEOUT_MS = 2000
+const OPEN_STATUS = 'proposed'
+const ACTIONABLE_NOTE =
+ 'PostHog suggests these changes to this view. Accept one with warehouse-suggestions-accept-prepare, or dismiss it with warehouse-suggestions-dismiss.'
+const READ_ONLY_NOTE =
+ 'PostHog suggests these changes to this view. Accepting or dismissing them needs edit access to the view and an API key with write scope, so share them with someone who has both.'
+
+type ViewGetParams = { id: string }
+type OpenSuggestion = Pick<Schemas.WarehouseSuggestion, 'id' | 'kind' | 'payload' | 'can_act'>
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+async function withinTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const timeout = new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms`)), timeoutMs)
+ })
+ try {
+ return await Promise.race([promise, timeout])
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+async function fetchOpenSuggestions(context: Context, viewId: string): Promise<OpenSuggestion[]> {
+ const projectId = await context.stateManager.getProjectId()
+ const page = await context.api.request<Schemas.PaginatedWarehouseSuggestionList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_suggestions/`,
+ query: { subject_id: viewId, status: OPEN_STATUS },
+ })
+ return (page.results ?? []).map(({ id, kind, payload, can_act }) => ({ id, kind, payload, can_act }))
+}
+
+async function afterResponse(context: Context, params: ViewGetParams, result: unknown): Promise<unknown> {
+ if (!isRecord(result)) {
+ return result
+ }
+ const openSuggestions = await withinTimeout(fetchOpenSuggestions(context, params.id), SUGGESTIONS_TIMEOUT_MS).catch(
+ () => []
+ )
+ if (openSuggestions.length === 0) {
+ return result
+ }
+ const note = openSuggestions.some((openSuggestion) => openSuggestion.can_act) ? ACTIONABLE_NOTE : READ_ONLY_NOTE
+ return { ...result, open_suggestions: openSuggestions, open_suggestions_note: note }
+}
+
+export default { afterResponse } satisfies ToolHooks<ViewGetParams>
diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.ts
index ae8b04bf0058..6fab39a510b8 100644
--- a/services/mcp/src/tools/generated/data_warehouse.ts
+++ b/services/mcp/src/tools/generated/data_warehouse.ts
@@ -3,6 +3,8 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/data_warehouse/api'
+import hooks_viewGet from '@/tools/dataWarehouse/viewGetHooks'
+import { withToolHooks } from '@/tools/tool-hooks'
import {
withPostHogUrl,
pickResponseFields,
@@ -298,14 +300,17 @@ const ViewGetSchema = () => {
const viewGet = (): ToolBase<ReturnType<typeof ViewGetSchema>, WithPostHogUrl<Schemas.DataWarehouseSavedQuery>> => ({
name: 'view-get',
schema: ViewGetSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof ViewGetSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.DataWarehouseSavedQuery>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/`,
- })
- return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)
- },
+ handler: withToolHooks(
+ hooks_viewGet,
+ async (context: Context, params: z.infer<ReturnType<typeof ViewGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.DataWarehouseSavedQuery>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/`,
+ })
+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)
+ }
+ ),
})
const ViewListSchema = () => {
diff --git a/services/mcp/tests/unit/view-get-hooks.test.ts b/services/mcp/tests/unit/view-get-hooks.test.ts
new file mode 100644
index 000000000000..1288e53a5c76
--- /dev/null
+++ b/services/mcp/tests/unit/view-get-hooks.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import viewGetHooks, { SUGGESTIONS_TIMEOUT_MS } from '@/tools/dataWarehouse/viewGetHooks'
+import type { Context } from '@/tools/types'
+
+const VIEW = { id: 'view-1', name: 'orders' }
+
+function suggestion(canAct: boolean): Record<string, unknown> {
+ return {
+ id: 'suggestion-1',
+ kind: 'materialize',
+ subject_kind: 'saved_query',
+ subject_id: 'view-1',
+ payload: { subject_name: 'orders' },
+ status: 'proposed',
+ score: 3,
+ can_act: canAct,
+ }
+}
+
+function contextWith(request: () => Promise<unknown>): { context: Context; request: ReturnType<typeof vi.fn> } {
+ const requestMock = vi.fn(request)
+ const context = {
+ stateManager: { getProjectId: async () => '7' },
+ api: { request: requestMock },
+ } as unknown as Context
+ return { context, request: requestMock }
+}
+
+describe('viewGetHooks.afterResponse', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it.each([
+ { name: 'one the caller can act on', canAct: true, note: 'warehouse-suggestions-accept-prepare' },
+ { name: 'none the caller can act on', canAct: false, note: 'edit access' },
+ ])('attaches the open suggestions of the view, with $name', async ({ canAct, note }) => {
+ const { context, request } = contextWith(async () => ({ count: 1, results: [suggestion(canAct)] }))
+
+ const result = await viewGetHooks.afterResponse(context, { id: VIEW.id }, VIEW)
+
+ expect(request).toHaveBeenCalledWith({
+ method: 'GET',
+ path: '/api/projects/7/warehouse_suggestions/',
+ query: { subject_id: VIEW.id, status: 'proposed' },
+ })
+ expect(result).toEqual({
+ ...VIEW,
+ open_suggestions: [
+ { id: 'suggestion-1', kind: 'materialize', payload: { subject_name: 'orders' }, can_act: canAct },
+ ],
+ open_suggestions_note: expect.stringContaining(note),
+ })
+ })
+
+ it.each([
+ { name: 'no open suggestions', request: async () => ({ count: 0, results: [] }) },
+ {
+ name: 'the suggestions request fails',
+ request: async () => {
+ throw new Error('Warehouse suggestions are not enabled for this project.')
+ },
+ },
+ ])('returns the view unchanged when $name', async ({ request }) => {
+ const { context } = contextWith(request)
+
+ await expect(viewGetHooks.afterResponse(context, { id: VIEW.id }, VIEW)).resolves.toBe(VIEW)
+ })
+
+ it('returns the view unchanged when the suggestions request outlasts the timeout', async () => {
+ vi.useFakeTimers()
+ const { context } = contextWith(() => new Promise(() => {}))
+
+ const result = viewGetHooks.afterResponse(context, { id: VIEW.id }, VIEW)
+ await vi.advanceTimersByTimeAsync(SUGGESTIONS_TIMEOUT_MS)
+
+ await expect(result).resolves.toBe(VIEW)
+ })
+})