:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): tell the agent to title the cells it adds (#75471)
Sinan Kucukkoseler095b07965e04
diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex 5063a15d8e37..d0283679427b 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -455,6 +455,11 @@ class AssistantContextManager(AssistantContextMixin):"- The user may ask you to change selected text, nearby content, or the entire notebook. ""Preserve unrelated content only when the request's scope is local."),+ (+ "- Component tags such as `<Query … />`, `<SQLV2 … />`, and `<PythonV2 … />` render a `title` "+ "prop in their block header. Keep the titles already there, and give any tag you add a short "+ "one saying what it shows, so a reader can skim the notebook without opening each block."+ ),("When the current user asks you to change broad notebook content, use notebook tools against ""the current notebook instead of explaining how the user could do it. "diff --git a/ee/hogai/context/test/test_context.py b/ee/hogai/context/test/test_context.pyindex 9c413da3a68f..da079f72b5b2 100644--- a/ee/hogai/context/test/test_context.py+++ b/ee/hogai/context/test/test_context.py@@ -368,6 +368,7 @@ class TestAssistantContextManager(BaseTest):self.assertIn("use create_notebook with content containing the complete final notebook markdown", result)self.assertIn("Full-notebook replacement content must omit", result)self.assertIn("single ph-markdown-notebook node", result)+ self.assertIn("render a `title` prop in their block header", result)mock_from_short_id.assert_not_called()@patch("ee.hogai.context.notebook.context.NotebookContext.from_short_id")diff --git a/ee/hogai/tools/create_notebook/tool.py b/ee/hogai/tools/create_notebook/tool.pyindex 2287680bb6a5..ec8b7c18237c 100644--- a/ee/hogai/tools/create_notebook/tool.py+++ b/ee/hogai/tools/create_notebook/tool.py@@ -78,6 +78,7 @@ Our signup funnel shows the following conversion rates:- In that case, `content` must be the complete final markdown for the notebook, not just the text that replaces the inline prompt- Do not include the inline placeholder text, empty `<Prompt question="" />` blocks, or the user's instruction prompt in the final markdown unless the user explicitly asks to keep them- Use a direct assistant markdown response instead of this tool only for local answers or small insertions that should replace the inline response placeholder+- Component tags such as `<Query … />`, `<SQLV2 … />`, and `<PythonV2 … />` render a `title` prop in their block header. Keep the titles already there, and give any tag you add a short one saying what it shows, so a reader can skim the notebook without opening each block# Transient vs saved notebooks:- By default, notebooks are created as transient artifacts visible only in this conversation. Do NOT share URLs or references to notebook pages for transient artifacts.diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yamlindex f643ad143361..0b55d14adbad 100644--- a/products/notebooks/mcp/tools.yaml+++ b/products/notebooks/mcp/tools.yaml@@ -67,7 +67,8 @@ tools:"InsightVizNode", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery |LifecycleQuery>}` for product-analytics insights; or (c) `{kind: "SavedInsightNode", shortId: "..."}` toembed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode`- wrapping a SQL chart.+ wrapping a SQL chart. Give every embedded node a short `attrs.title` saying what it shows — it renders in+ the node's header and is what a reader skims instead of the query.exclude_params:- _create_in_folderfeature_flag: revamped-py-notebooksdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c30b4436a6dc..72ccfd5eebe0 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6267,7 +6267,7 @@"feature_flag": "revamped-py-notebooks"},"notebooks-create": {- "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart.",+ "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart. Give every embedded node a short `attrs.title` saying what it shows — it renders in the node's header and is what a reader skims instead of the query.","category": "Notebooks","feature": "notebooks","summary": "Create notebook",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 3fe5e8008c76..1c1ebd32d64f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6718,7 +6718,7 @@}},"notebooks-add-cell": {- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist.",+ "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.","category": "Notebooks","feature": "notebooks","summary": "Add a cell to a notebook; SQL/Python cells run immediately.",@@ -6748,7 +6748,7 @@"feature_flag": "revamped-py-notebooks"},"notebooks-create": {- "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart.",+ "description": "Create a new notebook. Provide a title and content. Content is a JSON object representing the notebook's rich text document structure (ProseMirror-based). Returns the created notebook with its short_id.\nEmbedded charts use `{type: \"ph-query\", attrs: {nodeId, query}}` nodes. The `query` object must be one of: (a) `{kind: \"DataVisualizationNode\", source: {kind: \"HogQLQuery\", query: \"SELECT ...\"}, display: \"ActionsBar\", chartSettings: {...}}` for SQL charts — do NOT wrap this in an InsightVizNode; (b) `{kind: \"InsightVizNode\", source: <TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery>}` for product-analytics insights; or (c) `{kind: \"SavedInsightNode\", shortId: \"...\"}` to embed a saved insight. The server rejects other shapes and auto-corrects the common `InsightVizNode` wrapping a SQL chart. Give every embedded node a short `attrs.title` saying what it shows — it renders in the node's header and is what a reader skims instead of the query.","category": "Notebooks","feature": "notebooks","summary": "Create notebook",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 203dffe746e0..f3ef60105111 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -340,7 +340,7 @@}},"notebooks-add-cell": {- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist.",+ "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.","category": "Notebooks","feature": "notebooks","summary": "Add a cell to a notebook; SQL/Python cells run immediately.",diff --git a/services/mcp/src/tools/notebooks/addCell.ts b/services/mcp/src/tools/notebooks/addCell.tsindex 6b386dfa70d3..5416d00dcbfc 100644--- a/services/mcp/src/tools/notebooks/addCell.ts+++ b/services/mcp/src/tools/notebooks/addCell.ts@@ -25,6 +25,9 @@ import {} from './cellTags'import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor } from './markdownDoc'+/** The cell header renders a title on a single ellipsized line, so anything longer is cut off anyway. */+const CELL_TITLE_MAX_LENGTH = 120+export const NotebooksAddCellSchema = z.object({notebook_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),@@ -59,6 +62,13 @@ export const NotebooksAddCellSchema = z.describe('Name other cells use to reference this cell\'s result dataframe (e.g. in SQL joins or Python code). Auto-assigned ("sql_df", "df", …) when omitted for sql/python cells.'),+ title: z+ .string()+ .max(CELL_TITLE_MAX_LENGTH)+ .optional()+ .describe(+ 'Short label shown in the cell header, e.g. "Weekly signups by source". Set it on every cell you add so a reader can skim the notebook without reading the code — say what the cell shows, not that it is SQL or Python. Not accepted for markdown cells; give those a markdown heading instead.'+ ),after_node_id: z.string().optional()@@ -180,7 +190,14 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu}}+ const title = params.title?.trim() || undefined+if (params.cell_type === 'markdown') {+ if (title) {+ throw new Error(+ 'A markdown cell has no header to title — put the heading in the markdown itself (e.g. "## Weekly signups").'+ )+ }await applyMarkdownEdit(context, params.notebook_id, (markdown) =>insertBlock(markdown, params.markdown!.trim(), params.after_node_id))@@ -192,6 +209,7 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResuif (params.cell_type === 'saved_insight') {const tag = buildCellTag('Query', {nodeId,+ title,query: { kind: 'SavedInsightNode', shortId: params.insight_short_id },hideFilters: true,})@@ -202,7 +220,8 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu}if (params.cell_type === 'component') {- const tag = buildCellTag(params.tag_name!, { ...params.props, nodeId })+ // `title` last only when set, so a component that carries its own title prop keeps it.+ const tag = buildCellTag(params.tag_name!, { ...params.props, nodeId, ...(title ? { title } : {}) })await applyMarkdownEdit(context, params.notebook_id, (markdown) =>insertBlock(markdown, tag, params.after_node_id))@@ -214,7 +233,7 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResuconst dataframeName =params.dataframe_name ??uniqueDataframeName(params.cell_type === 'sql' ? 'sql_df' : 'df', parseCellTags(initial.markdown))- const tag = buildCellTag(tagName, { nodeId, code: params.code, returnVariable: dataframeName })+ const tag = buildCellTag(tagName, { nodeId, title, code: params.code, returnVariable: dataframeName })const { markdown } = await applyMarkdownEdit(context, params.notebook_id, (current) =>insertBlock(current, tag, params.after_node_id)diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.tsindex 7d42083347b1..e1e08799c071 100644--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts@@ -6,6 +6,8 @@ import { deleteCellHandler } from '@/tools/notebooks/deleteCell'import { updateCellHandler } from '@/tools/notebooks/updateCell'import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type Context } from '@/tools/types'+type AddCellParams = Parameters<typeof addCellHandler>[1]+interface MockState {markdown: stringversion: number@@ -201,6 +203,57 @@ describe('notebook cell tools', () => {expect(state.runBodies).toHaveLength(0)})+ // The header title is what a reader skims instead of the code, so every tag-backed cell type+ // has to carry it through to the markdown.+ it.each([+ ['sql', { cell_type: 'sql', code: 'select 1' }, 'SQLV2'],+ ['python', { cell_type: 'python', code: 'x = 1' }, 'PythonV2'],+ ['saved_insight', { cell_type: 'saved_insight', insight_short_id: 'iNs12345' }, 'Query'],+ ['component', { cell_type: 'component', tag_name: 'Image', props: { src: 'https://ph.com/a.png' } }, 'Image'],+ ] satisfies [string, Omit<AddCellParams, 'notebook_id' | 'title'>, string][])(+ 'add %s cell writes the title onto the tag',+ async (_label, params, tagName) => {+ const state = makeState('# Doc\n')+ state.runStatusResponses.push(DONE_STATUS)+ const context = createMockContext(state)++ await addCellHandler(context, { ...params, notebook_id: 'aBcD1234', title: 'Weekly signups by source' })++ const inserted = state.saveBodies[0].content.content[0].attrs.markdown+ expect(inserted).toContain(`<${tagName} `)+ expect(inserted).toContain('title="Weekly signups by source"')+ }+ )++ it('markdown cell rejects a title, pointing at a markdown heading instead', async () => {+ const state = makeState('# Doc\n')+ const context = createMockContext(state)++ await expect(+ addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'markdown',+ markdown: 'Some notes.',+ title: 'Notes',+ })+ ).rejects.toThrow(/heading in the markdown/)+ expect(state.saveBodies).toHaveLength(0)+ })++ it('component cell keeps a title carried in its own props', async () => {+ const state = makeState('# Doc\n')+ const context = createMockContext(state)++ await addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'component',+ tag_name: 'Image',+ props: { src: 'https://ph.com/a.png', title: 'From props' },+ })++ expect(state.saveBodies[0].content.content[0].attrs.markdown).toContain('title="From props"')+ })+it('component cell rejects executable tags', async () => {const state = makeState('# Doc\n')const context = createMockContext(state)