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): tell mcp agents to build analyses in notebook sql cells (#109359)

Sinan Kucukkoselerc5d57e0690a4
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 71fde80804b0..669a86777538 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10094,7 +10094,7 @@
"superseded_by": ["notebooks-create-markdown"]
},
"notebooks-create-markdown": {
- "description": "Create a notebook for deep, step-by-step data analysis: query PostHog and connected data warehouse data with SQL (HogQL), or analyze with Python code. SQL and Python cells can also read and query dataframes fetched or created by upstream cells in the notebook. Run a cell, read its result, decide the next step; add markdown cells to explain and summarize findings, and embed saved insights. Give it a title and optionally an initial markdown body. Returns the notebook_id to use with notebooks-add-cell. This is the default artifact for an analysis with a narrative — a deep dive, a one-off investigation, a 'why did X change' — where the reader needs the reasoning and caveats, not just a number; a dashboard is for metrics tracked repeatedly over time. Reach for a notebook without being asked whenever the work needs Python, so the code, its output, and its errors are visible to the user next to the result instead of running where they can't see them.",
+ "description": "Create a notebook for deep, step-by-step data analysis: query PostHog and connected data warehouse data with SQL (HogQL), or analyze with Python code. SQL and Python cells can also read and query dataframes fetched or created by upstream cells in the notebook. Run a cell, read its result, decide the next step; add markdown cells to explain and summarize findings, and embed saved insights. Give it a title and optionally an initial markdown body that states the question and the plan, not results computed elsewhere. Returns the notebook_id to use with notebooks-add-cell. This is the default artifact for an analysis with a narrative — a deep dive, a one-off investigation, a 'why did X change' — where the reader needs the reasoning and caveats, not just a number; a dashboard is for metrics tracked repeatedly over time. Reach for a notebook without being asked whenever the work needs Python, so the code, its output, and its errors are visible to the user next to the result instead of running where they can't see them.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Create a markdown notebook for deep-dive analysis with SQL and Python cells.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index cc3d9fa50e42..bbab925c7d24 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -289,7 +289,7 @@
}
},
"notebooks-create-markdown": {
- "description": "Create a notebook for deep, step-by-step data analysis: query PostHog and connected data warehouse data with SQL (HogQL), or analyze with Python code. SQL and Python cells can also read and query dataframes fetched or created by upstream cells in the notebook. Run a cell, read its result, decide the next step; add markdown cells to explain and summarize findings, and embed saved insights. Give it a title and optionally an initial markdown body. Returns the notebook_id to use with notebooks-add-cell. This is the default artifact for an analysis with a narrative — a deep dive, a one-off investigation, a 'why did X change' — where the reader needs the reasoning and caveats, not just a number; a dashboard is for metrics tracked repeatedly over time. Reach for a notebook without being asked whenever the work needs Python, so the code, its output, and its errors are visible to the user next to the result instead of running where they can't see them.",
+ "description": "Create a notebook for deep, step-by-step data analysis: query PostHog and connected data warehouse data with SQL (HogQL), or analyze with Python code. SQL and Python cells can also read and query dataframes fetched or created by upstream cells in the notebook. Run a cell, read its result, decide the next step; add markdown cells to explain and summarize findings, and embed saved insights. Give it a title and optionally an initial markdown body that states the question and the plan, not results computed elsewhere. Returns the notebook_id to use with notebooks-add-cell. This is the default artifact for an analysis with a narrative — a deep dive, a one-off investigation, a 'why did X change' — where the reader needs the reasoning and caveats, not just a number; a dashboard is for metrics tracked repeatedly over time. Reach for a notebook without being asked whenever the work needs Python, so the code, its output, and its errors are visible to the user next to the result instead of running where they can't see them.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Create a markdown notebook for deep-dive analysis with SQL and Python cells.",
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index 51f9dd79784a..da7437027d26 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -35,6 +35,7 @@ import METRIC_DISCOVERY_COMPACT from '@/templates/sections/metric-discovery-comp
import METRIC_DISCOVERY from '@/templates/sections/metric-discovery.md'
import NOTEBOOK_PYTHON from '@/templates/sections/notebook-python.md'
import NOTEBOOK_RUN from '@/templates/sections/notebook-run.md'
+import NOTEBOOK_SQL from '@/templates/sections/notebook-sql.md'
import RETRIEVING_DATA from '@/templates/sections/retrieving-data.md'
import SCHEMA_WORKFLOW from '@/templates/sections/schema-workflow.md'
import SKILLS_FIRST from '@/templates/sections/skills-first.md'
@@ -93,6 +94,25 @@ function businessKnowledgeRepoSearchLine(execSyntax: boolean): string {
return `- For this team's code, or when document search returns no chunks, call \`${BUSINESS_KNOWLEDGE_REPO_SEARCH_TOOL}\` with file names or topic words, not a sentence. Each repository includes its description. When a description names a handbook or docs, search that repository for those words, read the file, and cite its permalink.`
}
+/** The SQL section's bullets that name a tool. Each one is left out when the connection
+ * lacks a tool it names, so the guidance never sends the agent to a name it cannot call. */
+function notebookSqlVars(ctx: InstructionsContext): Record<string, string> {
+ const available = (tool: string): boolean => ctx.tools?.some(({ name }) => name === tool) ?? false
+ const runAll = available('notebooks-run') ? ', or all at once with `notebooks-run`' : ''
+ return {
+ throwaway_checks: available('execute-sql')
+ ? " Use `execute-sql` only for throwaway checks the notebook does not rely on, like confirming a table's columns."
+ : '',
+ fix_in_place:
+ available('notebooks-update-cell') && available('notebooks-delete-cell')
+ ? '- Fix a failing or wrong query in the same cell with `notebooks-update-cell`, and remove dead ends with `notebooks-delete-cell`, so the notebook keeps only the steps the conclusion rests on.'
+ : '',
+ run_later: available('notebooks-run-cell')
+ ? `- To lay out dependent cells before running them, add them with \`run: false\`, then run them in order with \`notebooks-run-cell\`${runAll}.`
+ : '',
+ }
+}
+
/** Resolve the field, falling back to the advertised tool list for callers that
* build a context without it (the CLI's `--agent-help`). */
function docsSearchAvailable(ctx: InstructionsContext): boolean {
@@ -161,12 +181,12 @@ export class InstructionsFormatter {
}
/** Artifact-choice guidance: notebook vs dashboard vs insight, plus the
- * Python-goes-in-a-cell rule when the notebook cell tools are available, and
+ * SQL-and-Python-go-in-cells rules when the notebook cell tools are available, and
* the refresh-a-notebook rule when the run tool is. */
private artifactSections(ctx: InstructionsContext): string[] {
return [
ANALYSIS_ARTIFACTS,
- ...(ctx.notebookCellsEnabled ? [NOTEBOOK_PYTHON] : []),
+ ...(ctx.notebookCellsEnabled ? [formatPrompt(NOTEBOOK_SQL, notebookSqlVars(ctx)), NOTEBOOK_PYTHON] : []),
...(ctx.notebookRunEnabled ? [NOTEBOOK_RUN] : []),
]
}
diff --git a/services/mcp/src/templates/sections/notebook-sql.md b/services/mcp/src/templates/sections/notebook-sql.md
new file mode 100644
index 000000000000..bcb828fc8738
--- /dev/null
+++ b/services/mcp/src/templates/sections/notebook-sql.md
@@ -0,0 +1,9 @@
+### SQL in an analysis
+
+When the deliverable is a notebook, build the analysis in it as you go, not after. Create the notebook first with a title and the question, then add each query that a reported number depends on as a SQL cell (`notebooks-add-cell` with `cell_type: 'sql'`). A finished run returns the columns and a row preview, while a run that is still going returns only its status: wait for the result, and read it before you write the prose that interprets it.{throwaway_checks}
+
+{fix_in_place}
+
+- Don't retype a cell's result as a markdown table. The cell already shows the table; the prose says what it means.
+- To chart a result, set `visualization` on the SQL cell. Don't save a separate SQL insight for a chart that lives in the notebook; save an insight only when the user wants it outside the notebook.
+{run_later}
diff --git a/services/mcp/src/tools/notebooks/createMarkdown.ts b/services/mcp/src/tools/notebooks/createMarkdown.ts
index 291906ad1d4d..f61f1db90a50 100644
--- a/services/mcp/src/tools/notebooks/createMarkdown.ts
+++ b/services/mcp/src/tools/notebooks/createMarkdown.ts
@@ -13,7 +13,7 @@ export const NotebooksCreateMarkdownSchema = z
.string()
.optional()
.describe(
- 'Optional initial markdown body below the title. Do not include executable cells here — add them with notebooks-add-cell.'
+ 'Optional initial markdown body below the title: the question and the plan, not results computed elsewhere. Do not include executable cells here — add them with notebooks-add-cell.'
),
})
.strict()
diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.ts
index 17785cabd091..77cdeacca51a 100644
--- a/services/mcp/tests/unit/instructions-formatter.test.ts
+++ b/services/mcp/tests/unit/instructions-formatter.test.ts
@@ -521,15 +521,29 @@ describe('InstructionsFormatter', () => {
expect(result).toContain('**Dashboard**')
})
- // The Python guidance names `notebooks-add-cell`, so it must stay out of prompts
+ // The SQL and Python guidance names `notebooks-add-cell`, so it must stay out of prompts
// for clients that aren't advertised the cell tools.
- it.each(surfaces)('$name gates the Python section on the notebook cell tools', ({ render }) => {
+ it.each(surfaces)('$name gates the SQL and Python sections on the notebook cell tools', ({ render }) => {
const formatter = new InstructionsFormatter()
const cellsOn = render(formatter, { ...fullCtx, notebookCellsEnabled: true })
+ expect(cellsOn).toContain('### SQL in an analysis')
+ expect(cellsOn).toContain("cell_type: 'sql'")
expect(cellsOn).toContain('### Python in an analysis')
expect(cellsOn).toContain("cell_type: 'python'")
+ // A connection can carry the cell tools without execute-sql, which needs another scope.
+ const sqlSection = (text: string): string =>
+ text.slice(text.indexOf('### SQL in an analysis'), text.indexOf('### Python in an analysis'))
+ expect(sqlSection(cellsOn)).toContain('`execute-sql`')
+ const withoutExecuteSql = render(formatter, {
+ ...fullCtx,
+ notebookCellsEnabled: true,
+ tools: fullCtx.tools?.filter(({ name }) => name !== 'execute-sql'),
+ })
+ expect(sqlSection(withoutExecuteSql)).not.toContain('execute-sql')
+
const cellsOff = render(formatter, { ...fullCtx, notebookCellsEnabled: false })
+ expect(cellsOff).not.toContain('### SQL in an analysis')
expect(cellsOff).not.toContain('### Python in an analysis')
expect(cellsOff).toBe(render(formatter, fullCtx))
})