: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(mcp): notebooks-run and notebooks-run-status tools (#98156)
Sinan Kucukkoseler12a7be7fcf76
diff --git a/products/notebooks/evals/eval_notebook_cells.py b/products/notebooks/evals/eval_notebook_cells.pyindex 56b62d083976..0b4bbf43b202 100644--- a/products/notebooks/evals/eval_notebook_cells.py+++ b/products/notebooks/evals/eval_notebook_cells.py@@ -10,7 +10,7 @@ To run one case:from __future__ import annotations-from products.notebooks.evals.scorers import CellRunsCompleted, NotebookCreated+from products.notebooks.evals.scorers import CellRunsCompleted, NotebookCreated, NotebookRunCompletedfrom products.notebooks.evals.seeders import seed_case_teamfrom products.posthog_ai.eval_harness.base import SandboxedPublicEvalfrom products.posthog_ai.eval_harness.config import SandboxedEvalCase@@ -61,6 +61,27 @@ async def eval_notebook_cells(ctx: EvalContext) -> None:},setup=seed_case_team,),+ SandboxedEvalCase(+ # The whole-notebook run: the agent has to set the window and re-run every cell+ # in one step, rather than walking the cells one at a time.+ name="rerun_notebook_for_a_new_window",+ prompt=(+ "Create a notebook called 'Signup window'. Declare a variable `days_back` set to 30, "+ "add a SQL cell that counts `signed_up` events over the last `days_back` days, and add "+ "a Python cell that reads that cell's dataframe and prints the total. Then change "+ "`days_back` to 7 and run the whole notebook again so both cells reflect the new window."+ ),+ expected={+ "notebook_created": {},+ "cell_runs_completed": {"node_types": ["hogql", "python"]},+ # The point of the case. Walking the cells one at a time satisfies+ # cell_runs_completed just as well, so only the run row proves the agent used+ # the single call — and only its frozen variables prove the run that finished+ # is the second one, under the new window.+ "notebook_run_completed": {"variables": {"days_back": 7}},+ },+ setup=seed_case_team,+ ),]await SandboxedPublicEval(@@ -70,6 +91,7 @@ async def eval_notebook_cells(ctx: EvalContext) -> None:RequiredToolCall({"notebooks-add-cell"}),NotebookCreated(),CellRunsCompleted(),+ NotebookRunCompleted(),],ctx=ctx,)diff --git a/products/notebooks/evals/scorers.py b/products/notebooks/evals/scorers.pyindex 4bde2c9e7458..619c55d668a5 100644--- a/products/notebooks/evals/scorers.py+++ b/products/notebooks/evals/scorers.py@@ -9,6 +9,11 @@ Reading the ORM means running async: the engine dispatches every scorer through``eval_async``, and the base class's sync branch would execute Django ORM calls on theevent loop, which Django's async-safety guard rejects.+``NotebookRunCompleted`` reads the whole-notebook run row, which only the run endpoints+create — per-cell runs look the same whether the agent walked the cells or ran them in one+call, so that row is the only evidence of the single-call path, and its frozen variables say+which run finished.+``NotebookApproachQuality`` is the qualitative layer. It reads the cells the agent authoredfrom the tool-call transcript rather than the database, because the question it asks is aboutthe *approach* the agent took — the SQL it wrote, the Python it wrote, the story it told —@@ -25,7 +30,7 @@ from typing import Anyfrom posthog.dataclasses import frozenfrom products.notebooks.backend.markdown_conversion import MARKDOWN_NOTEBOOK_NODE_TYPE-from products.notebooks.backend.models import Notebook, NotebookNodeRun+from products.notebooks.backend.models import Notebook, NotebookNodeRun, NotebookRunfrom products.posthog_ai.eval_harness.log_parser import LogParser, ToolCallfrom products.posthog_ai.eval_harness.scorers import (GRADED_ALIGNMENT_CHOICE_SCORES,@@ -35,7 +40,13 @@ from products.posthog_ai.eval_harness.scorers import ()from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer-__all__ = ["CellRunsCompleted", "ChurnCohortSurfaced", "NotebookApproachQuality", "NotebookCreated"]+__all__ = [+ "CellRunsCompleted",+ "ChurnCohortSurfaced",+ "NotebookApproachQuality",+ "NotebookCreated",+ "NotebookRunCompleted",+]def _seeded_team_id(output: dict | None) -> int | None:@@ -214,6 +225,79 @@ class CellRunsCompleted(AsyncOnlyScorerMixin, Scorer):]+def _variables_match(variables: Any, required: dict[str, Any]) -> bool:+ """Whether a run's frozen variable snapshot carries every required name and value.++ Values are compared as text: a variable the agent set through the tool arrives as the+ JSON it sent, so 7 and "7" are the same answer to "which window did this run use".+ """+ if not isinstance(variables, list):+ return False+ by_name = {entry.get("name"): entry.get("value") for entry in variables if isinstance(entry, dict)}+ return all(str(by_name.get(name)) == str(value) for name, value in required.items())+++class NotebookRunCompleted(AsyncOnlyScorerMixin, Scorer):+ """Binary: did a whole-notebook run finish, carrying the variables the case asked for?++ ``expected = {"notebook_run_completed": {"variables": {"days_back": 7}}}``++ Reads ``NotebookRun``, which only the whole-notebook run endpoints create. Walking the+ cells one at a time leaves the same per-cell run rows behind, so ``CellRunsCompleted``+ cannot tell the two apart — this row is what proves the agent took the single-call path.+ Its frozen variable snapshot then proves *which* run finished, so a case that asks for a+ re-run under a new window is not satisfied by the first pass.++ Self-skips (``None``) when the case does not opt in.+ """++ def _name(self) -> str:+ return "notebook_run_completed"++ async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:+ spec = _spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})+ team_id = _seeded_team_id(output)+ if team_id is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No seed.team_id — case needs a seeder"})++ runs = await asyncio.to_thread(self._read_runs, team_id)+ finished = [run for run in runs if run["status"] == NotebookRun.Status.DONE]+ if not finished:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "No whole-notebook run finished", "runs": runs},+ )++ required = spec.get("variables")+ if not isinstance(required, dict) or not required:+ return Score(name=self._name(), score=1.0, metadata={"runs": finished})+ matching = [run for run in finished if _variables_match(run["variables"], required)]+ if not matching:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "A run finished, but none with the expected variables",+ "expected_variables": required,+ "runs": finished,+ },+ )+ return Score(name=self._name(), score=1.0, metadata={"runs": matching})++ @staticmethod+ def _read_runs(team_id: int) -> list[dict[str, Any]]:+ return [+ {"notebook_short_id": short_id, "status": status, "variables": variables, "cell_count": len(plan or [])}+ for short_id, status, variables, plan in NotebookRun.objects.for_team(team_id)+ .filter(notebook__deleted=False)+ .order_by("created_at")+ .values_list("notebook__short_id", "status", "variables", "cell_plan")+ ]++@frozenclass _CohortMatch:"""Which planted accounts one notebook named, and which it missed."""diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex a57a4c491ecc..6418827abf02 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9678,6 +9678,21 @@"feature_flag_behavior": "disable","superseded_by": ["notebooks-get"]},+ "notebooks-run": {+ "description": "Run every SQL and Python cell of a markdown notebook, in document order, in one call. Cells run one at a time, and the run stops at the first cell that fails or is stopped, so a later cell never reads a stale upstream result. Pass `variables` to set the notebook's values first: the list replaces the whole set and the notebook stores it, so \"refresh this report for last week\" is a single call. Waits up to ~45s and writes each cell's result into the document as it lands. A longer run comes back with status 'running' and a run_id; continue with notebooks-run-status, which keeps waiting and writes the rest. Editing the notebook during a run does not change which cells run: the plan is frozen when the run starts, and a result whose cell was deleted is dropped. Editing a cell's code mid-run is the one case to avoid: the frozen code still runs, and its result lands under the code you just wrote. A Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them the sandbox_hourly_price the first time a run starts one.",+ "category": "Notebooks",+ "feature": "notebooks",+ "summary": "Run every SQL and Python cell of a notebook in document order.",+ "title": "Run notebook",+ "required_scopes": ["notebook:write", "query:read"],+ "feature_flag": "revamped-py-notebooks",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"notebooks-run-cell-interrupt": {"description": "Stop a running cell. Idempotent — interrupting an already-finished run returns its outcome unchanged. The stdout/stderr captured before the stop still arrive through notebooks-run-cell-result.","category": "Notebooks",@@ -9708,8 +9723,23 @@},"feature_flag": "revamped-py-notebooks"},+ "notebooks-run-status": {+ "description": "Keep waiting on a notebook run that notebooks-run started, and write each cell's result into the document as it lands. Waits up to ~45s per call, so call it again while the status is still 'running'. Safe to repeat: a result already in the document is not written a second time. Returns the same shape as notebooks-run, including which cell stopped the run. A cell edited since the run started still receives the frozen code's result, so its rows and its code can disagree.",+ "category": "Notebooks",+ "feature": "notebooks",+ "summary": "Continue waiting on a notebook run and write its results into the document.",+ "title": "Notebook run status",+ "required_scopes": ["notebook:write", "query:read"],+ "feature_flag": "revamped-py-notebooks",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"notebooks-set-variables": {- "description": "Declare or change a markdown notebook's variables: named, typed values that cells read without hardcoding them — a SQL cell as a bare `{name}` placeholder (bound as a value, never as SQL text), a Python cell as a plain global. Use one for an input the reader will want to change (a country, a date range start, a threshold, a row limit) instead of repeating a literal across cells. The list you pass replaces the whole set, so read the current one from notebooks-get first and include every variable you want to keep. Returns the saved variables and stale_cells: cells whose code reads a variable that was added, removed, retyped, or given a new value. Nothing re-runs automatically — re-run each stale cell with notebooks-update-cell (no code) so its result reflects the new values.",+ "description": "Declare or change a markdown notebook's variables: named, typed values that cells read without hardcoding them — a SQL cell as a bare `{name}` placeholder (bound as a value, never as SQL text), a Python cell as a plain global. Use one for an input the reader will want to change (a country, a date range start, a threshold, a row limit) instead of repeating a literal across cells. The list you pass replaces the whole set, so read the current one from notebooks-get first and include every variable you want to keep. Returns the saved variables and stale_cells: cells whose code reads a variable that was added, removed, retyped, or given a new value. Nothing re-runs automatically: re-run each stale cell with notebooks-update-cell (no code), or run the whole notebook with notebooks-run, which can set the variables in the same call.","category": "Notebooks","feature": "notebooks","summary": "Set a notebook's variables; cells read them as {name} in SQL or globals in Python.",@@ -9724,7 +9754,7 @@}},"notebooks-update-cell": {- "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",+ "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. To refresh the whole notebook in one call instead, use notebooks-run. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.","category": "Notebooks","feature": "notebooks","summary": "Update a cell's code and re-run it.",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 6a1bb79a438d..2e7ce4fe93a5 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -319,7 +319,7 @@}},"notebooks-update-cell": {- "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",+ "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. To refresh the whole notebook in one call instead, use notebooks-run. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.","category": "Notebooks","feature": "notebooks","summary": "Update a cell's code and re-run it.",@@ -348,8 +348,38 @@"readOnlyHint": false}},+ "notebooks-run": {+ "description": "Run every SQL and Python cell of a markdown notebook, in document order, in one call. Cells run one at a time, and the run stops at the first cell that fails or is stopped, so a later cell never reads a stale upstream result. Pass `variables` to set the notebook's values first: the list replaces the whole set and the notebook stores it, so \"refresh this report for last week\" is a single call. Waits up to ~45s and writes each cell's result into the document as it lands. A longer run comes back with status 'running' and a run_id; continue with notebooks-run-status, which keeps waiting and writes the rest. Editing the notebook during a run does not change which cells run: the plan is frozen when the run starts, and a result whose cell was deleted is dropped. Editing a cell's code mid-run is the one case to avoid: the frozen code still runs, and its result lands under the code you just wrote. A Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them the sandbox_hourly_price the first time a run starts one.",+ "category": "Notebooks",+ "feature": "notebooks",+ "summary": "Run every SQL and Python cell of a notebook in document order.",+ "title": "Run notebook",+ "required_scopes": ["notebook:write", "query:read"],+ "feature_flag": "revamped-py-notebooks",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "notebooks-run-status": {+ "description": "Keep waiting on a notebook run that notebooks-run started, and write each cell's result into the document as it lands. Waits up to ~45s per call, so call it again while the status is still 'running'. Safe to repeat: a result already in the document is not written a second time. Returns the same shape as notebooks-run, including which cell stopped the run. A cell edited since the run started still receives the frozen code's result, so its rows and its code can disagree.",+ "category": "Notebooks",+ "feature": "notebooks",+ "summary": "Continue waiting on a notebook run and write its results into the document.",+ "title": "Notebook run status",+ "required_scopes": ["notebook:write", "query:read"],+ "feature_flag": "revamped-py-notebooks",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"notebooks-set-variables": {- "description": "Declare or change a markdown notebook's variables: named, typed values that cells read without hardcoding them — a SQL cell as a bare `{name}` placeholder (bound as a value, never as SQL text), a Python cell as a plain global. Use one for an input the reader will want to change (a country, a date range start, a threshold, a row limit) instead of repeating a literal across cells. The list you pass replaces the whole set, so read the current one from notebooks-get first and include every variable you want to keep. Returns the saved variables and stale_cells: cells whose code reads a variable that was added, removed, retyped, or given a new value. Nothing re-runs automatically — re-run each stale cell with notebooks-update-cell (no code) so its result reflects the new values.",+ "description": "Declare or change a markdown notebook's variables: named, typed values that cells read without hardcoding them — a SQL cell as a bare `{name}` placeholder (bound as a value, never as SQL text), a Python cell as a plain global. Use one for an input the reader will want to change (a country, a date range start, a threshold, a row limit) instead of repeating a literal across cells. The list you pass replaces the whole set, so read the current one from notebooks-get first and include every variable you want to keep. Returns the saved variables and stale_cells: cells whose code reads a variable that was added, removed, retyped, or given a new value. Nothing re-runs automatically: re-run each stale cell with notebooks-update-cell (no code), or run the whole notebook with notebooks-run, which can set the variables in the same call.","category": "Notebooks","feature": "notebooks","summary": "Set a notebook's variables; cells read them as {name} in SQL or globals in Python.",diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex 8a92893a6abc..ddde0dd3dd83 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -33,6 +33,7 @@ import { toMcpInputSchema } from './tool-catalog'/** Presence of this tool is the runtime signal that the notebook cell surface* (the `revamped-py-notebooks` flag) is live for this client. */const NOTEBOOK_ADD_CELL_TOOL = 'notebooks-add-cell'+const NOTEBOOK_RUN_TOOL = 'notebooks-run'const DOCS_SEARCH_TOOL = 'docs-search'const BUSINESS_KNOWLEDGE_SEARCH_TOOL = 'business-knowledge-documents-search'@@ -77,6 +78,7 @@ export class InstructionsBuilder {}),renderUiEnabled: state.renderUiEnabled,notebookCellsEnabled: state.allTools.some((tool) => tool.name === NOTEBOOK_ADD_CELL_TOOL),+ notebookRunEnabled: state.allTools.some((tool) => tool.name === NOTEBOOK_RUN_TOOL),docsSearchEnabled: state.allTools.some((tool) => tool.name === DOCS_SEARCH_TOOL),}}diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 8bac086a54e4..a2bb6740103d 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -8,8 +8,8 @@ import {type ToolInfo,} from '@/lib/instructions'import { formatPrompt } from '@/lib/utils'-import ACTIVITY_HISTORY from '@/templates/sections/activity-history.md'import ACTIVITY_HISTORY_SQL from '@/templates/sections/activity-history-sql.md'+import ACTIVITY_HISTORY from '@/templates/sections/activity-history.md'import AGENT_FEEDBACK from '@/templates/sections/agent-feedback.md'import ANALYSIS_ARTIFACTS from '@/templates/sections/analysis-artifacts.md'import BASIC_FUNCTIONALITY from '@/templates/sections/basic-functionality.md'@@ -34,6 +34,7 @@ import EXEC_TOOL_BLURB from '@/templates/sections/exec-tool-blurb.md'import METRIC_DISCOVERY_COMPACT from '@/templates/sections/metric-discovery-compact.md'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 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'@@ -62,6 +63,11 @@ export interface InstructionsContext {* advertised to this client. Gates the Python-in-a-notebook section so we never* tell an agent to put its analysis in a cell type it can't create. */notebookCellsEnabled?: boolean | undefined+ /** Whether `notebooks-run` is advertised to this client. Gated separately from+ * the cell tools, because a connection can carry the cell tools without the+ * run tool, and naming a command the catalog withholds sends the agent to a+ * name `search` and `call` cannot resolve. */+ notebookRunEnabled?: boolean | undefined/** Whether `docs-search` is advertised to this client. Gates every mention of* the tool, so the prompt never names a command `search` and `call` cannot* resolve. Carried as a field rather than derived from `tools`, which@@ -133,9 +139,14 @@ 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. */+ * Python-goes-in-a-cell rule 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] : [])]+ return [+ ANALYSIS_ARTIFACTS,+ ...(ctx.notebookCellsEnabled ? [NOTEBOOK_PYTHON] : []),+ ...(ctx.notebookRunEnabled ? [NOTEBOOK_RUN] : []),+ ]}private activityHistorySections(ctx: InstructionsContext): string[] {diff --git a/services/mcp/src/templates/sections/notebook-run.md b/services/mcp/src/templates/sections/notebook-run.mdnew file mode 100644index 000000000000..70a8334a1083--- /dev/null+++ b/services/mcp/src/templates/sections/notebook-run.md@@ -0,0 +1 @@+To refresh a notebook somebody already wrote, use `notebooks-run` rather than re-running the cells one at a time. It runs every SQL and Python cell in document order and can set the notebook's variables in the same call, so a report for a new time window is one call.diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex b2c5ad08f008..b744c8dbd884 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -28,6 +28,8 @@ import notebookAddCell from './notebooks/addCell'import notebookCreateMarkdown from './notebooks/createMarkdown'import notebookDeleteCell from './notebooks/deleteCell'import notebookEdit from './notebooks/edit'+import notebookRun from './notebooks/runNotebook'+import notebookRunStatus from './notebooks/runNotebookStatus'import notebookSetVariables from './notebooks/setVariables'import notebookUpdateCell from './notebooks/updateCell'// Organizations@@ -114,6 +116,8 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {'notebooks-add-cell': notebookAddCell,'notebooks-create-markdown': notebookCreateMarkdown,'notebooks-delete-cell': notebookDeleteCell,+ 'notebooks-run': notebookRun,+ 'notebooks-run-status': notebookRunStatus,'notebooks-set-variables': notebookSetVariables,'notebooks-update-cell': notebookUpdateCell,diff --git a/services/mcp/src/tools/notebooks/cellRuns.ts b/services/mcp/src/tools/notebooks/cellRuns.tsindex 80d0be8e33d0..50cc4e475c67 100644--- a/services/mcp/src/tools/notebooks/cellRuns.ts+++ b/services/mcp/src/tools/notebooks/cellRuns.ts@@ -7,8 +7,8 @@ import type { Context } from '@/tools/types'* timeouts (~60s) so a slow cell degrades to `{status: 'running'}` instead of a client* abort; the next notebooks-run-cell-result call continues the wait.*/-const RUN_WAIT_BUDGET_MS = 45_000-const POLL_DELAYS_MS = [1_000, 1_500, 2_000, 3_000]+export const RUN_WAIT_BUDGET_MS = 45_000+export const POLL_DELAYS_MS = [1_000, 1_500, 2_000, 3_000]const STREAM_CAP_CHARS = 4_000export interface CellRunOutcome {@@ -35,7 +35,7 @@ export interface ShapedRunResult {hint?: string}-const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))+export const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))export async function dispatchRun(context: Context,diff --git a/services/mcp/src/tools/notebooks/cellTags.ts b/services/mcp/src/tools/notebooks/cellTags.tsindex 8f5f284c86b9..6e4f31f1aeb0 100644--- a/services/mcp/src/tools/notebooks/cellTags.ts+++ b/services/mcp/src/tools/notebooks/cellTags.ts@@ -108,6 +108,26 @@ export function upsertProp(tagSource: string, name: string, value: unknown): strreturn `${tagSource.slice(0, closing)}${needsSpace ? ' ' : ''}${serialized} ${tagSource.slice(closing)}`}+/** Drop a prop from a self-closing tag, leaving every other prop untouched. */+export function removeProp(tagSource: string, name: string): string {+ const stringMatch = stringPropRegex(name).exec(tagSource)+ if (stringMatch) {+ // The match starts at the whitespace the prop sits behind, so dropping the whole+ // match keeps the remaining props single-spaced.+ return tagSource.slice(0, stringMatch.index) + tagSource.slice(stringMatch.index + stringMatch[0].length)+ }+ const expression = findExpressionProp(tagSource, name)+ if (!expression) {+ return tagSource+ }+ // `start` points at the name, so walk back over the space in front of it.+ let start = expression.start+ while (start > 0 && /\s/.test(tagSource[start - 1]!)) {+ start -= 1+ }+ return tagSource.slice(0, start) + tagSource.slice(expression.end)+}+export function buildCellTag(tagName: string, props: Record<string, unknown>): string {const serialized = Object.entries(props).filter(([, value]) => value !== undefined)diff --git a/services/mcp/src/tools/notebooks/markdownDoc.ts b/services/mcp/src/tools/notebooks/markdownDoc.tsindex 551a12e26830..dcd2be30c034 100644--- a/services/mcp/src/tools/notebooks/markdownDoc.ts+++ b/services/mcp/src/tools/notebooks/markdownDoc.ts@@ -102,6 +102,11 @@ export async function applyMarkdownEdit(for (let attempt = 0; attempt < 2; attempt++) {const state = await fetchMarkdownNotebook(context, shortId)const nextMarkdown = transform(state.markdown, state.version)+ if (nextMarkdown === state.markdown) {+ // Saving identical content only bumps the version and tells every collaborator the+ // document changed. A repeated write-back is the case this spares them.+ return { notebook: state.notebook, markdown: state.markdown }+ }try {const notebook = await saveMarkdown(context, state, nextMarkdown)return { notebook, markdown: nextMarkdown }diff --git a/services/mcp/src/tools/notebooks/notebookRuns.ts b/services/mcp/src/tools/notebooks/notebookRuns.tsnew file mode 100644index 000000000000..5f9361a218fe--- /dev/null+++ b/services/mcp/src/tools/notebooks/notebookRuns.ts@@ -0,0 +1,202 @@+import type { Schemas } from '@/api/generated'+import type { Context } from '@/tools/types'++import {+ buildResultProp,+ POLL_DELAYS_MS,+ RUN_WAIT_BUDGET_MS,+ shapeRunForModel,+ sleep,+ type ShapedRunResult,+} from './cellRuns'+import { findCellTag, readStringProp, removeProp, replaceCellTag, upsertProp } from './cellTags'+import { applyMarkdownEdit } from './markdownDoc'++export interface NotebookRunCellOutcome {+ node_id: string+ dataframe_name?: string+ /** 'running', 'done', 'failed', 'interrupted', or null before the run reaches the cell. */+ status: string | null+ run?: ShapedRunResult+}++export interface NotebookRunOutcome {+ run_id: string+ status: string+ cell_count: number+ completed_count: number+ failed_cell?: string+ cells: NotebookRunCellOutcome[]+ starts_sandbox?: boolean+ sandbox_hourly_price?: number | null+ hint?: string+}++const STILL_RUNNING_HINT =+ 'The notebook is still running. Call notebooks-run-status with this run_id to keep waiting and to write the remaining results into the document.'++const TERMINAL_CELL_STATUSES = new Set(['done', 'failed', 'interrupted'])++/**+ * How many cells one document save may carry. Batching keeps a poll that finds a whole+ * notebook's worth of finished cells — the agent that started a run and came back later —+ * from holding every result envelope in memory at once, since a single envelope can run to+ * megabytes. A normal poll finds far fewer than this, so it still saves once.+ */+const MAX_CELLS_PER_SAVE = 10++/** A cell result already written into the document, keyed by the run that produced it. */+/**+ * Whether the cell already carries this run's result, or one from a later run.+ *+ * Run ids are uuid7, so their canonical form sorts by creation time and an id above this one+ * belongs to a later execution. Without the ordering, reading the status of an older run —+ * an agent polling run A after run B has finished — puts A's rows back under the cell that+ * B produced, leaving results that do not match the code beside them.+ */+function carriesThisRunOrNewer(markdown: string, nodeId: string, runId: string): boolean {+ const block = findCellTag(markdown, nodeId)+ if (!block) {+ return false+ }+ const existing = readStringProp(block.source, 'runId')+ return !!existing && existing >= runId+}++/**+ * Wait for a whole-notebook run, writing each cell's result into the document as it lands.+ *+ * One `applyMarkdownEdit` per poll, not per cell: a ten-cell run would otherwise save the+ * document ten times in a few seconds, and every save is a version bump other editors see.+ * Returns as soon as the run is terminal, or when the budget runs out — in which case the+ * caller tells the agent to continue with notebooks-run-status.+ */+export async function awaitNotebookRun(+ context: Context,+ notebookId: string,+ notebookPath: string,+ runId: string,+ waitBudgetMs: number = RUN_WAIT_BUDGET_MS+): Promise<NotebookRunOutcome> {+ const deadline = Date.now() + waitBudgetMs+ const shapedByNodeId = new Map<string, ShapedRunResult>()+ const writtenRunIds = new Set<string>()+ let pollIndex = 0++ for (;;) {+ const status = await context.api.request<Schemas.NotebookRunStatusResponse>({+ method: 'GET',+ path: `${notebookPath}runs/${encodeURIComponent(runId)}/`,+ })+ await writeLandedCells(context, notebookId, notebookPath, status, shapedByNodeId, writtenRunIds)++ if (status.status !== 'running') {+ return buildOutcome(runId, status, shapedByNodeId)+ }+ const delay = POLL_DELAYS_MS[Math.min(pollIndex, POLL_DELAYS_MS.length - 1)]!+ pollIndex += 1+ if (Date.now() + delay > deadline) {+ return { ...buildOutcome(runId, status, shapedByNodeId), hint: STILL_RUNNING_HINT }+ }+ await sleep(delay)+ }+}++async function writeLandedCells(+ context: Context,+ notebookId: string,+ notebookPath: string,+ status: Schemas.NotebookRunStatusResponse,+ shapedByNodeId: Map<string, ShapedRunResult>,+ writtenRunIds: Set<string>+): Promise<void> {+ const landed = status.cells.filter(+ (cell) => cell.run_id && !writtenRunIds.has(cell.run_id) && TERMINAL_CELL_STATUSES.has(cell.status ?? '')+ )+ for (let start = 0; start < landed.length; start += MAX_CELLS_PER_SAVE) {+ await writeCellBatch(+ context,+ notebookId,+ notebookPath,+ landed.slice(start, start + MAX_CELLS_PER_SAVE),+ shapedByNodeId,+ writtenRunIds+ )+ }+}++async function writeCellBatch(+ context: Context,+ notebookId: string,+ notebookPath: string,+ batch: Schemas.NotebookRunCell[],+ shapedByNodeId: Map<string, ShapedRunResult>,+ writtenRunIds: Set<string>+): Promise<void> {+ const envelopes: { nodeId: string; runId: string; envelope: Schemas.NotebookSQLV2Envelope | null }[] = []+ for (const cell of batch) {+ const cellRunId = cell.run_id!+ writtenRunIds.add(cellRunId)+ const result = await context.api.request<Schemas.NotebookSQLV2RunStatusResponse>({+ method: 'GET',+ path: `${notebookPath}sql_v2/runs/${encodeURIComponent(cellRunId)}/`,+ })+ const envelope = result.result ?? null+ shapedByNodeId.set(+ cell.node_id,+ shapeRunForModel({+ run_id: cellRunId,+ status: (cell.status ?? 'failed') as ShapedRunResult['status'],+ envelope,+ error: result.error ?? null,+ })+ )+ envelopes.push({ nodeId: cell.node_id, runId: cellRunId, envelope })+ }++ await applyMarkdownEdit(context, notebookId, (current) => {+ let markdown = current+ for (const { nodeId, runId: cellRunId, envelope } of envelopes) {+ // A cell deleted while the run worked has nowhere for its result to land, a cell+ // already carrying this run's result must not be written twice, and one carrying a+ // later run's result must not be rolled back to this one.+ if (carriesThisRunOrNewer(markdown, nodeId, cellRunId)) {+ continue+ }+ const block = findCellTag(markdown, nodeId)+ if (!block) {+ continue+ }+ let source = upsertProp(block.source, 'runId', cellRunId)+ source = envelope+ ? upsertProp(source, 'result', buildResultProp(envelope))+ : // No envelope means this run produced none — it failed or was stopped. Leaving+ // the previous run's rows attached would show them as this run's output, and+ // the editor skips recovery for a cell that already carries a result.+ removeProp(source, 'result')+ markdown = replaceCellTag(markdown, block, source)+ }+ return markdown+ })+}++function buildOutcome(+ runId: string,+ status: Schemas.NotebookRunStatusResponse,+ shapedByNodeId: Map<string, ShapedRunResult>+): NotebookRunOutcome {+ const cells: NotebookRunCellOutcome[] = status.cells.map((cell) => ({+ node_id: cell.node_id,+ ...(cell.dataframe_name ? { dataframe_name: cell.dataframe_name } : {}),+ status: cell.status ?? null,+ ...(shapedByNodeId.has(cell.node_id) ? { run: shapedByNodeId.get(cell.node_id)! } : {}),+ }))+ return {+ run_id: runId,+ status: status.status,+ cell_count: status.cell_count,+ completed_count: cells.filter((cell) => cell.status === 'done').length,+ ...(status.failed_node_id ? { failed_cell: status.failed_node_id } : {}),+ cells,+ }+}diff --git a/services/mcp/src/tools/notebooks/notebookVariableSchema.ts b/services/mcp/src/tools/notebooks/notebookVariableSchema.tsnew file mode 100644index 000000000000..8511d210ff65--- /dev/null+++ b/services/mcp/src/tools/notebooks/notebookVariableSchema.ts@@ -0,0 +1,29 @@+import { z } from 'zod'++import { DATAFRAME_NAME_REGEX } from './cellTags'++/** Mirrors MAX_VARIABLES_PER_NOTEBOOK in sql_v2_serializers.py, so the schema stops at the server's limit. */+export const MAX_NOTEBOOK_VARIABLES = 10++/** One notebook variable, as both notebooks-set-variables and notebooks-run accept it. */+export const NotebookVariableSchema = z+ .object({+ name: z+ .string()+ .regex(DATAFRAME_NAME_REGEX)+ .describe(+ "Identifier cells read: `{name}` in a SQL cell, a plain global in a Python cell. Letters, numbers, and underscores; must not start with a number, repeat another variable, or reuse a cell's dataframe_name."+ ),+ type: z+ .enum(['string', 'number', 'boolean', 'date'])+ .describe(+ "How the value binds: 'string', 'number', 'boolean', or 'date'. A 'date' is an absolute ISO 8601 date or datetime ('2025-01-31', '2025-01-31T09:00:00Z'); relative expressions like '-7d' are rejected, so compute the date first."+ ),+ value: z+ .union([z.string(), z.number(), z.boolean(), z.null()])+ .optional()+ .describe('The current value. Omit or pass null for a declared-but-unset variable.'),+ })+ .strict()++export type NotebookVariableInput = z.infer<typeof NotebookVariableSchema>diff --git a/services/mcp/src/tools/notebooks/runNotebook.ts b/services/mcp/src/tools/notebooks/runNotebook.tsnew file mode 100644index 000000000000..297700f3fdfa--- /dev/null+++ b/services/mcp/src/tools/notebooks/runNotebook.ts@@ -0,0 +1,89 @@+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import type { Context, ToolBase } from '@/tools/types'++import { wrapRunResultAsInformational } from './cellRuns'+import { notebookPathFor } from './markdownDoc'+import { awaitNotebookRun, type NotebookRunOutcome } from './notebookRuns'+import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'+import { MAX_NOTEBOOK_VARIABLES, NotebookVariableSchema } from './notebookVariableSchema'++const RunNotebookInputSchema = z+ .object({+ notebook_id: z.string().describe(NOTEBOOK_SHORT_ID_DESCRIPTION),+ variables: z+ .array(NotebookVariableSchema)+ .max(MAX_NOTEBOOK_VARIABLES)+ .optional()+ .describe(+ `Set the notebook's variables before the run, in one call. This replaces the whole list, so include every variable you want to keep, and the notebook stores what you pass. Omit it to run with the variables already saved. At most ${MAX_NOTEBOOK_VARIABLES}.`+ ),+ wait: z+ .boolean()+ .optional()+ .default(true)+ .describe(+ 'Wait for the run and write each result into the document as it lands. Set false to start the run and return immediately, then follow with notebooks-run-status.'+ ),+ })+ .strict()++export const NotebooksRunSchema = z.preprocess(notebookIdAliases('notebook_id'), RunNotebookInputSchema)++export const runNotebookHandler: ToolBase<typeof NotebooksRunSchema, NotebookRunOutcome>['handler'] = async (+ context: Context,+ params: z.infer<typeof NotebooksRunSchema>+) => {+ const projectId = await context.stateManager.getProjectId()+ const notebookPath = notebookPathFor(projectId, params.notebook_id)++ const started = await context.api.request<Schemas.NotebookRunStartResponse>({+ method: 'POST',+ path: `${notebookPath}runs/`,+ body: params.variables ? { variables: params.variables } : {},+ })+ const disclosure = {+ starts_sandbox: started.starts_sandbox,+ sandbox_hourly_price: started.sandbox_hourly_price ?? null,+ }++ if (params.wait === false) {+ return wrapRunResultAsInformational({+ run_id: started.run_id,+ status: 'running',+ cell_count: started.cell_count,+ completed_count: 0,+ cells: [],+ ...disclosure,+ hint: 'The notebook is running. Call notebooks-run-status with this run_id to read the results and write them into the document.',+ })+ }++ try {+ const outcome = await awaitNotebookRun(context, params.notebook_id, notebookPath, started.run_id)+ return wrapRunResultAsInformational({ ...outcome, ...disclosure })+ } catch (error) {+ // The run started, and the cells may well be executing. Only following it failed —+ // a save that lost every attempt to an active editor, say. Raising bare would take+ // the run id with it, and the caller needs that id: the status tool asks for it, and+ // starting over either collides with this run or repeats it once it finishes.+ return wrapRunResultAsInformational({+ run_id: started.run_id,+ status: 'running',+ cell_count: started.cell_count,+ completed_count: 0,+ cells: [],+ ...disclosure,+ hint: `The run started, but following it failed (${error instanceof Error ? error.message : String(error)}). Call notebooks-run-status with this run_id to read the results and write them into the document.`,+ })+ }+}++const tool = (): ToolBase<typeof NotebooksRunSchema, NotebookRunOutcome> => ({+ name: 'notebooks-run',+ schema: NotebooksRunSchema,+ handler: runNotebookHandler,+})++export default tooldiff --git a/services/mcp/src/tools/notebooks/runNotebookStatus.ts b/services/mcp/src/tools/notebooks/runNotebookStatus.tsnew file mode 100644index 000000000000..86e56ca77b7a--- /dev/null+++ b/services/mcp/src/tools/notebooks/runNotebookStatus.ts@@ -0,0 +1,37 @@+import { z } from 'zod'++import type { Context, ToolBase } from '@/tools/types'++import { wrapRunResultAsInformational } from './cellRuns'+import { notebookPathFor } from './markdownDoc'+import { awaitNotebookRun, type NotebookRunOutcome } from './notebookRuns'+import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'++const RunNotebookStatusInputSchema = z+ .object({+ notebook_id: z.string().describe(NOTEBOOK_SHORT_ID_DESCRIPTION),+ run_id: z.string().describe('The run to continue waiting on, as returned by notebooks-run.'),+ })+ .strict()++export const NotebooksRunStatusSchema = z.preprocess(notebookIdAliases('notebook_id'), RunNotebookStatusInputSchema)++export const runNotebookStatusHandler: ToolBase<+ typeof NotebooksRunStatusSchema,+ NotebookRunOutcome+>['handler'] = async (context: Context, params: z.infer<typeof NotebooksRunStatusSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const notebookPath = notebookPathFor(projectId, params.notebook_id)+ // Idempotent: a cell whose result already carries this run's id is not written again, so+ // calling this repeatedly costs polls rather than document versions.+ const outcome = await awaitNotebookRun(context, params.notebook_id, notebookPath, params.run_id)+ return wrapRunResultAsInformational(outcome)+}++const tool = (): ToolBase<typeof NotebooksRunStatusSchema, NotebookRunOutcome> => ({+ name: 'notebooks-run-status',+ schema: NotebooksRunStatusSchema,+ handler: runNotebookStatusHandler,+})++export default tooldiff --git a/services/mcp/src/tools/notebooks/setVariables.ts b/services/mcp/src/tools/notebooks/setVariables.tsindex c61e97081dd2..ca72c74e8571 100644--- a/services/mcp/src/tools/notebooks/setVariables.ts+++ b/services/mcp/src/tools/notebooks/setVariables.ts@@ -4,31 +4,9 @@ import type { Schemas } from '@/api/generated'import { withInformationalResponse } from '@/tools/tool-utils'import type { Context, ToolBase } from '@/tools/types'-import { DATAFRAME_NAME_REGEX, parseCellTags, variableReaders } from './cellTags'+import { parseCellTags, variableReaders } from './cellTags'import { fetchMarkdownNotebook } from './markdownDoc'--/** Mirrors MAX_VARIABLES_PER_NOTEBOOK in sql_v2_serializers.py, so the schema stops at the server's limit. */-const MAX_NOTEBOOK_VARIABLES = 10--const NotebookVariableSchema = z- .object({- name: z- .string()- .regex(DATAFRAME_NAME_REGEX)- .describe(- "Identifier cells read: `{name}` in a SQL cell, a plain global in a Python cell. Letters, numbers, and underscores; must not start with a number, repeat another variable, or reuse a cell's dataframe_name."- ),- type: z- .enum(['string', 'number', 'boolean', 'date'])- .describe(- "How the value binds: 'string', 'number', 'boolean', or 'date'. A 'date' is an absolute ISO 8601 date or datetime ('2025-01-31', '2025-01-31T09:00:00Z'); relative expressions like '-7d' are rejected, so compute the date first."- ),- value: z- .union([z.string(), z.number(), z.boolean(), z.null()])- .optional()- .describe('The current value. Omit or pass null for a declared-but-unset variable.'),- })- .strict()+import { MAX_NOTEBOOK_VARIABLES, NotebookVariableSchema, type NotebookVariableInput } from './notebookVariableSchema'export const NotebooksSetVariablesSchema = z.object({@@ -47,14 +25,12 @@ export interface SetVariablesResult {stale_cells: { node_id: string; dataframe_name?: string }[]}-type VariableInput = z.infer<typeof NotebookVariableSchema>-function sameDeclaration(a: Schemas.NotebookVariable | undefined, b: Schemas.NotebookVariable | undefined): boolean {return !!a && !!b && a.type === b.type && (a.value ?? null) === (b.value ?? null)}/** Names whose declaration differs between the two lists: added, removed, retyped, or given a new value. */-function changedVariableNames(before: Schemas.NotebookVariable[], after: VariableInput[]): string[] {+function changedVariableNames(before: Schemas.NotebookVariable[], after: NotebookVariableInput[]): string[] {const byNameBefore = new Map(before.map((variable) => [variable.name, variable]))const byNameAfter = new Map(after.map((variable) => [variable.name, variable]))const names = new Set([...byNameBefore.keys(), ...byNameAfter.keys()])diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.tsindex d1deaa98aec7..86703b8ae0b7 100644--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts@@ -5,6 +5,8 @@ import { GENERATED_TOOLS } from '@/tools/generated/notebooks'import { addCellHandler } from '@/tools/notebooks/addCell'import { createMarkdownHandler } from '@/tools/notebooks/createMarkdown'import { deleteCellHandler } from '@/tools/notebooks/deleteCell'+import { runNotebookHandler } from '@/tools/notebooks/runNotebook'+import { runNotebookStatusHandler } from '@/tools/notebooks/runNotebookStatus'import { setVariablesHandler } from '@/tools/notebooks/setVariables'import { updateCellHandler } from '@/tools/notebooks/updateCell'import { formatNotebookWidgetCatalogForAgents } from '@/tools/notebooks/widgetCatalog'@@ -24,6 +26,8 @@ interface MockState {saveBodies: any[]runBodies: any[]runStatusResponses: any[]+ notebookRunStatuses: any[]+ notebookRunStartBodies: any[]createBodies: any[]patchBodies: any[]// Cells the sql_v2 state endpoint reports. Supplied per test: the spans are the backend's@@ -59,6 +63,13 @@ function createMockContext(state: MockState): Context {cells: state.stateCells ?? [],}}+ if (opts.method === 'GET' && /\/runs\//.test(path)) {+ const next = state.notebookRunStatuses.shift()+ if (!next) {+ throw new Error('No queued notebook run status')+ }+ return next+ }if (opts.method === 'GET') {return {short_id: 'aBcD1234',@@ -77,6 +88,10 @@ function createMockContext(state: MockState): Context {variables: state.variables,}}+ if (opts.method === 'POST' && path.endsWith('/runs/')) {+ state.notebookRunStartBodies.push(opts.body)+ return { run_id: 'nbrun-1', cell_count: 2, starts_sandbox: false, sandbox_hourly_price: null }+ }if (opts.method === 'POST' && path.endsWith('/sql_v2/run/')) {state.runBodies.push(opts.body)return { run_id: 'run-1' }@@ -125,6 +140,8 @@ function makeState(markdown: string, variables: any[] = []): MockState {saveBodies: [],runBodies: [],runStatusResponses: [],+ notebookRunStatuses: [],+ notebookRunStartBodies: [],createBodies: [],patchBodies: [],}@@ -1014,4 +1031,240 @@ describe('notebook cell tools', () => {expect(state.saveBodies).toHaveLength(0)})})+ const RUN_MARKDOWN = [+ '# Doc',+ '',+ '<SQLV2 nodeId="first" code="select 1" returnVariable="df" />',+ '',+ '<PythonV2 nodeId="second" code="df.head()" returnVariable="out" />',+ '',+ ].join('\n')++ const runCell = (+ node_id: string,+ dataframe_name: string,+ status: string | null,+ run_id: string | null+ ): Record<string, unknown> => ({+ node_id,+ cell_type: node_id === 'second' ? 'python' : 'sql',+ dataframe_name,+ run_id,+ status,+ error: null,+ })++ const notebookRunStatus = (+ status: string,+ cells: any[],+ failed_node_id: string | null = null+ ): Record<string, unknown> => ({+ run_id: 'nbrun-1',+ status,+ trigger: 'mcp',+ variables: [],+ cell_count: 2,+ current_index: 0,+ current_node_id: null,+ failed_node_id,+ error: null,+ cells,+ created_at: '2026-01-01T00:00:00Z',+ finished_at: null,+ })++ it('run notebook writes each landed result back and batches one save per poll', async () => {+ vi.useFakeTimers()+ const state = makeState(RUN_MARKDOWN)+ state.notebookRunStatuses.push(+ notebookRunStatus('running', [+ runCell('first', 'df', 'done', 'cell-1'),+ runCell('second', 'out', null, null),+ ]),+ notebookRunStatus('done', [+ runCell('first', 'df', 'done', 'cell-1'),+ runCell('second', 'out', 'done', 'cell-2'),+ ])+ )+ state.runStatusResponses.push(DONE_STATUS, DONE_STATUS)+ const context = createMockContext(state)++ const pending = runNotebookHandler(context, { notebook_id: 'aBcD1234', wait: true })+ await vi.advanceTimersByTimeAsync(10_000)+ const result: any = await pending++ expect(result).toMatchObject({ run_id: 'nbrun-1', status: 'done', cell_count: 2, completed_count: 2 })+ // One save per poll, not one per cell: two cells landed across two polls.+ expect(state.saveBodies).toHaveLength(2)+ const markdown = state.saveBodies[1].content.content[0].attrs.markdown+ expect(markdown).toContain('runId="cell-1"')+ expect(markdown).toContain('runId="cell-2"')+ expect(result.cells[0].run).toMatchObject({ run_id: 'cell-1', status: 'done', row_count: 1 })+ })++ it('run status writes a large catch-up in bounded batches', async () => {+ // An agent that starts a run and comes back later finds every cell landed at once.+ // One save per cell-batch keeps the raw envelopes it holds bounded.+ const cells = Array.from({ length: 12 }, (_, i) => `c${i}`)+ const state = makeState(+ [+ '# Doc',+ '',+ ...cells.map((id) => `<SQLV2 nodeId="${id}" code="select 1" returnVariable="${id}" />\n`),+ ].join('\n')+ )+ state.notebookRunStatuses.push({+ ...notebookRunStatus('done', []),+ cell_count: cells.length,+ cells: cells.map((id, i) => runCell(id, id, 'done', `cell-${i}`)),+ })+ cells.forEach(() => state.runStatusResponses.push(DONE_STATUS))+ const context = createMockContext(state)++ const result: any = await runNotebookStatusHandler(context, {+ notebook_id: 'aBcD1234',+ run_id: 'nbrun-1',+ })++ expect(result.completed_count).toBe(12)+ // 12 cells at a cap of 10 is two saves, not one unbounded save and not twelve.+ expect(state.saveBodies).toHaveLength(2)+ const markdown = state.saveBodies[1].content.content[0].attrs.markdown+ expect(markdown).toContain('runId="cell-0"')+ expect(markdown).toContain('runId="cell-11"')+ })++ it('run notebook sets the variables in the same call', async () => {+ const state = makeState(RUN_MARKDOWN)+ state.notebookRunStatuses.push(notebookRunStatus('done', []))+ const context = createMockContext(state)++ await runNotebookHandler(context, {+ notebook_id: 'aBcD1234',+ wait: true,+ variables: [{ name: 'week_start', type: 'date', value: '2026-01-05' }],+ })++ expect(state.notebookRunStartBodies[0]).toEqual({+ variables: [{ name: 'week_start', type: 'date', value: '2026-01-05' }],+ })+ })++ it('run notebook reports the cell that stopped the run', async () => {+ const state = makeState(RUN_MARKDOWN)+ state.notebookRunStatuses.push(+ notebookRunStatus(+ 'failed',+ [runCell('first', 'df', 'failed', 'cell-1'), runCell('second', 'out', null, null)],+ 'first'+ )+ )+ state.runStatusResponses.push({ status: 'failed', result: null, error: 'Unknown table' })+ const context = createMockContext(state)++ const result: any = await runNotebookHandler(context, { notebook_id: 'aBcD1234', wait: true })++ expect(result).toMatchObject({ status: 'failed', failed_cell: 'first', completed_count: 0 })+ expect(result.cells[1].status).toBeNull()+ })++ it('run notebook hands the agent the status tool when the budget ends', async () => {+ vi.useFakeTimers()+ const state = makeState(RUN_MARKDOWN)+ for (let i = 0; i < 60; i++) {+ state.notebookRunStatuses.push(+ notebookRunStatus('running', [+ runCell('first', 'df', 'running', 'cell-1'),+ runCell('second', 'out', null, null),+ ])+ )+ }+ const context = createMockContext(state)++ const pending = runNotebookHandler(context, { notebook_id: 'aBcD1234', wait: true })+ await vi.advanceTimersByTimeAsync(60_000)+ const result: any = await pending++ expect(result.status).toBe('running')+ expect(result.hint).toContain('notebooks-run-status')+ })++ it('run status does not roll a cell back to an older run', async () => {+ // Finish run A, finish run B, then read A's status. The cell carries B's result, and+ // A's rows must not replace them: run ids are uuid7, so the one already there sorting+ // above this one means a later execution produced it.+ const state = makeState(+ ['# Doc', '', '<SQLV2 nodeId="first" code="select 1" returnVariable="df" runId="cell-b" />', ''].join('\n')+ )+ state.notebookRunStatuses.push(notebookRunStatus('done', [runCell('first', 'df', 'done', 'cell-a')]))+ state.runStatusResponses.push(DONE_STATUS)+ const context = createMockContext(state)++ await runNotebookStatusHandler(context, { notebook_id: 'aBcD1234', run_id: 'nbrun-a' })++ expect(state.saveBodies).toHaveLength(0)+ expect(state.markdown).toContain('runId="cell-b"')+ })++ it('a run that produced nothing clears the rows the previous one left', async () => {+ // Rerunning a cell that already has rows, and failing, used to update runId and leave+ // the old result attached. Reopening then shows those rows as this run's output, and+ // the editor skips recovery for a cell that already carries one.+ const state = makeState(+ [+ '# Doc',+ '',+ '<SQLV2 nodeId="first" code="select 1" returnVariable="df" runId="cell-1" result={{"columns":["x"],"first_page":[[1]]}} />',+ '',+ ].join('\n')+ )+ state.notebookRunStatuses.push(notebookRunStatus('done', [runCell('first', 'df', 'failed', 'cell-2')]))+ state.runStatusResponses.push({ status: 'failed', result: null, error: 'boom' })+ const context = createMockContext(state)++ await runNotebookStatusHandler(context, { notebook_id: 'aBcD1234', run_id: 'nbrun-1' })++ const markdown = state.saveBodies[0].content.content[0].attrs.markdown+ expect(markdown).toContain('runId="cell-2"')+ expect(markdown).not.toContain('result=')+ })++ it('a failed write-back still hands back the run id', async () => {+ // The run started and its cells may be executing. Raising bare would take the id with+ // it, and the status tool needs that id — starting over either collides with this run+ // or repeats it once it finishes.+ const state = makeState(RUN_MARKDOWN)+ state.notebookRunStatuses.push(notebookRunStatus('done', [runCell('first', 'df', 'done', 'cell-1')]))+ state.runStatusResponses.push(DONE_STATUS)+ const context = createMockContext(state)+ const passThrough = context.api.request as any+ ;(context.api as any).request = vi.fn(async (opts: any) => {+ if (opts.method === 'POST' && (opts.path ?? '').endsWith('/collab/markdown_save/')) {+ throw new Error('an editor holds the document')+ }+ return passThrough(opts)+ })++ const result: any = await runNotebookHandler(context, { notebook_id: 'aBcD1234', wait: true })++ expect(result.run_id).toBe('nbrun-1')+ expect(result.hint).toContain('notebooks-run-status')+ })++ it('run status leaves a result the document already carries alone', async () => {+ const state = makeState(+ ['# Doc', '', '<SQLV2 nodeId="first" code="select 1" returnVariable="df" runId="cell-1" />', ''].join('\n')+ )+ state.notebookRunStatuses.push(notebookRunStatus('done', [runCell('first', 'df', 'done', 'cell-1')]))+ state.runStatusResponses.push(DONE_STATUS)+ const context = createMockContext(state)++ const result: any = await runNotebookStatusHandler(context, {+ notebook_id: 'aBcD1234',+ run_id: 'nbrun-1',+ })++ expect(result.status).toBe('done')+ expect(state.saveBodies).toHaveLength(0)+ })})diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 41caaaa7daa4..4f78fb75c653 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -964,6 +964,8 @@ describe('Tool Filtering - Feature Flags', () => {expect(off).not.toContain('notebooks-create-markdown')expect(off).not.toContain('notebooks-add-cell')expect(off).not.toContain('notebooks-set-variables')+ expect(off).not.toContain('notebooks-run')+ expect(off).not.toContain('notebooks-run-status')expect(off).not.toContain('notebooks-get')const on = getToolsForFeatures({ featureFlags: { 'revamped-py-notebooks': true } })@@ -972,6 +974,8 @@ describe('Tool Filtering - Feature Flags', () => {expect(on).toContain('notebooks-update-cell')expect(on).toContain('notebooks-delete-cell')expect(on).toContain('notebooks-set-variables')+ expect(on).toContain('notebooks-run')+ expect(on).toContain('notebooks-run-status')expect(on).toContain('notebooks-run-cell-result')expect(on).toContain('notebooks-get')expect(on).toContain('notebooks-list-frames')