: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
fix(mcp): tell agents where a notebook short_id comes from (#94772)
posthog[bot]ae8c2d6b45c6
diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yamlindex 699e7135bfe4..8f5b2f542062 100644--- a/products/notebooks/mcp/tools.yaml+++ b/products/notebooks/mcp/tools.yaml@@ -68,6 +68,16 @@ tools:dollars whenever you set or change the size. That price always describes the sandbox actually serving thenotebook, so if a restart failed it is the old one still running, not the size you just set.notebooks-compute-options lists the presets and the values this tool accepts.+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idfeature_flag: revamped-py-notebooksnotebooks-create:operation: notebooks_create@@ -111,6 +121,16 @@ tools:title: Delete notebookdescription: |Delete a notebook by short_id. The notebook will be soft-deleted and no longer appear in lists.+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idsoft_delete: truenotebooks-get:operation: notebooks_sql_v2_state_retrieve@@ -130,7 +150,18 @@ tools:different code than its last completed run (the cell or an upstream changed), so its displayed result isoutdated. Use this to read or orient in a notebook, find which cells need re-running after edits, and decidere-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Legacy- rich-text notebooks return their raw document in content instead of markdown.+ rich-text notebooks return their raw document in content instead of markdown. When you do not have the+ notebook's short_id, find it with notebooks-list.+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idfeature_flag: revamped-py-notebooksresponse:informational_wrapper:@@ -194,6 +225,16 @@ tools:after Python/DuckDB cells run). To probe deeper than the schema, run a SELECT in a cell. Only a modalbackend is charged: hourly_price is calculated for a local docker kernel too, so quote it to the user onlywhen backend is modal.+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idfeature_flag: revamped-py-notebooksresponse:include:@@ -229,6 +270,16 @@ tools:replacing it with legacy rich-text blocks.exclude_params:- _create_in_folder+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idfeature_flag: notebooks-collaborationfeature_flag_behavior: disablenotebooks-recording-comments-retrieve:@@ -250,7 +301,19 @@ tools:and creation/modification metadata. Use this when you need the raw content or the current version number —required by notebooks-partial-update for optimistic concurrency. For the analysis-oriented view of amarkdown notebook — every cell with its code, dataframe name, dependency edges, and stale status — use- notebooks-get instead (exposed only when the revamped Python notebooks flag is enabled)."+ notebooks-get instead (exposed only when the revamped Python notebooks flag is enabled). When you do not+ have the notebook's short_id, find it with notebooks-list; searching by title is what its search parameter+ is for."+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idfeature_flag: revamped-py-notebooksfeature_flag_behavior: disablenotebooks-run-cell:@@ -286,6 +349,16 @@ tools:description: >Stop a running cell. Idempotent — interrupting an already-finished run returns its outcome unchanged. Thestdout/stderr captured before the stop still arrive through notebooks-run-cell-result.+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idfeature_flag: revamped-py-notebooksnotebooks-run-cell-result:operation: notebooks_sql_v2_runs_retrieve@@ -304,6 +377,16 @@ tools:and tracebacks), media, and error. Use this when notebooks-add-cell or notebooks-update-cell returned status'running' (the cell outlived the call's wait window): poll with the run_id, waiting a few seconds betweenpolls, until the status is terminal, then use the envelope to decide the next step.+ param_overrides:+ short_id:+ description: >+ The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that+ `notebooks-list` returns; not the notebook's UUID `id`.+ aliases:+ - notebook_id+ - notebookId+ - shortId+ - notebook_short_idfeature_flag: revamped-py-notebooksresponse:exclude:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1aa36e61b134..2eea0968a4d1 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8052,7 +8052,7 @@}},"notebooks-get": {- "description": "The full notebook view: title, markdown source, and every cell with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell or an upstream changed), so its displayed result is outdated. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Legacy rich-text notebooks return their raw document in content instead of markdown.",+ "description": "The full notebook view: title, markdown source, and every cell with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell or an upstream changed), so its displayed result is outdated. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Legacy rich-text notebooks return their raw document in content instead of markdown. When you do not have the notebook's short_id, find it with notebooks-list.","category": "Notebooks","feature": "notebooks","summary": "Get notebook",@@ -8112,7 +8112,7 @@"feature_flag_behavior": "disable"},"notebooks-retrieve": {- "description": "Get a notebook's raw record by short_id: title, content (markdown or legacy ProseMirror JSON), version, and creation/modification metadata. Use this when you need the raw content or the current version number — required by notebooks-partial-update for optimistic concurrency. For the analysis-oriented view of a markdown notebook — every cell with its code, dataframe name, dependency edges, and stale status — use notebooks-get instead (exposed only when the revamped Python notebooks flag is enabled).",+ "description": "Get a notebook's raw record by short_id: title, content (markdown or legacy ProseMirror JSON), version, and creation/modification metadata. Use this when you need the raw content or the current version number — required by notebooks-partial-update for optimistic concurrency. For the analysis-oriented view of a markdown notebook — every cell with its code, dataframe name, dependency edges, and stale status — use notebooks-get instead (exposed only when the revamped Python notebooks flag is enabled). When you do not have the notebook's short_id, find it with notebooks-list; searching by title is what its search parameter is for.","category": "Notebooks","feature": "notebooks","summary": "Get notebook",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex c543cd9ed680..ff97e2daa112 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8507,7 +8507,7 @@}},"notebooks-get": {- "description": "The full notebook view: title, markdown source, and every cell with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell or an upstream changed), so its displayed result is outdated. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Legacy rich-text notebooks return their raw document in content instead of markdown.",+ "description": "The full notebook view: title, markdown source, and every cell with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell or an upstream changed), so its displayed result is outdated. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Legacy rich-text notebooks return their raw document in content instead of markdown. When you do not have the notebook's short_id, find it with notebooks-list.","category": "Notebooks","feature": "notebooks","summary": "Get notebook",@@ -8567,7 +8567,7 @@"feature_flag_behavior": "disable"},"notebooks-retrieve": {- "description": "Get a notebook's raw record by short_id: title, content (markdown or legacy ProseMirror JSON), version, and creation/modification metadata. Use this when you need the raw content or the current version number — required by notebooks-partial-update for optimistic concurrency. For the analysis-oriented view of a markdown notebook — every cell with its code, dataframe name, dependency edges, and stale status — use notebooks-get instead (exposed only when the revamped Python notebooks flag is enabled).",+ "description": "Get a notebook's raw record by short_id: title, content (markdown or legacy ProseMirror JSON), version, and creation/modification metadata. Use this when you need the raw content or the current version number — required by notebooks-partial-update for optimistic concurrency. For the analysis-oriented view of a markdown notebook — every cell with its code, dataframe name, dependency edges, and stale status — use notebooks-get instead (exposed only when the revamped Python notebooks flag is enabled). When you do not have the notebook's short_id, find it with notebooks-list; searching by title is what its search parameter is for.","category": "Notebooks","feature": "notebooks","summary": "Get notebook",diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex cd39ac2e3e72..f1aaa8d5cb7c 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -426,6 +426,47 @@ function undeclaredKeys(input: unknown, schema: ZodObjectAny | undefined): strin* undeclared payload cannot inflate the analytics error message. */const MAX_DROPPED_KEYS_NAMED = 5+/** Bound on the parameter description echoed back with a missing-parameter+ * rejection, so a tool with a long field description cannot inflate the+ * analytics error message. */+const MAX_MISSING_PARAM_HINT = 200++/**+ * The missing parameter's own description, appended to the rejection.+ *+ * A bare `missing required parameter: short_id` names the field to fill but not+ * what to fill it with, so a caller that never held the identifier retries the+ * same empty call. The field's description already answers that — where the+ * value comes from and what shape it takes — and this puts it in front of the+ * caller at the moment it needs it, instead of requiring a separate `info` call.+ *+ * Top-level fields only: a nested path describes a field the caller has not+ * reached yet. The text comes from the tool's own schema, never from caller+ * input, so it is safe in the message returned to the caller and recorded as the+ * analytics error message.+ */+function missingParameterHint(path: ReadonlyArray<PropertyKey>, schema: ZodObjectAny | undefined): string {+ if (!schema || path.length !== 1) {+ return ''+ }+ const root = inputJsonSchema(schema)+ const properties = isRecord(root) ? root['properties'] : undefined+ const field = isRecord(properties) ? properties[String(path[0])] : undefined+ const description = isRecord(field) && typeof field['description'] === 'string' ? field['description'].trim() : ''+ if (!description) {+ return ''+ }+ const capped =+ description.length > MAX_MISSING_PARAM_HINT+ ? `${description.slice(0, MAX_MISSING_PARAM_HINT).trimEnd()}...`+ : description+ return ` (${capped})`+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}+/** Turns a Zod validation failure into a short, field-named message the model* can act on. Without it, a missing/`undefined` path segment slips through to* the HTTP layer and the API returns a generic 404 that reads as "entity does@@ -450,8 +491,9 @@ export function formatInputValidationError(const path = issue.path.map(String).join('.')if (issue.code === 'invalid_type') {if ('input' in issue && issue.input === undefined) {+ const hint = missingParameterHint(issue.path, schema)if (looksLikeUnwrappedPayload(issue.path, input, schema)) {- return `missing required parameter: ${path}; the fields you sent belong inside it, so resend them as {"${path}": {...}}`+ return `missing required parameter: ${path}${hint}; the fields you sent belong inside it, so resend them as {"${path}": {...}}`}const dropped = keysWereRejected ? [] : undeclaredKeys(input, schema)if (dropped.length) {@@ -459,9 +501,9 @@ export function formatInputValidationError(.slice(0, MAX_DROPPED_KEYS_NAMED).map((key) => `"${key}"`).join(', ')- return `missing required parameter: ${path}; this tool ignored these keys it does not accept: ${named}`+ return `missing required parameter: ${path}${hint}; this tool ignored these keys it does not accept: ${named}`}- return `missing required parameter: ${path}`+ return `missing required parameter: ${path}${hint}`}return `parameter "${path}" must be of type ${issue.expected}`}@@ -539,6 +581,27 @@ function normalizeDescriptorPath(segments: readonly PropertyKey[], declaredNames}const declaredPropertyNamesCache = new WeakMap<object, ReadonlySet<string>>()+const inputJsonSchemaCache = new WeakMap<object, unknown>()++/**+ * The agent-facing JSON Schema for a tool, converted once per schema object.+ *+ * A schema that can't be converted caches `null`, so a failure costs detail once+ * rather than being retried on every rejection.+ */+function inputJsonSchema(schema: z.ZodType): unknown {+ if (inputJsonSchemaCache.has(schema)) {+ return inputJsonSchemaCache.get(schema)+ }+ let converted: unknown = null+ try {+ converted = z.toJSONSchema(schema, { io: 'input' })+ } catch {+ // Neither telemetry nor an error message may break a tool call.+ }+ inputJsonSchemaCache.set(schema, converted)+ return converted+}/*** Every property name a tool's schema declares, at any depth. A path segment@@ -555,11 +618,7 @@ function declaredPropertyNames(schema: z.ZodType): ReadonlySet<string> {return cached}const names = new Set<string>()- try {- collectDeclaredPropertyNames(z.toJSONSchema(schema, { io: 'input' }), names)- } catch {- // Telemetry must never break a tool call; an empty set only costs detail.- }+ collectDeclaredPropertyNames(inputJsonSchema(schema), names)declaredPropertyNamesCache.set(schema, names)return names}diff --git a/services/mcp/src/tools/generated/notebooks.ts b/services/mcp/src/tools/generated/notebooks.tsindex fc9768d0f77f..efa8317bea89 100644--- a/services/mcp/src/tools/generated/notebooks.ts+++ b/services/mcp/src/tools/generated/notebooks.ts@@ -3,6 +3,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import * as orvalSchemas from '@/generated/notebooks/api'+import { normalizeParamAliases } from '@/tools/cast-helpers'import {withPostHogUrl,withInformationalResponse,@@ -34,7 +35,16 @@ const notebooksComputeOptions = (): ToolBase<const NotebooksConfigureComputeSchema = () => {const NotebooksKernelConfigCreateBody = orvalSchemas.NotebooksKernelConfigCreateBody()const NotebooksKernelConfigCreateParams = orvalSchemas.NotebooksKernelConfigCreateParams()- return NotebooksKernelConfigCreateParams.omit({ project_id: true }).extend(NotebooksKernelConfigCreateBody.shape)+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksKernelConfigCreateParams.omit({ project_id: true })+ .extend(NotebooksKernelConfigCreateBody.shape)+ .extend({+ short_id: NotebooksKernelConfigCreateParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksConfigureCompute = (): ToolBase<@@ -104,7 +114,14 @@ const notebooksCreate = (): ToolBase<ReturnType<typeof NotebooksCreateSchema>, Wconst NotebooksDestroySchema = () => {const NotebooksDestroyParams = orvalSchemas.NotebooksDestroyParams()- return NotebooksDestroyParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksDestroyParams.omit({ project_id: true }).extend({+ short_id: NotebooksDestroyParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksDestroy = (): ToolBase<ReturnType<typeof NotebooksDestroySchema>, Schemas.Notebook> => ({@@ -123,7 +140,14 @@ const notebooksDestroy = (): ToolBase<ReturnType<typeof NotebooksDestroySchema>,const NotebooksGetSchema = () => {const NotebooksSqlV2StateRetrieveParams = orvalSchemas.NotebooksSqlV2StateRetrieveParams()- return NotebooksSqlV2StateRetrieveParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksSqlV2StateRetrieveParams.omit({ project_id: true }).extend({+ short_id: NotebooksSqlV2StateRetrieveParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksGet = (): ToolBase<@@ -178,7 +202,14 @@ const notebooksList = (): ToolBase<const NotebooksListFramesSchema = () => {const NotebooksKernelStatusRetrieveParams = orvalSchemas.NotebooksKernelStatusRetrieveParams()- return NotebooksKernelStatusRetrieveParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksKernelStatusRetrieveParams.omit({ project_id: true }).extend({+ short_id: NotebooksKernelStatusRetrieveParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksListFrames = (): ToolBase<@@ -214,7 +245,16 @@ const notebooksListFrames = (): ToolBase<const NotebooksPartialUpdateSchema = () => {const NotebooksPartialUpdateBody = orvalSchemas.NotebooksPartialUpdateBody()const NotebooksPartialUpdateParams = orvalSchemas.NotebooksPartialUpdateParams()- return NotebooksPartialUpdateParams.omit({ project_id: true }).extend(NotebooksPartialUpdateBody.shape)+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksPartialUpdateParams.omit({ project_id: true })+ .extend(NotebooksPartialUpdateBody.shape)+ .extend({+ short_id: NotebooksPartialUpdateParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksPartialUpdate = (): ToolBase<@@ -255,7 +295,14 @@ const notebooksPartialUpdate = (): ToolBase<const NotebooksRetrieveSchema = () => {const NotebooksRetrieveParams = orvalSchemas.NotebooksRetrieveParams()- return NotebooksRetrieveParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksRetrieveParams.omit({ project_id: true }).extend({+ short_id: NotebooksRetrieveParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksRetrieve = (): ToolBase<@@ -276,7 +323,14 @@ const notebooksRetrieve = (): ToolBase<const NotebooksRunCellInterruptSchema = () => {const NotebooksSqlV2RunsInterruptCreateParams = orvalSchemas.NotebooksSqlV2RunsInterruptCreateParams()- return NotebooksSqlV2RunsInterruptCreateParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksSqlV2RunsInterruptCreateParams.omit({ project_id: true }).extend({+ short_id: NotebooksSqlV2RunsInterruptCreateParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksRunCellInterrupt = (): ToolBase<@@ -297,7 +351,14 @@ const notebooksRunCellInterrupt = (): ToolBase<const NotebooksRunCellResultSchema = () => {const NotebooksSqlV2RunsRetrieveParams = orvalSchemas.NotebooksSqlV2RunsRetrieveParams()- return NotebooksSqlV2RunsRetrieveParams.omit({ project_id: true })+ return z.preprocess(+ normalizeParamAliases({ short_id: ['notebook_id', 'notebookId', 'shortId', 'notebook_short_id'] }),+ NotebooksSqlV2RunsRetrieveParams.omit({ project_id: true }).extend({+ short_id: NotebooksSqlV2RunsRetrieveParams.shape['short_id'].describe(+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."+ ),+ })+ )}const notebooksRunCellResult = (): ToolBase<diff --git a/services/mcp/src/tools/notebooks/addCell.ts b/services/mcp/src/tools/notebooks/addCell.tsindex 0b8a8d633637..6077ad1be798 100644--- a/services/mcp/src/tools/notebooks/addCell.ts+++ b/services/mcp/src/tools/notebooks/addCell.ts@@ -24,14 +24,15 @@ import {type CellTagBlock,} from './cellTags'import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor } from './markdownDoc'+import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'import { getNotebookWidgetTagNames, getNotebookWidgetViewError } from './widgetCatalog'/** The cell header renders a title on a single ellipsized line, so anything longer is cut off anyway. */const CELL_TITLE_MAX_LENGTH = 120-export const NotebooksAddCellSchema = z+const AddCellInputSchema = z.object({- notebook_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),+ notebook_id: z.string().describe(NOTEBOOK_SHORT_ID_DESCRIPTION),cell_type: z.enum(['sql', 'python', 'markdown', 'saved_insight', 'component']).describe(@@ -77,6 +78,8 @@ export const NotebooksAddCellSchema = z}).strict()+export const NotebooksAddCellSchema = z.preprocess(notebookIdAliases('notebook_id'), AddCellInputSchema)+export interface AddCellResult {node_id?: stringdataframe_name?: stringdiff --git a/services/mcp/src/tools/notebooks/deleteCell.ts b/services/mcp/src/tools/notebooks/deleteCell.tsindex eed266193d62..6c716418973a 100644--- a/services/mcp/src/tools/notebooks/deleteCell.ts+++ b/services/mcp/src/tools/notebooks/deleteCell.ts@@ -5,14 +5,17 @@ import type { Context, ToolBase } from '@/tools/types'import { directDependents, findCellTag, parseCellTags, removeCellTag } from './cellTags'import { applyMarkdownEdit, fetchMarkdownNotebook } from './markdownDoc'+import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'-export const NotebooksDeleteCellSchema = z+const DeleteCellInputSchema = z.object({- notebook_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),+ notebook_id: z.string().describe(NOTEBOOK_SHORT_ID_DESCRIPTION),node_id: z.string().describe('The cell to delete, as returned by notebooks-add-cell.'),}).strict()+export const NotebooksDeleteCellSchema = z.preprocess(notebookIdAliases('notebook_id'), DeleteCellInputSchema)+export interface DeleteCellResult {deleted: trueorphaned_dependents: { node_id: string; dataframe_name?: string }[]diff --git a/services/mcp/src/tools/notebooks/edit.ts b/services/mcp/src/tools/notebooks/edit.tsindex 7574d561d250..5ea4c4a77f07 100644--- a/services/mcp/src/tools/notebooks/edit.ts+++ b/services/mcp/src/tools/notebooks/edit.ts@@ -27,13 +27,15 @@ import type { Schemas } from '@/api/generated'import { buildSchemaForDoc, packDocAttrs, type ProseMirrorNodeJSON, unpackDocAttrs } from '@/lib/prosemirror/schema'import type { Context, ToolBase } from '@/tools/types'+import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'+const MARKDOWN_NOTEBOOK_NODE_TYPE = 'ph-markdown-notebook'const ERROR_PREVIEW_LENGTH = 160const Subtree = z.union([z.record(z.string(), z.unknown()), z.array(z.unknown())])const BaseEditSchema = z.object({- short_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),+ short_id: z.string().describe(NOTEBOOK_SHORT_ID_DESCRIPTION),replace_all: z.boolean().optional()@@ -75,11 +77,14 @@ const JsonEditSchema = BaseEditSchema.extend({path: ['new_value'],})-export const NotebookEditSchema = z.union([MarkdownEditSchema, JsonEditSchema])+export const NotebookEditSchema = z.preprocess(+ notebookIdAliases('short_id'),+ z.union([MarkdownEditSchema, JsonEditSchema])+)type MarkdownParams = z.infer<typeof MarkdownEditSchema>type JsonParams = z.infer<typeof JsonEditSchema>-type Params = z.infer<typeof NotebookEditSchema>+type Params = MarkdownParams | JsonParamsfunction isMarkdownParams(params: Params): params is MarkdownParams {return 'old_markdown' in paramsdiff --git a/services/mcp/src/tools/notebooks/notebookId.ts b/services/mcp/src/tools/notebooks/notebookId.tsnew file mode 100644index 000000000000..e8dedcfd6a58--- /dev/null+++ b/services/mcp/src/tools/notebooks/notebookId.ts@@ -0,0 +1,23 @@+import { normalizeParamAliases } from '@/tools/cast-helpers'++/**+ * How every notebook tool documents its notebook identifier.+ *+ * It names `notebooks-list` because a caller that omits the parameter usually+ * never held the id, and it rules out the UUID because that is the other value+ * a notebook record carries under a name that reads like an identifier.+ */+export const NOTEBOOK_SHORT_ID_DESCRIPTION =+ "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`."++/** Every spelling the notebook tools use for the identifier between them. */+const NOTEBOOK_ID_SPELLINGS = ['short_id', 'notebook_id', 'notebookId', 'shortId', 'notebook_short_id']++/**+ * Accepts the other notebook tools' spelling of the identifier and normalizes it+ * to this tool's own. The CRUD tools name it `short_id` and the cell tools name+ * it `notebook_id`, so a caller that learned one spelling was rejected by the+ * other. Compose with `z.preprocess(notebookIdAliases('notebook_id'), schema)`.+ */+export const notebookIdAliases = (canonical: string): ((input: unknown) => unknown) =>+ normalizeParamAliases({ [canonical]: NOTEBOOK_ID_SPELLINGS.filter((name) => name !== canonical) })diff --git a/services/mcp/src/tools/notebooks/updateCell.ts b/services/mcp/src/tools/notebooks/updateCell.tsindex d62b1f28c48d..44852d0231d4 100644--- a/services/mcp/src/tools/notebooks/updateCell.ts+++ b/services/mcp/src/tools/notebooks/updateCell.ts@@ -12,10 +12,11 @@ import {} from './cellRuns'import { collectRunRefs, directDependents, findCellTag, parseCellTags, replaceCellTag, upsertProp } from './cellTags'import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor } from './markdownDoc'+import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'-export const NotebooksUpdateCellSchema = z+const UpdateCellInputSchema = z.object({- notebook_id: z.string().describe('The notebook short_id (the public id in the URL, e.g. `aBcD1234`).'),+ notebook_id: z.string().describe(NOTEBOOK_SHORT_ID_DESCRIPTION),node_id: z.string().describe('The cell to update, as returned by notebooks-add-cell.'),code: z.string()@@ -24,6 +25,8 @@ export const NotebooksUpdateCellSchema = z}).strict()+export const NotebooksUpdateCellSchema = z.preprocess(notebookIdAliases('notebook_id'), UpdateCellInputSchema)+export interface UpdateCellResult {node_id: stringrun: ShapedRunResultdiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-destroy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-destroy.jsonindex a3fbb47e4b6a..164dc1610dd4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-destroy.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-destroy.json@@ -2,6 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"short_id": {+ "description": "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`.","type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.jsonindex be617fc35e79..0f2f4d386520 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-partial-update.json@@ -9,6 +9,7 @@"type": "boolean"},"short_id": {+ "description": "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`.","type": "string"},"text_content": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-retrieve.jsonindex a3fbb47e4b6a..164dc1610dd4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-retrieve.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/notebooks-retrieve.json@@ -2,6 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"short_id": {+ "description": "The notebook's short_id, the short alphanumeric id in its URL (e.g. `aBcD1234`) that `notebooks-list` returns; not the notebook's UUID `id`.","type": "string"}},diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 22a0327094d7..76173a76e786 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -1648,11 +1648,11 @@ describe('exec tool', () => {}it.each([- ['vision-scanners-get', 'scanner_id'],- ['vision-observations-retrieve', 'observation_id'],- ])('names the key %s dropped, so the caller can see it was not read', (toolName, sentKey) => {+ ['vision-scanners-get', 'scanner_id', 'replay scanner'],+ ['vision-observations-retrieve', 'observation_id', 'replay observation'],+ ])('names the key %s dropped, so the caller can see it was not read', (toolName, sentKey, entity) => {expect(formatFor(toolName, { [sentKey]: SOME_UUID })).toBe(- `Invalid input for "${toolName}": missing required parameter: id; this tool ignored these keys it does not accept: "${sentKey}"`+ `Invalid input for "${toolName}": missing required parameter: id (A UUID string identifying this ${entity}.); this tool ignored these keys it does not accept: "${sentKey}"`)})@@ -1676,20 +1676,20 @@ describe('exec tool', () => {// was dropped: the caller omitted the observation id rather than// having a key silently discarded.expect(formatFor('vision-scanners-observations-get', { scanner_id: SOME_UUID })).toBe(- 'Invalid input for "vision-scanners-observations-get": missing required parameter: id'+ 'Invalid input for "vision-scanners-observations-get": missing required parameter: id (A UUID string identifying this replay observation.)')})- it('keeps the bare message for a caller that sent nothing at all', () => {+ it('names no ignored keys for a caller that sent nothing at all', () => {expect(formatFor('vision-scanners-get', {})).toBe(- 'Invalid input for "vision-scanners-get": missing required parameter: id'+ 'Invalid input for "vision-scanners-get": missing required parameter: id (A UUID string identifying this replay scanner.)')})it('says nothing was ignored when the schema rejected the keys instead', () => {// This tool's schema is strict, so `hash` was refused rather than dropped.expect(formatFor('change-requests-approve-execute', { hash: 'x', confirmation: 'confirm' })).toBe(- 'Invalid input for "change-requests-approve-execute": missing required parameter: confirmation_hash; unexpected property: hash'+ 'Invalid input for "change-requests-approve-execute": missing required parameter: confirmation_hash (The confirmation_hash returned by the matching -prepare tool. Pass it back verbatim.); unexpected property: hash')})@@ -1714,5 +1714,62 @@ describe('exec tool', () => {)})})++ // A caller that omits an identifier usually never held one, so a rejection+ // naming only the field sends it back to retry the same empty call. These+ // lock in that the field's own description rides along with the rejection.+ describe('a missing parameter whose schema documents where the value comes from', () => {+ const formatFor = (schema: ZodObjectAny, input: unknown): string => {+ const result = schema.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)+ return formatInputValidationError('some-tool', result.error!, input, schema)+ }++ it('tells the caller which tool returns the identifier it omitted', () => {+ const schema = z.object({ short_id: z.string().describe('Get it from `notebooks-list`.') })++ expect(formatFor(schema, {})).toBe(+ 'Invalid input for "some-tool": missing required parameter: short_id (Get it from `notebooks-list`.)'+ )+ })++ it('names the field alone when its schema documents nothing', () => {+ const schema = z.object({ short_id: z.string() })++ expect(formatFor(schema, {})).toBe(+ 'Invalid input for "some-tool": missing required parameter: short_id'+ )+ })++ it('caps a long description so the analytics error message stays bounded', () => {+ const schema = z.object({ short_id: z.string().describe('word '.repeat(100)) })+ const message = formatFor(schema, {})++ expect(message.length).toBeLessThan(300)+ expect(message).toContain('...)')+ })++ it('leaves a nested miss alone, since that field is not the one to fill next', () => {+ const schema = z.object({+ query: z.object({ limit: z.number().describe('How many rows to return.') }),+ })++ expect(formatFor(schema, { query: {} })).toBe(+ 'Invalid input for "some-tool": missing required parameter: query.limit'+ )+ })++ it('fires for the real generated notebooks-retrieve tool, not just a stand-in schema', () => {+ // The failure this whole branch exists for: agents call the shipped+ // tool with no short_id, so its rejection has to name notebooks-list.+ const tool = GENERATED_TOOL_MAP['notebooks-retrieve']!()+ const result = tool.schema.safeParse({}, { reportInput: true })+ expect(result.success).toBe(false)++ expect(formatInputValidationError('notebooks-retrieve', result.error!, {}, tool.schema)).toContain(+ '`notebooks-list`'+ )+ })+ })})})diff --git a/services/mcp/tests/unit/notebook-identifier-contracts.test.ts b/services/mcp/tests/unit/notebook-identifier-contracts.test.tsnew file mode 100644index 000000000000..b1537bc4f57d--- /dev/null+++ b/services/mcp/tests/unit/notebook-identifier-contracts.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from 'vitest'++import { GENERATED_TOOLS } from '@/tools/generated/notebooks'+import { NotebooksAddCellSchema } from '@/tools/notebooks/addCell'+import { NotebooksDeleteCellSchema } from '@/tools/notebooks/deleteCell'+import { NotebookEditSchema } from '@/tools/notebooks/edit'+import { NotebooksUpdateCellSchema } from '@/tools/notebooks/updateCell'+import type { ZodObjectAny } from '@/tools/types'++// The notebook tools disagree on what to call the identifier: the CRUD tools take `short_id` and+// the cell tools take `notebook_id`. Production traces show agents carrying one tool's spelling to+// the next and being rejected at the schema, before any request goes out. Each tool therefore+// accepts the others' spellings, and dropping a map brings those rejections back.+describe('notebook identifier contracts', () => {+ const SHORT_ID = 'aBcD1234'++ const parseWith = (schema: ZodObjectAny, input: Record<string, unknown>): Record<string, unknown> => {+ const result = schema.safeParse(input)+ expect(result.success).toBe(true)+ return result.data as Record<string, unknown>+ }++ describe.each([+ ['notebooks-retrieve'],+ ['notebooks-get'],+ ['notebooks-destroy'],+ ['notebooks-partial-update'],+ ['notebooks-list-frames'],+ ])('%s normalizes aliases to `short_id`', (toolName) => {+ const schema = GENERATED_TOOLS[toolName]!().schema++ it.each([+ ['short_id', { short_id: SHORT_ID }],+ ['notebook_id', { notebook_id: SHORT_ID }],+ ['notebookId', { notebookId: SHORT_ID }],+ ['shortId', { shortId: SHORT_ID }],+ ])('accepts %s', (_label, input) => {+ const data = parseWith(schema, input)++ expect(data.short_id).toBe(SHORT_ID)+ expect(data).not.toHaveProperty('notebook_id')+ })++ it('keeps short_id when the caller sends both spellings', () => {+ expect(parseWith(schema, { short_id: SHORT_ID, notebook_id: 'other' }).short_id).toBe(SHORT_ID)+ })+ })++ describe.each([+ ['notebooks-update-cell', NotebooksUpdateCellSchema],+ ['notebooks-delete-cell', NotebooksDeleteCellSchema],+ ])('%s normalizes aliases to `notebook_id`', (_toolName, schema) => {+ it.each([+ ['notebook_id', { notebook_id: SHORT_ID }],+ ['short_id', { short_id: SHORT_ID }],+ ['shortId', { shortId: SHORT_ID }],+ ])('accepts %s', (_label, id) => {+ const data = parseWith(schema, { ...id, node_id: 'cell-1' })++ expect(data.notebook_id).toBe(SHORT_ID)+ expect(data).not.toHaveProperty('short_id')+ })+ })++ it('notebooks-add-cell accepts short_id in place of notebook_id', () => {+ const data = parseWith(NotebooksAddCellSchema, {+ short_id: SHORT_ID,+ cell_type: 'markdown',+ markdown: '# Findings',+ })++ expect(data.notebook_id).toBe(SHORT_ID)+ })++ it('notebook-edit accepts notebook_id in place of short_id', () => {+ const data = parseWith(NotebookEditSchema, {+ notebook_id: SHORT_ID,+ old_markdown: 'before',+ new_markdown: 'after',+ })++ expect(data.short_id).toBe(SHORT_ID)+ })+})