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(notebooks): capture programmatic notebook read event (#68467)

Sinan Kucukkoseler0ea9b82874a4
diff --git a/products/notebooks/backend/analytics.py b/products/notebooks/backend/analytics.py
index 9a3eabbe8999..d4827c72ee2b 100644
--- a/products/notebooks/backend/analytics.py
+++ b/products/notebooks/backend/analytics.py
@@ -1,8 +1,8 @@
"""Analytics capture for notebook lifecycle events.
-Single owner of the server-side `notebook created` event so every creation path — REST/MCP
-(via the serializer) and the AI/background paths (via the facade create functions) — emits one
-uniform event with an attributed `creation_source`.
+Single owner of the server-side `notebook created` and `notebook read` events, so every
+creation path (REST/MCP via the serializer, AI/background via the facade create functions) and
+every programmatic read emits one uniform, attributed event.
"""
from typing import TYPE_CHECKING, Any
@@ -14,6 +14,7 @@ if TYPE_CHECKING:
from rest_framework.request import Request
NOTEBOOK_CREATED_EVENT = "notebook created"
+NOTEBOOK_READ_EVENT = "notebook read"
class NotebookCreationSource:
@@ -35,10 +36,9 @@ def notebook_node_count(content: Any) -> int | None:
return None
-def _created_properties(short_id: str, creation_source: str, extra: dict[str, Any]) -> dict[str, Any]:
- props: dict[str, Any] = {"short_id": short_id, "creation_source": creation_source}
- props.update({key: value for key, value in extra.items() if value is not None})
- return props
+def _optional_props(**props: Any) -> dict[str, Any]:
+ """Keep only the props whose value is not None, so optional event fields don't clutter the payload."""
+ return {key: value for key, value in props.items() if value is not None}
def capture_notebook_created(
@@ -61,19 +61,19 @@ def capture_notebook_created(
the facade create functions pass ``team_id`` + ``created_by_id`` for the request-less
AI/background paths, where attribution falls back to the team when there is no user
(e.g. group auto-create)."""
- props = _created_properties(
- short_id,
- creation_source,
- {
- "mcp_consumer": mcp_consumer,
- "mcp_oauth_client": mcp_oauth_client,
- "api_key_type": api_key_type,
- "conversation_id": conversation_id,
- "topic": topic,
- "visibility": visibility,
- "node_count": node_count,
- },
- )
+ props = {
+ "short_id": short_id,
+ "creation_source": creation_source,
+ **_optional_props(
+ mcp_consumer=mcp_consumer,
+ mcp_oauth_client=mcp_oauth_client,
+ api_key_type=api_key_type,
+ conversation_id=conversation_id,
+ topic=topic,
+ visibility=visibility,
+ node_count=node_count,
+ ),
+ }
if request is not None and user is not None:
report_user_action(user, NOTEBOOK_CREATED_EVENT, props, request=request)
@@ -86,3 +86,32 @@ def capture_notebook_created(
if team is None:
return
report_user_or_team_action(NOTEBOOK_CREATED_EVENT, props, user=resolved_user, team=team)
+
+
+def capture_notebook_read(
+ *,
+ request: "Request",
+ user: Any,
+ short_id: str,
+ read_source: str,
+ is_creator: bool,
+ user_access_level: str | None = None,
+ mcp_consumer: str | None = None,
+ mcp_oauth_client: str | None = None,
+ api_key_type: str | None = None,
+) -> None:
+ """Emit `notebook read` for a programmatic (non-browser) notebook retrieve. Browser opens are
+ the client-side `notebook opened` event, so the caller gates this on non-session auth to keep
+ agent traffic out of the human revisit numbers."""
+ props = {
+ "short_id": short_id,
+ "read_source": read_source,
+ "is_creator": is_creator,
+ **_optional_props(
+ user_access_level=user_access_level,
+ mcp_consumer=mcp_consumer,
+ mcp_oauth_client=mcp_oauth_client,
+ api_key_type=api_key_type,
+ ),
+ }
+ report_user_action(user, NOTEBOOK_READ_EVENT, props, request=request)
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 3813048246ca..15cefe7530a0 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -49,7 +49,12 @@ from posthog.utils import relative_date_parse
from products.notebooks.backend import collab_stream, markdown_collab, presence
from products.notebooks.backend.activity_logging import log_notebook_activity
-from products.notebooks.backend.analytics import NotebookCreationSource, capture_notebook_created, notebook_node_count
+from products.notebooks.backend.analytics import (
+ NotebookCreationSource,
+ capture_notebook_created,
+ capture_notebook_read,
+ notebook_node_count,
+)
from products.notebooks.backend.collab import submit_steps
from products.notebooks.backend.kernel_runtime import build_notebook_sandbox_config, get_kernel_runtime
from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun
@@ -700,6 +705,22 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
if str(request.headers.get("If-None-Match")) == str(instance.version):
return Response(None, 304)
+ read_source, source_props = classify_request_source(request)
+ if read_source != NotebookCreationSource.UI:
+ # Browser opens are the client-side `notebook opened` event; only count programmatic
+ # (MCP / API) reads here so agent traffic doesn't inflate the human revisit numbers.
+ capture_notebook_read(
+ request=request,
+ user=request.user,
+ short_id=instance.short_id,
+ read_source=read_source,
+ is_creator=instance.created_by_id == getattr(request.user, "id", None),
+ user_access_level=serializer.data.get("user_access_level"),
+ mcp_consumer=source_props.get("mcp_consumer"),
+ mcp_oauth_client=source_props.get("mcp_oauth_client"),
+ api_key_type=source_props.get("api_key_type"),
+ )
+
return Response(serializer.data)
@action(methods=["POST"], url_path="kernel/start", detail=True)
diff --git a/products/notebooks/backend/test/test_analytics.py b/products/notebooks/backend/test/test_analytics.py
index 338644ec2c93..27d2b7ade50f 100644
--- a/products/notebooks/backend/test/test_analytics.py
+++ b/products/notebooks/backend/test/test_analytics.py
@@ -10,8 +10,10 @@ from posthog.auth import SessionAuthentication
from products.notebooks.backend.analytics import (
NOTEBOOK_CREATED_EVENT,
+ NOTEBOOK_READ_EVENT,
NotebookCreationSource,
capture_notebook_created,
+ capture_notebook_read,
notebook_node_count,
)
from products.notebooks.backend.presentation.views.notebook import classify_request_source
@@ -92,3 +94,32 @@ class TestNotebookAnalytics(BaseTest):
args[2],
{"short_id": "abc123", "creation_source": "ui", "visibility": "private", "node_count": 3},
)
+
+ @patch("products.notebooks.backend.analytics.report_user_action")
+ def test_capture_notebook_read_builds_props_and_drops_none(self, mock_report):
+ capture_notebook_read(
+ request=_fake_request(SessionAuthentication()),
+ user=self.user,
+ short_id="abc123",
+ read_source=NotebookCreationSource.MCP,
+ is_creator=False,
+ user_access_level="viewer",
+ api_key_type="PersonalAPIKeyAuthentication",
+ mcp_consumer="posthog-code",
+ )
+ self.assertEqual(mock_report.call_count, 1)
+ args, _ = mock_report.call_args
+ self.assertEqual(args[0], self.user)
+ self.assertEqual(args[1], NOTEBOOK_READ_EVENT)
+ # mcp_consumer flows through; mcp_oauth_client is unset and so dropped.
+ self.assertEqual(
+ args[2],
+ {
+ "short_id": "abc123",
+ "read_source": "mcp",
+ "is_creator": False,
+ "user_access_level": "viewer",
+ "api_key_type": "PersonalAPIKeyAuthentication",
+ "mcp_consumer": "posthog-code",
+ },
+ )
diff --git a/products/notebooks/backend/test/test_notebook_read_event.py b/products/notebooks/backend/test/test_notebook_read_event.py
new file mode 100644
index 000000000000..213a967cdaf2
--- /dev/null
+++ b/products/notebooks/backend/test/test_notebook_read_event.py
@@ -0,0 +1,48 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+CAPTURE_PATH = "products.notebooks.backend.presentation.views.notebook.capture_notebook_read"
+
+
+class TestNotebookReadEvent(APIBaseTest):
+ def _create_notebook(self) -> str:
+ response = self.client.post(f"/api/projects/{self.team.id}/notebooks/", data={}, format="json")
+ assert response.status_code == status.HTTP_201_CREATED
+ return response.json()["short_id"]
+
+ def _url(self, short_id: str) -> str:
+ return f"/api/projects/{self.team.id}/notebooks/{short_id}/"
+
+ @patch(CAPTURE_PATH)
+ def test_browser_session_read_does_not_emit(self, mock_capture):
+ short_id = self._create_notebook()
+ response = self.client.get(self._url(short_id))
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ # Browser reads are the client-side `notebook opened` event — emitting here would double-count.
+ mock_capture.assert_not_called()
+
+ @patch(CAPTURE_PATH)
+ def test_personal_api_key_read_emits_programmatic_event(self, mock_capture):
+ short_id = self._create_notebook()
+
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="read-key",
+ secure_value=hash_key_value(key_value),
+ scopes=["notebook:read"],
+ )
+ self.client.logout()
+
+ response = self.client.get(self._url(short_id), HTTP_AUTHORIZATION=f"Bearer {key_value}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_capture.assert_called_once()
+ kwargs = mock_capture.call_args.kwargs
+ self.assertEqual(kwargs["short_id"], short_id)
+ self.assertEqual(kwargs["read_source"], "mcp")
+ self.assertEqual(kwargs["api_key_type"], "PersonalAPIKeyAuthentication")