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.

fix(notebooks): offer only the revamped SQL cell behind revamped-py-notebooks (#74656)

Sinan Kucukkoselerbe5c8aae1e06
diff --git a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
index 59502fefb149..0f5f1f1aa84d 100644
--- a/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/InsertMenu.tsx
@@ -47,6 +47,21 @@ export function getInsertMenuOptionDomId(menuId: string, commandKey: string): st
return `${menuId}-option-${commandKey}`
}
+/** Exported so a caller whose registry supersedes the built-in SQL command can hide it by key
+ * without hard-coding the string, which would silently stop matching if the key were renamed. */
+export const QUERY_SQL_INSERT_COMMAND_KEY = 'query-sql'
+
+/** The menu's top group. Exported so a registry component can place its insert command here
+ * without hard-coding the label, which would split into a second group if this were renamed. */
+export const COMMON_INSERT_COMMAND_CATEGORY = 'Common'
+
+export function omitInsertCommands(commands: InsertCommand[], hiddenKeys: string[] | undefined): InsertCommand[] {
+ if (!hiddenKeys?.length) {
+ return commands
+ }
+ return commands.filter((command) => !hiddenKeys.includes(command.key))
+}
+
export function InsertMenu({
id,
query,
@@ -214,7 +229,7 @@ export function buildInsertCommands(
isAskAIDisabled?: boolean,
extraCommands: InsertCommand[] = []
): InsertCommand[] {
- const commonCategory = 'Common'
+ const commonCategory = COMMON_INSERT_COMMAND_CATEGORY
const insertComponent = (targetNodeId: string, tagName: string, props: NotebookComponentProps): void => {
const node: NotebookComponentBlockNode = {
@@ -391,7 +406,7 @@ export function buildInsertCommands(
const sqlCommands: InsertCommand[] = [
{
- key: 'query-sql',
+ key: QUERY_SQL_INSERT_COMMAND_KEY,
label: 'SQL',
category: commonCategory,
icon: <IconDatabase />,
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 2194f419bb63..5f7b4e99ddd3 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -165,6 +165,7 @@ import {
getInsertMenuOptionDomId,
getInsertMenuPosition,
getNextInsertMenuSelectedIndex,
+ omitInsertCommands,
} from './InsertMenu'
import {
deleteListItemSelectionRange,
@@ -244,6 +245,9 @@ export type MarkdownNotebookProps = {
/** Caller-supplied insert-menu commands. Receives an API for inserting blocks so the command's
* behavior (e.g. opening a picker modal) and labeling stay in the caller, not this component. */
extraInsertCommands?: (api: MarkdownNotebookInsertMenuApi) => InsertCommand[]
+ /** Built-in insert-menu commands to drop, by key (e.g. `QUERY_SQL_INSERT_COMMAND_KEY`). For a
+ * caller whose registry supplies its own block for the same job and must not offer both. */
+ hiddenInsertCommandKeys?: string[]
remoteValue?: string
/** Notebook version `remoteValue` corresponds to, for version-aware caret mapping. */
remoteVersion?: number
@@ -561,6 +565,7 @@ function MarkdownNotebookEditor({
mode = 'edit',
registry,
extraInsertCommands,
+ hiddenInsertCommandKeys,
remoteValue,
remoteVersion,
deferRemoteValue = false,
@@ -2845,27 +2850,30 @@ function MarkdownNotebookEditor({
const placeholderNodeId = hasNotebookContent(renderedNodes) ? null : renderedNodes[0]?.id
const insertCommands = useMemo(
() =>
- buildInsertCommands(
- mergedRegistry,
- replaceNodeWithInsertedComponent,
- replaceNode,
- (nodeId) => {
- restoreSelectionRef.current = { nodeId, start: 0, end: 0 }
- },
- (nodeId) => {
- restoreSelectionRef.current = {
- nodeId,
- tableCell: { section: 'header', rowIndex: 0, columnIndex: 0 },
- start: 0,
- end: 8,
- }
- },
- (nodeId) => {
- restoreSelectionRef.current = { nodeId, start: 0, end: 0 }
- },
- onAskAI ? openAIPrompt : undefined,
- false,
- extraInsertCommands ? extraInsertCommands(insertMenuApi) : []
+ omitInsertCommands(
+ buildInsertCommands(
+ mergedRegistry,
+ replaceNodeWithInsertedComponent,
+ replaceNode,
+ (nodeId) => {
+ restoreSelectionRef.current = { nodeId, start: 0, end: 0 }
+ },
+ (nodeId) => {
+ restoreSelectionRef.current = {
+ nodeId,
+ tableCell: { section: 'header', rowIndex: 0, columnIndex: 0 },
+ start: 0,
+ end: 8,
+ }
+ },
+ (nodeId) => {
+ restoreSelectionRef.current = { nodeId, start: 0, end: 0 }
+ },
+ onAskAI ? openAIPrompt : undefined,
+ false,
+ extraInsertCommands ? extraInsertCommands(insertMenuApi) : []
+ ),
+ hiddenInsertCommandKeys
),
[
mergedRegistry,
@@ -2874,6 +2882,7 @@ function MarkdownNotebookEditor({
onAskAI,
openAIPrompt,
extraInsertCommands,
+ hiddenInsertCommandKeys,
insertMenuApi,
]
)
diff --git a/frontend/src/lib/components/MarkdownNotebook/index.ts b/frontend/src/lib/components/MarkdownNotebook/index.ts
index 7df40406d73f..048ab0e5208c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/index.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/index.ts
@@ -1,6 +1,12 @@
export { MarkdownNotebook } from './MarkdownNotebook'
export type { MarkdownNotebookAskAIRequest, MarkdownNotebookProps } from './MarkdownNotebook'
export type { InsertCommand, MarkdownNotebookInsertMenuApi } from './editorTypes'
+export {
+ COMMON_INSERT_COMMAND_CATEGORY,
+ QUERY_SQL_INSERT_COMMAND_KEY,
+ buildInsertCommands,
+ omitInsertCommands,
+} from './InsertMenu'
export {
getMarkdownNotebookDefaultRegistry,
createMarkdownNotebookRegistry,
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
index 56afb88c7a4d..997677a913bf 100644
--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx
@@ -39,7 +39,10 @@ import {
} from './MarkdownNotebookEntityListPicker'
import { MarkdownNotebookExperimentPicker } from './MarkdownNotebookExperimentPicker'
import { InlineAIAssistantMessage, InlineAICompletion, InlineNotebookAIRunner } from './MarkdownNotebookInlineAI'
-import { getMarkdownRegistryForFeatureFlags } from './markdownNotebookRegistry'
+import {
+ getHiddenInsertCommandKeysForFeatureFlags,
+ getMarkdownRegistryForFeatureFlags,
+} from './markdownNotebookRegistry'
import { useNotebookComponentRunStatusResolver } from './markdownNotebookRunStatus'
import {
InlineNotebookAIRequest,
@@ -90,6 +93,10 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
useValues(notebookLogic)
const { featureFlags } = useValues(featureFlagLogic)
const markdownRegistry = useMemo(() => getMarkdownRegistryForFeatureFlags(featureFlags), [featureFlags])
+ const hiddenInsertCommandKeys = useMemo(
+ () => getHiddenInsertCommandKeysForFeatureFlags(featureFlags),
+ [featureFlags]
+ )
const resolveComponentRunStatus = useNotebookComponentRunStatusResolver(mountedNotebookLogic.props.shortId)
const {
handleMarkdownEditorChange,
@@ -744,6 +751,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot
mode={isEditable ? 'edit' : 'view'}
registry={markdownRegistry}
extraInsertCommands={isEditable ? buildExtraInsertCommands : undefined}
+ hiddenInsertCommandKeys={hiddenInsertCommandKeys}
onChange={isEditable ? handleMarkdownNotebookChange : undefined}
onConflict={reportMarkdownMergeConflicts}
remoteCarets={remoteCarets}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
index 2b6555a41479..67eeb88f5959 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx
@@ -1,6 +1,13 @@
import { render } from '@testing-library/react'
+import {
+ buildInsertCommands,
+ getMarkdownNotebookDefaultRegistry,
+ mergeMarkdownNotebookRegistries,
+ omitInsertCommands,
+} from 'lib/components/MarkdownNotebook'
import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { NotebookNodeType } from '../types'
import { KNOWN_NODES } from '../utils'
@@ -8,6 +15,7 @@ import {
NOTEBOOK_MARKDOWN_REGISTRY,
RealNotebookNodeEdit,
getEditableNodeAttributeKeys,
+ getHiddenInsertCommandKeysForFeatureFlags,
getMarkdownNodeAttributeLabel,
getMarkdownRegistryForFeatureFlags,
getQueryTitle,
@@ -15,6 +23,31 @@ import {
getSerializableProps,
} from './markdownNotebookRegistry'
+// Mirrors how MarkdownNotebook composes its menu, so the assertions cover the list a user sees
+// rather than the registry alone: built-in commands are not registry entries, so a node hidden
+// from the registry can still reach the menu through a built-in that inserts the same tag.
+function getInsertCommandsByLabel(featureFlags: FeatureFlagsSet, label: string): { key: string; category: string }[] {
+ const noop = (): void => {}
+ const commands = omitInsertCommands(
+ buildInsertCommands(
+ mergeMarkdownNotebookRegistries(
+ getMarkdownNotebookDefaultRegistry(),
+ getMarkdownRegistryForFeatureFlags(featureFlags)
+ ),
+ noop,
+ noop,
+ noop,
+ noop,
+ noop
+ ),
+ getHiddenInsertCommandKeysForFeatureFlags(featureFlags)
+ )
+
+ return commands
+ .filter((command) => command.label === label)
+ .map((command) => ({ key: command.key, category: command.category }))
+}
+
describe('markdownNotebookRegistry', () => {
describe('getMarkdownRegistryForFeatureFlags', () => {
it('offers a single SQL and Python cell, gated by the revamped notebooks flag', () => {
@@ -34,6 +67,27 @@ describe('markdownNotebookRegistry', () => {
})
})
+ describe('insert menu SQL commands', () => {
+ // Exactly one SQL entry either way, and it stays in the menu's top group across the
+ // flag flip so SQL doesn't move on people when the revamped cell takes over.
+ it.each([
+ [
+ 'the revamped SQL cell replaces the legacy one when the flag is on',
+ true,
+ [{ key: 'component-SQLV2', category: 'Common' }],
+ ],
+ [
+ 'the legacy SQL cell is the only one when the flag is off',
+ false,
+ [{ key: 'query-sql', category: 'Common' }],
+ ],
+ ])('%s', (_label, isFlagOn, expectedCommands) => {
+ expect(getInsertCommandsByLabel({ [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]: isFlagOn }, 'SQL')).toEqual(
+ expectedCommands
+ )
+ })
+ })
+
it('does not make real notebook nodes mutually exclusive in markdown notebooks', () => {
expect(NOTEBOOK_MARKDOWN_REGISTRY.components.Recording.exclusiveEditPanel).toBeUndefined()
expect(NOTEBOOK_MARKDOWN_REGISTRY.components.FeatureFlag.exclusiveEditPanel).toBeUndefined()
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index 48efddf8bd1d..ba4e279d73d7 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -38,7 +38,11 @@ import { type CSSProperties, type PointerEvent as ReactPointerEvent, useCallback
import { IconComment, IconImage } from '@posthog/icons'
import { LemonButton, LemonInput, LemonTextArea, lemonToast } from '@posthog/lemon-ui'
-import { createMarkdownNotebookRegistry } from 'lib/components/MarkdownNotebook'
+import {
+ COMMON_INSERT_COMMAND_CATEGORY,
+ QUERY_SQL_INSERT_COMMAND_KEY,
+ createMarkdownNotebookRegistry,
+} from 'lib/components/MarkdownNotebook'
import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
import { isDiscussionCommentProps } from 'lib/components/MarkdownNotebook/markdown'
import {
@@ -177,6 +181,10 @@ export const MARKDOWN_NODE_DEFINITIONS: {
// are not insertable), so it reads as plain "SQL" in the insert menu.
label: 'SQL',
insertCommand: {
+ // Sits in the menu's top group, where the built-in SQL command it replaces used to be,
+ // so SQL stays where people already reach for it. Only the menu grouping moves; the
+ // definition's category still drives the node's SQL styling in the editor.
+ category: COMMON_INSERT_COMMAND_CATEGORY,
aliases: ['data', 'sql'],
// New cells get a durable nodeId up front: parsed markdown block ids are content
// fingerprints, so without a persisted id every prop change (running the cell
@@ -285,6 +293,15 @@ export function getMarkdownRegistryForFeatureFlags(featureFlags: FeatureFlagsSet
return { components }
}
+// The editor's built-in insert commands live outside the registry, so hiding a node's tag is not
+// enough to keep it out of the menu: a built-in that inserts the same tag has to be dropped by key.
+export function getHiddenInsertCommandKeysForFeatureFlags(featureFlags: FeatureFlagsSet): string[] {
+ // The built-in SQL command inserts a legacy `<Query>` HogQL cell, which SQLV2 replaces: it runs
+ // through the sandbox, names a dataframe other cells can reference, and keeps run history.
+ // Offering both would put two entries labeled "SQL" in the menu.
+ return featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS] ? [QUERY_SQL_INSERT_COMMAND_KEY] : []
+}
+
export function getMarkdownNotebookNodeTitle(
node: NotebookComponentBlockNode,
nodeType: NotebookNodeType | undefined,
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 6881009f6a5d..5649dc0f149a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6732,7 +6732,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 noticeably longer while the notebook's sandbox kernel starts. Markdown cells insert prose — headings, tables, code fences, and mermaid diagrams via ```mermaid fences. saved_insight cells embed an existing insight. component cells insert any other notebook component tag: 'Query' with a query prop for charts and event tables (InsightVizNode wrapping Trends/Funnels/Retention/Paths/Stickiness/Lifecycle queries, DataVisualizationNode for HogQL charts, DataTableNode for event tables), or PostHog components like Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. None of those run.",
+ "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.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Add a cell to a notebook; SQL/Python cells run immediately.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index f1253fec1dba..203dffe746e0 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 noticeably longer while the notebook's sandbox kernel starts. Markdown cells insert prose — headings, tables, code fences, and mermaid diagrams via ```mermaid fences. saved_insight cells embed an existing insight. component cells insert any other notebook component tag: 'Query' with a query prop for charts and event tables (InsightVizNode wrapping Trends/Funnels/Retention/Paths/Stickiness/Lifecycle queries, DataVisualizationNode for HogQL charts, DataTableNode for event tables), or PostHog components like Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. None of those run.",
+ "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.",
"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.ts
index 038202991ec0..61e2904ebf9f 100644
--- a/services/mcp/src/tools/notebooks/addCell.ts
+++ b/services/mcp/src/tools/notebooks/addCell.ts
@@ -44,13 +44,13 @@ export const NotebooksAddCellSchema = z
.regex(COMPONENT_TAG_REGEX)
.optional()
.describe(
- "Component cells: the notebook component to insert, e.g. 'Query' (charts and event tables via its query prop), 'Image', 'Embed', 'Latex', 'FeatureFlag', 'Survey', 'Experiment', 'Person', 'Cohort', 'Recording', 'RecordingPlaylist'. Executable cells are not allowed here — use cell_type sql/python."
+ "Component cells: the notebook component to insert, e.g. 'Query' (product analytics charts and event tables via its query prop), 'Image', 'Embed', 'Latex', 'FeatureFlag', 'Survey', 'Experiment', 'Person', 'Cohort', 'Recording', 'RecordingPlaylist'. Executable cells are not allowed here — use cell_type sql/python."
),
props: z
.record(z.string(), z.unknown())
.optional()
.describe(
- 'Component cells: the props for the tag, matching what the notebook UI stores for that component. For Query: {"query": {"kind": "InsightVizNode", "source": <TrendsQuery|FunnelsQuery|RetentionQuery|PathsQuery|StickinessQuery|LifecycleQuery>}} for insights, {"query": {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "SELECT …"}}} for SQL charts, or {"query": {"kind": "DataTableNode", "source": {"kind": "EventsQuery", …}}} for event tables.'
+ 'Component cells: the props for the tag, matching what the notebook UI stores for that component. For Query: {"query": {"kind": "InsightVizNode", "source": <TrendsQuery|FunnelsQuery|RetentionQuery|PathsQuery|StickinessQuery|LifecycleQuery>}} for insights, or {"query": {"kind": "DataTableNode", "source": {"kind": "EventsQuery", …}}} for event tables. HogQLQuery sources are not accepted here — use cell_type sql, which charts its result too.'
),
dataframe_name: z
.string()
@@ -121,6 +121,25 @@ async function runAndWriteBack(
return shapeRunForModel(outcome)
}
+/**
+ * A `<Query>` whose source is HogQL is the legacy SQL cell. It renders a result table or chart but
+ * does not run through the sandbox, so it names no dataframe other cells can reference and keeps no
+ * run history. SQLV2 (cell_type 'sql') supersedes it and charts its result the same way, so SQL
+ * authored over MCP must land there. The editor's insert menu makes the same choice behind the
+ * revamped-py-notebooks flag that gates this tool.
+ */
+function hasHogQLQuerySource(props: Record<string, unknown> | undefined): boolean {
+ const query = props?.query
+ if (!query || typeof query !== 'object') {
+ return false
+ }
+ const { kind, source } = query as { kind?: unknown; source?: unknown }
+ if (kind === 'HogQLQuery') {
+ return true
+ }
+ return !!source && typeof source === 'object' && (source as { kind?: unknown }).kind === 'HogQLQuery'
+}
+
export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResult>['handler'] = async (
context: Context,
params: z.infer<typeof NotebooksAddCellSchema>
@@ -145,6 +164,11 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu
`Use cell_type 'sql' or 'python' for executable cells instead of tag_name ${params.tag_name}.`
)
}
+ if (hasHogQLQuerySource(params.props)) {
+ throw new Error(
+ "Use cell_type 'sql' for SQL instead of a component with a HogQLQuery source. A sql cell runs the query, names a dataframe other cells can reference, and charts its result."
+ )
+ }
}
if (params.cell_type === 'markdown') {
diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.ts
index b03da502d22d..43402ce7de33 100644
--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts
+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts
@@ -208,6 +208,26 @@ describe('notebook cell tools', () => {
expect(state.saveBodies).toHaveLength(0)
})
+ // The legacy SQL cell: a Query node rendering HogQL results without a run, a dataframe name, or
+ // run history. Reachable only through the component escape hatch, so it is blocked there too.
+ it.each([
+ ['a SQL chart', { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'select 1' } }],
+ ['a SQL result table', { kind: 'DataTableNode', source: { kind: 'HogQLQuery', query: 'select 1' } }],
+ ])('component cell rejects %s, directing SQL to a sql cell', async (_label, query) => {
+ const state = makeState('# Doc\n')
+ const context = createMockContext(state)
+
+ await expect(
+ addCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ cell_type: 'component',
+ tag_name: 'Query',
+ props: { query },
+ })
+ ).rejects.toThrow(/cell_type 'sql'/)
+ expect(state.saveBodies).toHaveLength(0)
+ })
+
it('rejects legacy rich-text notebooks', async () => {
const state = makeState('unused')
const context = createMockContext(state)