:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): let annotation tools target an insight or dashboard (#108363)
posthog[bot]8fbc5f5ec759
diff --git a/products/annotations/backend/api/annotation.py b/products/annotations/backend/api/annotation.pyindex a6f6f33b2ea5..8468f1128e70 100644--- a/products/annotations/backend/api/annotation.py+++ b/products/annotations/backend/api/annotation.py@@ -146,6 +146,29 @@ class AnnotationSerializer(serializers.ModelSerializer):else:insight = getattr(self.instance, "dashboard_item", None)+ # A create checks only an explicit scope, because rows created without one take the model+ # default and have no insight. An update checks the scope the row will have, so clearing the+ # parent is caught too. A row already stored without its parent, such as a default row or one+ # whose dashboard was hard-deleted, stays editable, because the UI echoes its scope back.+ instance = self.instance+ checked_scope = scope if instance is None else scope or instance.scope+ if (+ checked_scope == Annotation.Scope.INSIGHT.value+ and insight is None+ and not (instance is not None and instance.scope == checked_scope and instance.dashboard_item_id is None)+ ):+ raise serializers.ValidationError(+ {"dashboard_item": "Set `dashboard_item` to the insight ID when the scope is `dashboard_item`."}+ )+ if (+ checked_scope == Annotation.Scope.DASHBOARD.value+ and dashboard is None+ and not (instance is not None and instance.scope == checked_scope and instance.dashboard_id is None)+ ):+ raise serializers.ValidationError(+ {"dashboard_id": "Set `dashboard_id` to the dashboard ID when the scope is `dashboard`."}+ )+# AnnotationsViewSet.safely_get_queryset hides an annotation whose own scope points at a# soft-deleted parent, so accepting one here would strand a row that nothing can list, edit# or delete. Project- and organization-scoped rows keep their pointers, which are only useddiff --git a/products/annotations/backend/api/test/test_annotation.py b/products/annotations/backend/api/test/test_annotation.pyindex ba5b2d6e7e6c..8c1b9f10c7ba 100644--- a/products/annotations/backend/api/test/test_annotation.py+++ b/products/annotations/backend/api/test/test_annotation.py@@ -610,6 +610,64 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json() == self.validation_error_response("Dashboard not found.", attr="dashboard_id")+ @parameterized.expand(+ [+ ("create_insight_scope", None, {"scope": "dashboard_item"}, "dashboard_item"),+ ("create_dashboard_scope", None, {"scope": "dashboard"}, "dashboard_id"),+ ("patch_to_insight_scope", "project", {"scope": "dashboard_item"}, "dashboard_item"),+ ("patch_to_dashboard_scope", "project", {"scope": "dashboard"}, "dashboard_id"),+ ("patch_clears_insight", "insight", {"scope": "dashboard_item", "dashboard_item": None}, "dashboard_item"),+ ("patch_keeps_stored_insight", "insight", {"scope": "dashboard_item"}, None),+ ("patch_keeps_stored_dashboard", "dashboard", {"scope": "dashboard"}, None),+ ("patch_without_scope_on_default_row", "none", {"content": "edited"}, None),+ ("patch_clears_dashboard_without_scope", "dashboard", {"dashboard_id": None}, "dashboard_id"),+ ("patch_clears_insight_without_scope", "insight", {"dashboard_item": None}, "dashboard_item"),+ (+ "ui_edit_of_default_row",+ "none",+ {"content": "edited", "scope": "dashboard_item", "dashboard_item": None, "dashboard_id": None},+ None,+ ),+ (+ "ui_edit_of_detached_dashboard_row",+ "detached_dashboard",+ {"content": "edited", "scope": "dashboard", "dashboard_item": None, "dashboard_id": None},+ None,+ ),+ ]+ )+ def test_insight_and_dashboard_scopes_require_the_matching_id(+ self, _name: str, existing_parent: str | None, payload: dict[str, Any], error_attr: str | None+ ) -> None:+ if existing_parent is None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/annotations/",+ {"content": "Scoped annotation", "date_marker": "2024-01-01T00:00:00.000000Z", **payload},+ )+ else:+ annotation = Annotation.objects.create(+ organization=self.organization,+ team=self.team,+ created_by=self.user,+ content="Original annotation",+ scope={+ "dashboard": Annotation.Scope.DASHBOARD,+ "detached_dashboard": Annotation.Scope.DASHBOARD,+ "project": Annotation.Scope.PROJECT,+ }.get(existing_parent, Annotation.Scope.INSIGHT),+ dashboard_item=Insight.objects.create(team=self.team) if existing_parent == "insight" else None,+ dashboard=Dashboard.objects.create(team=self.team) if existing_parent == "dashboard" else None,+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/annotations/{annotation.id}/", payload, format="json"+ )++ if error_attr is None:+ assert response.status_code == status.HTTP_200_OK, response.json()+ else:+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == error_attr+def test_creating_annotation_with_insight_from_different_team_returns_400(self) -> None:other_team = Team.objects.create(organization=self.organization, name="Other Team")other_insight = Insight.objects.create(team=other_team, name="Other Insight")diff --git a/products/annotations/frontend/logics/annotationModalLogic.test.ts b/products/annotations/frontend/logics/annotationModalLogic.test.tsnew file mode 100644index 000000000000..2059b6afe362--- /dev/null+++ b/products/annotations/frontend/logics/annotationModalLogic.test.ts@@ -0,0 +1,89 @@+import { expectLogic } from 'kea-test-utils'++import { dayjs } from 'lib/dayjs'++import { initKeaTests } from '~/test/init'+import { AnnotationScope, AnnotationType } from '~/types'++import * as generatedApi from '../generated/api'+import type { AnnotationApi } from '../generated/api.schemas'+import { annotationModalLogic } from './annotationModalLogic'++describe('annotationModalLogic', () => {+ let updateSpy: jest.SpyInstance++ beforeEach(() => {+ initKeaTests()+ updateSpy = jest.spyOn(generatedApi, 'annotationsPartialUpdate').mockResolvedValue({ id: 1 } as AnnotationApi)+ })++ afterEach(() => {+ updateSpy.mockRestore()+ })++ it.each([+ {+ name: 'omits the stored insight when edited off an insight',+ stored: { scope: AnnotationScope.Organization, dashboard_item: 99 },+ insightId: null,+ dashboardId: null,+ newScope: null,+ expected: { scope: AnnotationScope.Organization, dashboard_id: null },+ absent: ['dashboard_item'],+ },+ {+ name: 'moves the annotation to the insight it is edited from',+ stored: { scope: AnnotationScope.Project, dashboard_item: 99 },+ insightId: 7,+ dashboardId: null,+ newScope: AnnotationScope.Insight,+ expected: { scope: AnnotationScope.Insight, dashboard_item: 7 },+ absent: [],+ },+ {+ name: 'takes the open dashboard when a row without one moves to dashboard scope',+ stored: { scope: AnnotationScope.Project, dashboard_id: null },+ insightId: 7,+ dashboardId: 5,+ newScope: AnnotationScope.Dashboard,+ expected: { scope: AnnotationScope.Dashboard, dashboard_id: 5 },+ absent: [],+ },+ {+ name: 'keeps a project row off the dashboard it is edited from',+ stored: { scope: AnnotationScope.Project, dashboard_id: null },+ insightId: 7,+ dashboardId: 5,+ newScope: null,+ expected: { scope: AnnotationScope.Project, dashboard_id: null },+ absent: [],+ },+ ])('$name', async ({ stored, insightId, dashboardId, newScope, expected, absent }) => {+ const annotation: AnnotationType = {+ id: 1,+ content: 'Release',+ date_marker: dayjs('2024-01-01T00:00:00Z'),+ created_at: dayjs('2024-01-01T00:00:00Z'),+ updated_at: '2024-01-01T00:00:00Z',+ dashboard_item: null,+ dashboard_id: null,+ ...stored,+ }+ const logic = annotationModalLogic()+ logic.mount()++ logic.actions.openModalToEditAnnotation(annotation, insightId, dashboardId)+ if (newScope) {+ logic.actions.setAnnotationModalValue('scope', newScope)+ }+ logic.actions.submitAnnotationModal()+ await expectLogic(logic).toFinishAllListeners()++ expect(updateSpy).toHaveBeenCalledTimes(1)+ const body = updateSpy.mock.calls[0][2]+ expect(body).toMatchObject(expected)+ for (const key of absent) {+ expect(body).not.toHaveProperty(key)+ }+ })+})diff --git a/products/annotations/frontend/logics/annotationModalLogic.ts b/products/annotations/frontend/logics/annotationModalLogic.tsindex 3c8da3c56d34..dab1d022714b 100644--- a/products/annotations/frontend/logics/annotationModalLogic.ts+++ b/products/annotations/frontend/logics/annotationModalLogic.ts@@ -5,7 +5,7 @@ import { urlToAction } from 'kea-router'import '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { Dayjs, dayjs } from 'lib/dayjs'import { teamLogic } from 'scenes/teamLogic'@@ -17,6 +17,7 @@ import { AnnotationScope, AnnotationType, DashboardBasicType, InsightModel } froimport type { UserType } from '../../../../frontend/src/types'import type { RawAnnotationType } from '../../../../frontend/src/types'+import { annotationsPartialUpdate } from '../generated/api'export const ANNOTATION_DAYJS_FORMAT = 'MMMM DD, YYYY h:mm A'@@ -281,17 +282,25 @@ export const annotationModalLogic = kea<annotationModalLogicType>([if (values.existingModalAnnotation) {// annotationsModel's updateAnnotation inlined so that isAnnotationModalSubmitting works- const updatedAnnotation = await api.annotations.update(values.existingModalAnnotation.id, {- date_marker: dateMarker.toISOString(),- content,- emoji: emoji || null,- scope,- // update to new insight we're saving from- dashboard_item: dashboardItemId,- // preserve existing dashboard id- dashboard_id: values.existingModalAnnotation.dashboard_id,- })- actions.replaceAnnotation(updatedAnnotation)+ const updatedAnnotation = await annotationsPartialUpdate(+ String(ApiConfig.getCurrentProjectId()),+ values.existingModalAnnotation.id,+ {+ date_marker: dateMarker.toISOString(),+ content,+ emoji: emoji || null,+ scope,+ // Off an insight, omit the field so the PATCH keeps the stored insight. An organization-scoped+ // row can point at another team's insight, which fails the team-scoped lookup if sent back.+ ...(dashboardItemId ? { dashboard_item: dashboardItemId } : {}),+ // A row without a dashboard that moves to dashboard scope takes the one it was opened on,+ // because the API rejects that scope without an id.+ dashboard_id:+ values.existingModalAnnotation.dashboard_id ??+ (scope === AnnotationScope.Dashboard ? dashboardId : null),+ }+ )+ actions.replaceAnnotation(updatedAnnotation as unknown as RawAnnotationType)} else {// annotationsModel's createAnnotationGenerically inlined so that isAnnotationModalSubmitting worksconst createdAnnotation = await api.annotations.create({diff --git a/products/annotations/mcp/tools.yaml b/products/annotations/mcp/tools.yamlindex 464b2613530e..f6b3f871b2fa 100644--- a/products/annotations/mcp/tools.yaml+++ b/products/annotations/mcp/tools.yaml@@ -19,13 +19,17 @@ tools:title: Create annotationdescription: >Create an annotation to mark an important change (for example, a deployment) on charts and trends. Provide a- note in `content`, when it happened in `date_marker` (ISO 8601), and whether it is scoped to the current- `project` or the whole `organization`. Optionally set an `emoji` to show in place of the default badge on- the chart.+ note in `content`, when it happened in `date_marker` (ISO 8601), and its `scope`: the current `project`, the+ whole `organization`, one insight, or one dashboard. To annotate one insight, set `scope` to+ `dashboard_item` and `dashboard_item` to the insight's numeric ID. To annotate one dashboard, set `scope` to+ `dashboard` and `dashboard_id` to the dashboard ID. Optionally set an `emoji` to show in place of the+ default badge on the chart.include_params:- content- date_marker- scope+ - dashboard_item+ - dashboard_id- emoji- hidden_in_user_interfaceannotation-delete:@@ -99,12 +103,15 @@ tools:title: Update annotationdescription: >Update an existing annotation by ID. You can change its text (`content`), when it happened (`date_marker`,- ISO 8601), its visibility scope (`project` or `organization`), or its `emoji`. Only the fields you provide- are updated.+ ISO 8601), its visibility scope, or its `emoji`. To scope it to one insight, set `scope` to `dashboard_item`+ and `dashboard_item` to the insight's numeric ID. To scope it to one dashboard, set `scope` to `dashboard`+ and `dashboard_id` to the dashboard ID. Only the fields you provide are updated.include_params:- content- date_marker- scope+ - dashboard_item+ - dashboard_id- emoji- hidden_in_user_interfacechange-feed-list:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 0d7afc9acaba..16faa09a81c0 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -752,7 +752,7 @@}},"annotation-create": {- "description": "Create an annotation to mark an important change (for example, a deployment) on charts and trends. Provide a note in `content`, when it happened in `date_marker` (ISO 8601), and whether it is scoped to the current `project` or the whole `organization`. Optionally set an `emoji` to show in place of the default badge on the chart.",+ "description": "Create an annotation to mark an important change (for example, a deployment) on charts and trends. Provide a note in `content`, when it happened in `date_marker` (ISO 8601), and its `scope`: the current `project`, the whole `organization`, one insight, or one dashboard. To annotate one insight, set `scope` to `dashboard_item` and `dashboard_item` to the insight's numeric ID. To annotate one dashboard, set `scope` to `dashboard` and `dashboard_id` to the dashboard ID. Optionally set an `emoji` to show in place of the default badge on the chart.","category": "Annotations","feature": "annotations","summary": "Create annotation",@@ -808,7 +808,7 @@}},"annotations-partial-update": {- "description": "Update an existing annotation by ID. You can change its text (`content`), when it happened (`date_marker`, ISO 8601), its visibility scope (`project` or `organization`), or its `emoji`. Only the fields you provide are updated.",+ "description": "Update an existing annotation by ID. You can change its text (`content`), when it happened (`date_marker`, ISO 8601), its visibility scope, or its `emoji`. To scope it to one insight, set `scope` to `dashboard_item` and `dashboard_item` to the insight's numeric ID. To scope it to one dashboard, set `scope` to `dashboard` and `dashboard_id` to the dashboard ID. Only the fields you provide are updated.","category": "Annotations","feature": "annotations","summary": "Update annotation",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex ecf4d72a2498..d920b12fe438 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -767,7 +767,7 @@}},"annotation-create": {- "description": "Create an annotation to mark an important change (for example, a deployment) on charts and trends. Provide a note in `content`, when it happened in `date_marker` (ISO 8601), and whether it is scoped to the current `project` or the whole `organization`. Optionally set an `emoji` to show in place of the default badge on the chart.",+ "description": "Create an annotation to mark an important change (for example, a deployment) on charts and trends. Provide a note in `content`, when it happened in `date_marker` (ISO 8601), and its `scope`: the current `project`, the whole `organization`, one insight, or one dashboard. To annotate one insight, set `scope` to `dashboard_item` and `dashboard_item` to the insight's numeric ID. To annotate one dashboard, set `scope` to `dashboard` and `dashboard_id` to the dashboard ID. Optionally set an `emoji` to show in place of the default badge on the chart.","category": "Annotations","feature": "annotations","summary": "Create annotation",@@ -823,7 +823,7 @@}},"annotations-partial-update": {- "description": "Update an existing annotation by ID. You can change its text (`content`), when it happened (`date_marker`, ISO 8601), its visibility scope (`project` or `organization`), or its `emoji`. Only the fields you provide are updated.",+ "description": "Update an existing annotation by ID. You can change its text (`content`), when it happened (`date_marker`, ISO 8601), its visibility scope, or its `emoji`. To scope it to one insight, set `scope` to `dashboard_item` and `dashboard_item` to the insight's numeric ID. To scope it to one dashboard, set `scope` to `dashboard` and `dashboard_id` to the dashboard ID. Only the fields you provide are updated.","category": "Annotations","feature": "annotations","summary": "Update annotation",diff --git a/services/mcp/src/tools/generated/annotations.ts b/services/mcp/src/tools/generated/annotations.tsindex 664b5bf82b2e..46e9512c1fcc 100644--- a/services/mcp/src/tools/generated/annotations.ts+++ b/services/mcp/src/tools/generated/annotations.ts@@ -9,7 +9,7 @@ import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'const AnnotationCreateSchema = () => {const AnnotationsCreateBody = orvalSchemas.AnnotationsCreateBody()- return AnnotationsCreateBody.omit({ creation_type: true, dashboard_item: true, dashboard_id: true, deleted: true })+ return AnnotationsCreateBody.omit({ creation_type: true, deleted: true })}const annotationCreate = (): ToolBase<ReturnType<typeof AnnotationCreateSchema>, Schemas.Annotation> => ({@@ -24,6 +24,12 @@ const annotationCreate = (): ToolBase<ReturnType<typeof AnnotationCreateSchema>,if (params.date_marker !== undefined) {body['date_marker'] = params.date_marker}+ if (params.dashboard_item !== undefined) {+ body['dashboard_item'] = params.dashboard_item+ }+ if (params.dashboard_id !== undefined) {+ body['dashboard_id'] = params.dashboard_id+ }if (params.scope !== undefined) {body['scope'] = params.scope}@@ -130,12 +136,7 @@ const AnnotationsPartialUpdateSchema = () => {const AnnotationsPartialUpdateBody = orvalSchemas.AnnotationsPartialUpdateBody()const AnnotationsPartialUpdateParams = orvalSchemas.AnnotationsPartialUpdateParams()return AnnotationsPartialUpdateParams.omit({ project_id: true }).extend(- AnnotationsPartialUpdateBody.omit({- creation_type: true,- dashboard_item: true,- dashboard_id: true,- deleted: true,- }).shape+ AnnotationsPartialUpdateBody.omit({ creation_type: true, deleted: true }).shape)}@@ -154,6 +155,12 @@ const annotationsPartialUpdate = (): ToolBase<if (params.date_marker !== undefined) {body['date_marker'] = params.date_marker}+ if (params.dashboard_item !== undefined) {+ body['dashboard_item'] = params.dashboard_item+ }+ if (params.dashboard_id !== undefined) {+ body['dashboard_id'] = params.dashboard_id+ }if (params.scope !== undefined) {body['scope'] = params.scope}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/annotation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/annotation-create.jsonindex ceef95f07dbc..11d41d3c3b1f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/annotation-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/annotation-create.json@@ -13,6 +13,28 @@],"description": "Annotation text shown on charts to describe the change, release, or incident."},+ "dashboard_id": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional dashboard ID to attach this annotation to. Must belong to the current project."+ },+ "dashboard_item": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional insight ID to attach this annotation to. Must belong to the current project."+ },"date_marker": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/annotations-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/annotations-partial-update.jsonindex 5babd181fcc5..b828d9432188 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/annotations-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/annotations-partial-update.json@@ -13,6 +13,28 @@],"description": "Annotation text shown on charts to describe the change, release, or incident."},+ "dashboard_id": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional dashboard ID to attach this annotation to. Must belong to the current project."+ },+ "dashboard_item": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional insight ID to attach this annotation to. Must belong to the current project."+ },"date_marker": {"anyOf": [{