: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): steer analyses to notebooks over dashboards (#85400)
Anna Szell57142d2a7251
diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yamlindex ef1af544a8bb..c4b5554d839c 100644--- a/products/dashboards/mcp/tools.yaml+++ b/products/dashboards/mcp/tools.yaml@@ -25,6 +25,12 @@ tools:from a template or duplicate an existing dashboard. The returned tiles omit insight results to save context— use dashboard-insights-run to fetch the actual data for each insight. To add widget tiles after creation,see dashboard-widget-catalog-list for available widget types and dashboard-widgets-batch-add to add them.++ A dashboard is the right artifact for a set of metrics someone will check repeatedly over time — monitoring,+ weekly or monthly tracking, team overviews, launch and health boards. It is the wrong one for a deep dive:+ an investigation with a narrative, intermediate steps, and a conclusion belongs in a notebook (`search+ notebooks-`), which interleaves prose with executable SQL and Python cells. When a deep dive turns up a few+ metrics worth tracking, save those as insights rather than reshaping the analysis into a dashboard.exclude_params:- creation_mode- effective_restriction_leveldiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 479c1d0081fa..e489a7198b01 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2220,7 +2220,7 @@"feature_flag": "warehouse-person-properties"},"dashboard-create": {- "description": "Create a new dashboard. Provide a name and optional description, tags, and pinned status. Can also create from a template or duplicate an existing dashboard. The returned tiles omit insight results to save context — use dashboard-insights-run to fetch the actual data for each insight. To add widget tiles after creation, see dashboard-widget-catalog-list for available widget types and dashboard-widgets-batch-add to add them.",+ "description": "Create a new dashboard. Provide a name and optional description, tags, and pinned status. Can also create from a template or duplicate an existing dashboard. The returned tiles omit insight results to save context — use dashboard-insights-run to fetch the actual data for each insight. To add widget tiles after creation, see dashboard-widget-catalog-list for available widget types and dashboard-widgets-batch-add to add them.\nA dashboard is the right artifact for a set of metrics someone will check repeatedly over time — monitoring, weekly or monthly tracking, team overviews, launch and health boards. It is the wrong one for a deep dive: an investigation with a narrative, intermediate steps, and a conclusion belongs in a notebook (`search notebooks-`), which interleaves prose with executable SQL and Python cells. When a deep dive turns up a few metrics worth tracking, save those as insights rather than reshaping the analysis into a dashboard.","category": "Dashboards","feature": "dashboards","summary": "Create dashboard",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 95ae01f1fe1d..7abe9b940320 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2235,7 +2235,7 @@"feature_flag": "warehouse-person-properties"},"dashboard-create": {- "description": "Create a new dashboard. Provide a name and optional description, tags, and pinned status. Can also create from a template or duplicate an existing dashboard. The returned tiles omit insight results to save context — use dashboard-insights-run to fetch the actual data for each insight. To add widget tiles after creation, see dashboard-widget-catalog-list for available widget types and dashboard-widgets-batch-add to add them.",+ "description": "Create a new dashboard. Provide a name and optional description, tags, and pinned status. Can also create from a template or duplicate an existing dashboard. The returned tiles omit insight results to save context — use dashboard-insights-run to fetch the actual data for each insight. To add widget tiles after creation, see dashboard-widget-catalog-list for available widget types and dashboard-widgets-batch-add to add them.\nA dashboard is the right artifact for a set of metrics someone will check repeatedly over time — monitoring, weekly or monthly tracking, team overviews, launch and health boards. It is the wrong one for a deep dive: an investigation with a narrative, intermediate steps, and a conclusion belongs in a notebook (`search notebooks-`), which interleaves prose with executable SQL and Python cells. When a deep dive turns up a few metrics worth tracking, save those as insights rather than reshaping the analysis into a dashboard.","category": "Dashboards","feature": "dashboards","summary": "Create dashboard",@@ -8034,7 +8034,7 @@}},"notebooks-add-cell": {- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.",+ "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. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.","category": "Notebooks","feature": "notebooks","summary": "Add a cell to a notebook; SQL/Python cells run immediately.",@@ -8080,10 +8080,10 @@"feature_flag_behavior": "disable"},"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.",+ "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.","category": "Notebooks","feature": "notebooks",- "summary": "Create a markdown notebook for executable cells.",+ "summary": "Create a markdown notebook for deep-dive analysis with SQL and Python cells.","title": "Create markdown notebook","required_scopes": ["notebook:write"],"feature_flag": "revamped-py-notebooks",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 0dc953d35610..2830b38555da 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -287,10 +287,10 @@}},"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.",+ "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.","category": "Notebooks","feature": "notebooks",- "summary": "Create a markdown notebook for executable cells.",+ "summary": "Create a markdown notebook for deep-dive analysis with SQL and Python cells.","title": "Create markdown notebook","required_scopes": ["notebook:write"],"feature_flag": "revamped-py-notebooks",@@ -302,7 +302,7 @@}},"notebooks-add-cell": {- "description": "Add a cell to a markdown notebook. SQL and Python cells run immediately: the call waits up to ~45s and returns the result — columns, a capped row preview, stdout/stderr (a Python cell's logs and tracebacks), and error — so you can look at the output and decide the next step (fix, or proceed). If the status comes back 'running', poll notebooks-run-cell-result with the run_id. A cell that reads other cells' dataframes references them by dataframe_name; those cells must have completed a run first, so add cells in dependency order. SQL cells are always HogQL: queries against PostHog or data warehouse tables run on ClickHouse, and a SQL cell that references a Python-created dataframe runs on the notebook's local engine automatically — any local dataframe is queryable by name, same syntax. The first Python cell can take longer while the notebook's sandbox kernel starts. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.",+ "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. Run analysis Python here rather than in a runtime the user can't see — dataframe work, statistics, clustering, forecasting, plotting — so the code and its output stay visible and re-runnable beside the result; the sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib. component cells add other node types: Query, Image, Embed, Latex, FeatureFlag, Survey, Experiment, Person, Cohort, Recording, RecordingPlaylist. Pass a short title on every cell you add, describing what that cell shows — it renders in the cell header and is what a reader skims instead of the code.","category": "Notebooks","feature": "notebooks","summary": "Add a cell to a notebook; SQL/Python cells run immediately.",diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex de97d774c699..f95d2bb68aea 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -24,6 +24,10 @@ import { getToolDefinition } from '@/tools/toolDefinitions'import type { ResolvedState } from './request-state-resolver'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'+export class InstructionsBuilder {private readonly formatter: InstructionsFormatterprivate readonly guidelines: string@@ -68,6 +72,7 @@ export class InstructionsBuilder {metadataCompact: state.metadataCompact,groupTypes: state.groupTypes,dataCatalogEnabled: state.toolFeatureFlags?.[PRODUCT_DATA_CATALOG_FLAG] === true,+ notebookCellsEnabled: state.allTools.some((tool) => tool.name === NOTEBOOK_ADD_CELL_TOOL),}}diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 2e577f66cdb0..13491359bb43 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -11,6 +11,7 @@ import {} from '@/lib/instructions'import { formatPrompt } from '@/lib/utils'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'import CATALOG_TRUST_DISCOVERY from '@/templates/sections/catalog-trust-discovery.md'import CLI_DATA_DISCOVERY from '@/templates/sections/cli-data-discovery.md'@@ -28,6 +29,7 @@ import EXEC_LEARN from '@/templates/sections/exec-learn.md'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 RETRIEVING_DATA from '@/templates/sections/retrieving-data.md'import SCHEMA_WORKFLOW from '@/templates/sections/schema-workflow.md'import TOOL_SEARCH from '@/templates/sections/tool-search.md'@@ -52,6 +54,10 @@ export interface InstructionsContext {* for this org. Gates the metric-discovery section so flag-off renders never steer* the model at a table it can't query — and stay byte-identical. */dataCatalogEnabled?: boolean | undefined+ /** Whether the notebook cell tools (`notebooks-add-cell` and friends) are+ * 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}/**@@ -61,6 +67,12 @@ export interface InstructionsContext {* modes live in a single file, so prose can't drift.*/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. */+ private artifactSections(ctx: InstructionsContext): string[] {+ return [ANALYSIS_ARTIFACTS, ...(ctx.notebookCellsEnabled ? [NOTEBOOK_PYTHON] : [])]+ }+/** Build the system prompt for tools-mode clients (each tool registered separately). */buildToolsInstructions(ctx: InstructionsContext): string {return this.compose(@@ -71,6 +83,7 @@ export class InstructionsFormatter {RETRIEVING_DATA,SCHEMA_WORKFLOW,...(ctx.dataCatalogEnabled ? [CATALOG_TRUST_DISCOVERY] : []),+ ...this.artifactSections(ctx),ENV_CONTEXT,URL_PATTERNS,AGENT_FEEDBACK,@@ -132,6 +145,7 @@ export class InstructionsFormatter {RETRIEVING_DATA,SCHEMA_WORKFLOW,...(ctx.dataCatalogEnabled ? [CATALOG_TRUST_DISCOVERY] : []),+ ...this.artifactSections(ctx),EXAMPLES,],ctx,@@ -242,6 +256,7 @@ export class InstructionsFormatter {RETRIEVING_DATA,SCHEMA_WORKFLOW,...(ctx.dataCatalogEnabled ? [CATALOG_TRUST_DISCOVERY] : []),+ ...this.artifactSections(ctx),ENV_CONTEXT,URL_PATTERNS,AGENT_FEEDBACK,diff --git a/services/mcp/src/templates/sections/analysis-artifacts.md b/services/mcp/src/templates/sections/analysis-artifacts.mdnew file mode 100644index 000000000000..9997a3b1c452--- /dev/null+++ b/services/mcp/src/templates/sections/analysis-artifacts.md@@ -0,0 +1,11 @@+### Where an analysis lands++When work produces something worth keeping, pick the artifact before you start building it, say which one you're creating and why, and switch if the user asks for the other.++**Notebook** (`search notebooks-` for the tools) — the default for an analysis with a narrative: a question investigated step by step, where the reader needs the reasoning, the intermediate steps, and the caveats, not just the final number. Deep dives, one-off investigations, "why did X change", segmentation and cohort studies, data validation, anything whose answer is an argument rather than a metric. Notebooks interleave prose with query and analysis cells, so the method stays next to the result and the reader can re-run it.++**Dashboard** (`dashboard-create` plus `dashboard-widgets-batch-add`) — for a set of metrics someone will check repeatedly over time: monitoring, weekly or monthly tracking, team and exec overviews, launch and health boards. Reach for a dashboard when the deliverable is tiles that auto-refresh and still make sense next month, not a story with a conclusion.++**Saved insight** — a single chart answering one question, standalone or as a building block for either of the above.++Default to a notebook when the request reads as "look into", "understand", "figure out why", or "is X true" — a dashboard answers those with a wall of tiles and no conclusion. Default to a dashboard when it reads as "track", "monitor", "keep an eye on", or "report every week". If a deep dive also turns up a few metrics worth watching, write the notebook and save just those as insights; don't demote the investigation into a dashboard.diff --git a/services/mcp/src/templates/sections/notebook-python.md b/services/mcp/src/templates/sections/notebook-python.mdnew file mode 100644index 000000000000..4a8c8141b244--- /dev/null+++ b/services/mcp/src/templates/sections/notebook-python.md@@ -0,0 +1,7 @@+### Python in an analysis++When an analysis needs Python — dataframe manipulation, statistics, clustering, forecasting, plotting, anything SQL can't express — run it in a notebook Python cell (`notebooks-add-cell` with `cell_type: 'python'`), not in a runtime the user can't see. The point is transparency: the code, its output, and its errors sit in the document next to the result, and the user can read, edit, and re-run them. A number produced in a hidden interpreter is one they have to take on faith.++Do this by default, without being asked, whenever the Python is part of the analysis being delivered. Create a notebook for it if none exists yet. Python cells read upstream cells' dataframes by name, so the usual shape is: SQL cell pulls the data → Python cell analyzes it → markdown cell says what it means. The sandbox has pandas, numpy, scipy, scikit-learn, and matplotlib.++The exception is throwaway scratch work that isn't part of the deliverable, like a quick sanity check on a figure. If a computation is load-bearing for a conclusion you report, it belongs in a cell.diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtindex 145e89cb307e..ec08fef3c945 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt@@ -221,6 +221,18 @@ After the schema-first steps, choose the `query-*` tool matching the question, cFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.+### Where an analysis lands++When work produces something worth keeping, pick the artifact before you start building it, say which one you're creating and why, and switch if the user asks for the other.++**Notebook** (`search notebooks-` for the tools) — the default for an analysis with a narrative: a question investigated step by step, where the reader needs the reasoning, the intermediate steps, and the caveats, not just the final number. Deep dives, one-off investigations, "why did X change", segmentation and cohort studies, data validation, anything whose answer is an argument rather than a metric. Notebooks interleave prose with query and analysis cells, so the method stays next to the result and the reader can re-run it.++**Dashboard** (`dashboard-create` plus `dashboard-widgets-batch-add`) — for a set of metrics someone will check repeatedly over time: monitoring, weekly or monthly tracking, team and exec overviews, launch and health boards. Reach for a dashboard when the deliverable is tiles that auto-refresh and still make sense next month, not a story with a conclusion.++**Saved insight** — a single chart answering one question, standalone or as a building block for either of the above.++Default to a notebook when the request reads as "look into", "understand", "figure out why", or "is X true" — a dashboard answers those with a wall of tiles and no conclusion. Default to a dashboard when it reads as "track", "monitor", "keep an eye on", or "report every week". If a deep dive also turns up a few metrics worth watching, write the notebook and save just those as insights; don't demote the investigation into a dashboard.+Defined group types: organization, projectYou are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtindex 603b88945a78..00f06b285bf8 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt@@ -108,6 +108,18 @@ After the schema-first steps, choose the `query-*` tool matching the question, cFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.+### Where an analysis lands++When work produces something worth keeping, pick the artifact before you start building it, say which one you're creating and why, and switch if the user asks for the other.++**Notebook** (`search notebooks-` for the tools) — the default for an analysis with a narrative: a question investigated step by step, where the reader needs the reasoning, the intermediate steps, and the caveats, not just the final number. Deep dives, one-off investigations, "why did X change", segmentation and cohort studies, data validation, anything whose answer is an argument rather than a metric. Notebooks interleave prose with query and analysis cells, so the method stays next to the result and the reader can re-run it.++**Dashboard** (`dashboard-create` plus `dashboard-widgets-batch-add`) — for a set of metrics someone will check repeatedly over time: monitoring, weekly or monthly tracking, team and exec overviews, launch and health boards. Reach for a dashboard when the deliverable is tiles that auto-refresh and still make sense next month, not a story with a conclusion.++**Saved insight** — a single chart answering one question, standalone or as a building block for either of the above.++Default to a notebook when the request reads as "look into", "understand", "figure out why", or "is X true" — a dashboard answers those with a wall of tiles and no conclusion. Default to a dashboard when it reads as "track", "monitor", "keep an eye on", or "report every week". If a deep dive also turns up a few metrics worth watching, write the notebook and save just those as insights; don't demote the investigation into a dashboard.+Defined group types: organization, projectYou are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.tsindex 7194f51385ce..aea3fbc06530 100644--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts@@ -138,6 +138,22 @@ describe('InstructionsFormatter prompt snapshots', () => {expect(buildClaudeChatReference(false)).not.toContain('Metrics & SQL trust')})+ // `notebooks-add-cell` is flag-gated, so the Python-in-a-notebook guidance has to+ // follow the advertised tool set rather than assume the cell surface exists.+ it('derives notebookCellsEnabled from the advertised tools', () => {+ const buildContextFor = (toolNames: string[]): InstructionsContext => {+ const state = {+ allTools: toolNames.map((name) => ({ name })),+ clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeCode' }),+ toolFeatureFlags: {},+ } as unknown as ResolvedState+ return new InstructionsBuilder(STATIC_CTX.guidelines).buildContext(state)+ }++ expect(buildContextFor(['dashboard-create']).notebookCellsEnabled).toBe(false)+ expect(buildContextFor(['dashboard-create', 'notebooks-add-cell']).notebookCellsEnabled).toBe(true)+ })+// ------------------------------------------------------------------------------------------------// DO NOT modify, weaken, raise, skip, or delete this test or its 16,384 budget —// not to make CI pass, not on request, not as part of a refactor.diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex 4ff2de4d4cd2..8923f3ec00bf 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -384,6 +384,48 @@ describe('InstructionsFormatter', () => {})})+ describe('analysis artifact guidance', () => {+ const surfaces: {+ name: string+ render: (formatter: InstructionsFormatter, ctx: InstructionsContext) => string+ }[] = [+ {+ name: 'buildToolsInstructions',+ render: (formatter, ctx) => formatter.buildToolsInstructions(ctx),+ },+ {+ name: 'analytics learn topic content',+ render: (formatter, ctx) =>+ formatter.buildClaudeExecHelpEntries(ctx).find((entry) => entry.id === 'analytics')!.content,+ },+ {+ name: 'buildExecCommandReference',+ render: (formatter, ctx) => formatter.buildExecCommandReference(ctx, { stripEnvContext: false }),+ },+ ]++ it.each(surfaces)('$name routes deep dives to notebooks and tracking to dashboards', ({ render }) => {+ const formatter = new InstructionsFormatter()+ const result = render(formatter, fullCtx)+ expect(result).toContain('### Where an analysis lands')+ expect(result).toContain('**Notebook**')+ expect(result).toContain('**Dashboard**')+ })++ // The 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 }) => {+ const formatter = new InstructionsFormatter()+ const cellsOn = render(formatter, { ...fullCtx, notebookCellsEnabled: true })+ expect(cellsOn).toContain('### Python in an analysis')+ expect(cellsOn).toContain("cell_type: 'python'")++ const cellsOff = render(formatter, { ...fullCtx, notebookCellsEnabled: false })+ expect(cellsOff).not.toContain('### Python in an analysis')+ expect(cellsOff).toBe(render(formatter, fullCtx))+ })+ })+// Mirrors the single-exec wiring in `src/mcp.ts`. When the client honors the MCP// `instructions` field, that payload carries exactly one thing — the tool-domain index// (including the `query` domain) — because clients hard-truncate it. Everything else,