: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): show scalar constraints in exec info and state the experiment description cap (#101164)
ruby childse5b10cf9cb7a
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex bd420f1abbd0..e9a970a1c705 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1358,6 +1358,7 @@ class CreateFromPromptInputSerializer(serializers.Serializer):description = serializers.CharField(required=False,allow_blank=True,+ max_length=3000,help_text="Optional experiment description.",)diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 921ad80d01b9..0810b760b2a2 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2924,7 +2924,10 @@ export interface CreateFromPromptInputApi {name?: string/** Optional feature flag key. If omitted, a slug is derived from the experiment name. */feature_flag_key?: string- /** Optional experiment description. */+ /**+ * Optional experiment description.+ * @maxLength 3000+ */description?: string}diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.tsindex 0df8dfd7d7ba..b3d5f3989f99 100644--- a/products/experiments/frontend/generated/api.zod.ts+++ b/products/experiments/frontend/generated/api.zod.ts@@ -1398,6 +1398,8 @@ export const experimentsCreateFromPromptCreateBodyVersionsMax = 10export const experimentsCreateFromPromptCreateBodyTemplatesMax = 3+export const experimentsCreateFromPromptCreateBodyDescriptionMax = 3000+export const ExperimentsCreateFromPromptCreateBody = /* @__PURE__ */ zod.object({prompt_name: zod.string()@@ -1428,7 +1430,11 @@ export const ExperimentsCreateFromPromptCreateBody = /* @__PURE__ */ zod.object(.string().optional().describe('Optional feature flag key. If omitted, a slug is derived from the experiment name.'),- description: zod.string().optional().describe('Optional experiment description.'),+ description: zod+ .string()+ .max(experimentsCreateFromPromptCreateBodyDescriptionMax)+ .optional()+ .describe('Optional experiment description.'),})/**diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 50e8cf828c1b..b34fe4efe2c3 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -255,7 +255,8 @@ tools:created in the PostHog UI). Requires name and feature_flag_key. Feature flag is auto-created — do not createone separately, except for device-id bucketing, which this tool cannot set: create the flag first with`create-feature-flag`. Defaults: 50/50 control/test, 100% rollout, the team's default stats method. Launch- the experiment with the launch tool when ready.+ the experiment with the launch tool when ready. The description accepts at most 3,000 characters and longer+ text is rejected, so keep the hypothesis summary short.include_params:- name- description@@ -331,7 +332,8 @@ tools:experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying afeature flag payload with the prompt name and version so the SDK can resolve which version to serve, andattaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not- create one separately. Launch the experiment with the launch tool when ready.+ create one separately. Launch the experiment with the launch tool when ready. The description accepts at+ most 3,000 characters and longer text is rejected, so keep the hypothesis summary short.ui_app: experimentresponse:include:@@ -1501,7 +1503,8 @@ tools:Do NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or- experiment-ship-variant tools instead.+ experiment-ship-variant tools instead. The description accepts at most 3,000 characters and longer text is+ rejected, so keep the hypothesis summary short.include_params:- name- descriptiondiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 89aae591d297..cbfb9d5c75e3 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4924,7 +4924,7 @@}},"experiment-create": {- "description": "RULES (follow before calling):\n1. Load the creating-experiments skill for the full\n creation workflow.\n\n2. If the user mentions a rollout percentage (e.g. \"25%\"),\n load the configuring-experiment-rollout skill and\n ask the user to clarify BEFORE calling this tool.\n A percentage is always ambiguous — it can mean a\n variant split change OR an overall rollout change.\n\n3. Do NOT pass metrics on creation. Create the draft\n first, then add metrics via experiment-update. Use\n the configuring-experiment-analytics skill for\n metric guidance.\n\n4. If experiment-setup-context is available, call it\n first and use its facts to choose bucketing,\n exposure and metrics.\n\n\nCreates a new experiment in draft status (ignore the \"type\" param, since no-code/toolbar experiments must be created in the PostHog UI). Requires name and feature_flag_key. Feature flag is auto-created — do not create one separately, except for device-id bucketing, which this tool cannot set: create the flag first with `create-feature-flag`. Defaults: 50/50 control/test, 100% rollout, the team's default stats method. Launch the experiment with the launch tool when ready.",+ "description": "RULES (follow before calling):\n1. Load the creating-experiments skill for the full\n creation workflow.\n\n2. If the user mentions a rollout percentage (e.g. \"25%\"),\n load the configuring-experiment-rollout skill and\n ask the user to clarify BEFORE calling this tool.\n A percentage is always ambiguous — it can mean a\n variant split change OR an overall rollout change.\n\n3. Do NOT pass metrics on creation. Create the draft\n first, then add metrics via experiment-update. Use\n the configuring-experiment-analytics skill for\n metric guidance.\n\n4. If experiment-setup-context is available, call it\n first and use its facts to choose bucketing,\n exposure and metrics.\n\n\nCreates a new experiment in draft status (ignore the \"type\" param, since no-code/toolbar experiments must be created in the PostHog UI). Requires name and feature_flag_key. Feature flag is auto-created — do not create one separately, except for device-id bucketing, which this tool cannot set: create the flag first with `create-feature-flag`. Defaults: 50/50 control/test, 100% rollout, the team's default stats method. Launch the experiment with the launch tool when ready. The description accepts at most 3,000 characters and longer text is rejected, so keep the hypothesis summary short.","category": "Experiments","feature": "experiments","summary": "Create experiment",@@ -4938,7 +4938,7 @@}},"experiment-create-from-prompt": {- "description": "Create a draft experiment that compares versions of an existing LLM prompt (managed with the llma-prompt tools). Pass the prompt's exact name (call llma-prompt-list to discover names), two or more of its version numbers (the first entry becomes the control variant), and one or more metric templates — call experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying a feature flag payload with the prompt name and version so the SDK can resolve which version to serve, and attaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not create one separately. Launch the experiment with the launch tool when ready.",+ "description": "Create a draft experiment that compares versions of an existing LLM prompt (managed with the llma-prompt tools). Pass the prompt's exact name (call llma-prompt-list to discover names), two or more of its version numbers (the first entry becomes the control variant), and one or more metric templates — call experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying a feature flag payload with the prompt name and version so the SDK can resolve which version to serve, and attaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not create one separately. Launch the experiment with the launch tool when ready. The description accepts at most 3,000 characters and longer text is rejected, so keep the hypothesis summary short.","category": "Experiments","feature": "experiments","summary": "Create experiment from LLM prompt",@@ -5387,7 +5387,7 @@}},"experiment-update": {- "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n feature_flag config — without it, the request is\n rejected because the change would not sync to the\n feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead.",+ "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n feature_flag config — without it, the request is\n rejected because the change would not sync to the\n feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead. The description accepts at most 3,000 characters and longer text is rejected, so keep the hypothesis summary short.","category": "Experiments","feature": "experiments","summary": "Update experiment",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 74a362397c9d..e83a98dafd51 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4995,7 +4995,7 @@}},"experiment-create": {- "description": "RULES (follow before calling):\n1. Load the creating-experiments skill for the full\n creation workflow.\n\n2. If the user mentions a rollout percentage (e.g. \"25%\"),\n load the configuring-experiment-rollout skill and\n ask the user to clarify BEFORE calling this tool.\n A percentage is always ambiguous — it can mean a\n variant split change OR an overall rollout change.\n\n3. Do NOT pass metrics on creation. Create the draft\n first, then add metrics via experiment-update. Use\n the configuring-experiment-analytics skill for\n metric guidance.\n\n4. If experiment-setup-context is available, call it\n first and use its facts to choose bucketing,\n exposure and metrics.\n\n\nCreates a new experiment in draft status (ignore the \"type\" param, since no-code/toolbar experiments must be created in the PostHog UI). Requires name and feature_flag_key. Feature flag is auto-created — do not create one separately, except for device-id bucketing, which this tool cannot set: create the flag first with `create-feature-flag`. Defaults: 50/50 control/test, 100% rollout, the team's default stats method. Launch the experiment with the launch tool when ready.",+ "description": "RULES (follow before calling):\n1. Load the creating-experiments skill for the full\n creation workflow.\n\n2. If the user mentions a rollout percentage (e.g. \"25%\"),\n load the configuring-experiment-rollout skill and\n ask the user to clarify BEFORE calling this tool.\n A percentage is always ambiguous — it can mean a\n variant split change OR an overall rollout change.\n\n3. Do NOT pass metrics on creation. Create the draft\n first, then add metrics via experiment-update. Use\n the configuring-experiment-analytics skill for\n metric guidance.\n\n4. If experiment-setup-context is available, call it\n first and use its facts to choose bucketing,\n exposure and metrics.\n\n\nCreates a new experiment in draft status (ignore the \"type\" param, since no-code/toolbar experiments must be created in the PostHog UI). Requires name and feature_flag_key. Feature flag is auto-created — do not create one separately, except for device-id bucketing, which this tool cannot set: create the flag first with `create-feature-flag`. Defaults: 50/50 control/test, 100% rollout, the team's default stats method. Launch the experiment with the launch tool when ready. The description accepts at most 3,000 characters and longer text is rejected, so keep the hypothesis summary short.","category": "Experiments","feature": "experiments","summary": "Create experiment",@@ -5009,7 +5009,7 @@}},"experiment-create-from-prompt": {- "description": "Create a draft experiment that compares versions of an existing LLM prompt (managed with the llma-prompt tools). Pass the prompt's exact name (call llma-prompt-list to discover names), two or more of its version numbers (the first entry becomes the control variant), and one or more metric templates — call experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying a feature flag payload with the prompt name and version so the SDK can resolve which version to serve, and attaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not create one separately. Launch the experiment with the launch tool when ready.",+ "description": "Create a draft experiment that compares versions of an existing LLM prompt (managed with the llma-prompt tools). Pass the prompt's exact name (call llma-prompt-list to discover names), two or more of its version numbers (the first entry becomes the control variant), and one or more metric templates — call experiment-prompt-templates for the allowed template keys. Builds one variant per version, each carrying a feature flag payload with the prompt name and version so the SDK can resolve which version to serve, and attaches one primary metric per template, scoped to the prompt. The feature flag is auto-created — do not create one separately. Launch the experiment with the launch tool when ready. The description accepts at most 3,000 characters and longer text is rejected, so keep the hypothesis summary short.","category": "Experiments","feature": "experiments","summary": "Create experiment from LLM prompt",@@ -5486,7 +5486,7 @@}},"experiment-update": {- "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n feature_flag config — without it, the request is\n rejected because the change would not sync to the\n feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead.",+ "description": "RULES (follow before calling):\n1. If changing rollout or variants on a RUNNING\n experiment, you MUST warn the user about user\n experience AND statistical implications BEFORE\n making the change and get explicit confirmation.\n Load the configuring-experiment-rollout skill for\n the full warning. Do NOT silently apply the change\n — even if the user asked directly.\n\n2. If the user mentions a percentage, clarify whether\n they mean variant split or overall rollout BEFORE\n calling.\n\n3. If adding or changing metrics, load the\n configuring-experiment-analytics skill first. Call\n read-data-schema to discover available events BEFORE\n suggesting or using any event name. Never suggest\n event names you haven't confirmed exist.\n\n4. For running experiments, set\n update_feature_flag_params=true when changing\n feature_flag config — without it, the request is\n rejected because the change would not sync to the\n feature flag.\n\n5. Setting allow_unknown_events=true REQUIRES EXPLICIT\n USER CONFIRMATION. When the API returns\n \"Event(s) '...' not found\", do NOT silently retry\n with allow_unknown_events=true. Default to\n course-correcting: surface the missing event names\n and ask whether the user meant a different (existing)\n event. Only set allow_unknown_events=true when the\n user explicitly confirms the event is intentional\n (e.g. about to be instrumented). Course-correcting\n to a known event is the expected default; flipping\n the flag is the exception.\n\n\nUpdate an experiment by ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Metrics can be changed at any time including while running. Cannot add/remove variants on non-draft experiments (changing percentages between existing variants is allowed). Cannot change holdout on non-draft experiments.\n\nDo NOT use this to change lifecycle state — use the dedicated launch, end, pause, resume, archive, or experiment-ship-variant tools instead. The description accepts at most 3,000 characters and longer text is rejected, so keep the hypothesis summary short.","category": "Experiments","feature": "experiments","summary": "Update experiment",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7d5158307e5d..4b4f6e237c7b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24408,7 +24408,10 @@ export namespace Schemas {name?: string;/** Optional feature flag key. If omitted, a slug is derived from the experiment name. */feature_flag_key?: string;- /** Optional experiment description. */+ /**+ * Optional experiment description.+ * @maxLength 3000+ */description?: string;}diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex de5f282b8958..07c7dc061865 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -19308,6 +19308,8 @@ export const experimentsCreateFromPromptCreateBodyVersionsMax = 10export const experimentsCreateFromPromptCreateBodyTemplatesMax = 3+export const experimentsCreateFromPromptCreateBodyDescriptionMax = 3000+export const ExperimentsCreateFromPromptCreateBody = () => zod.object({prompt_name: zod.string()@@ -19338,7 +19340,11 @@ export const ExperimentsCreateFromPromptCreateBody = () => zod.object({.string().optional().describe('Optional feature flag key. If omitted, a slug is derived from the experiment name.'),- description: zod.string().optional().describe('Optional experiment description.'),+ description: zod+ .string()+ .max(experimentsCreateFromPromptCreateBodyDescriptionMax)+ .optional()+ .describe('Optional experiment description.'),})/**diff --git a/services/mcp/src/tools/schema-utils.ts b/services/mcp/src/tools/schema-utils.tsindex 4bea283f4c90..f4ae506749d0 100644--- a/services/mcp/src/tools/schema-utils.ts+++ b/services/mcp/src/tools/schema-utils.ts@@ -5,7 +5,23 @@ export const TOKEN_CHAR_LIMIT = 4 * 12_000type JSONSchema = Record<string, unknown>-interface SummarizedProperty {+/**+ * Scalar constraints copied through from the JSON Schema as-is. Without them an+ * agent in exec mode learns a string cap only from the rejection after it sent+ * too much.+ */+interface ScalarConstraints {+ minLength?: number+ maxLength?: number+ minimum?: number+ maximum?: number+ exclusiveMinimum?: number+ exclusiveMaximum?: number+ pattern?: string+ format?: string+}++interface SummarizedProperty extends ScalarConstraints {type?: stringdescription?: stringenum?: unknown[]@@ -22,7 +38,7 @@ interface SummarizedProperty {* nodes) so callers can read it unconditionally; `items` (arrays) and `variants`* (unions) carry the recursive shape that the old object-only summarizer dropped.*/-interface NodeSummary {+interface NodeSummary extends ScalarConstraints {type: stringtitle?: stringrequired?: string[]@@ -35,6 +51,75 @@ interface NodeSummary {default?: unknown}+const NUMERIC_CONSTRAINT_KEYS = [+ 'minLength',+ 'maxLength',+ 'minimum',+ 'maximum',+ 'exclusiveMinimum',+ 'exclusiveMaximum',+] as const satisfies readonly (keyof ScalarConstraints)[]+const STRING_CONSTRAINT_KEYS = ['pattern', 'format'] as const satisfies readonly (keyof ScalarConstraints)[]++/**+ * A `pattern` longer than this is a generated regex (zod's ISO date-time pattern is+ * 310 characters) that an agent cannot act on; its `format` says the same in a word.+ * Copying every one would grow the catalogue's summaries by about 6%.+ */+const MAX_PATTERN_CHARS = 80++function copyConstraints(from: JSONSchema, to: ScalarConstraints): void {+ for (const key of NUMERIC_CONSTRAINT_KEYS) {+ const value = from[key]+ if (typeof value === 'number') {+ to[key] = value+ }+ }+ for (const key of STRING_CONSTRAINT_KEYS) {+ const value = from[key]+ if (typeof value !== 'string') {+ continue+ }+ if (key === 'pattern' && (typeof from.format === 'string' || value.length > MAX_PATTERN_CHARS)) {+ continue+ }+ to[key] = value+ }+}++/**+ * zod renders `.nullable()` as `anyOf: [variant, {type: 'null'}]` and puts the+ * field's `description` and `default` on that wrapper, not on the variant. Whoever+ * collapses the wrapper to its variant has to carry those two across or the summary+ * loses them.+ */+function carryWrapperMetadata(wrapper: JSONSchema, variant: JSONSchema): JSONSchema {+ return {+ ...variant,+ ...(wrapper.description !== undefined ? { description: wrapper.description } : {}),+ ...(wrapper.default !== undefined ? { default: wrapper.default } : {}),+ }+}++/**+ * A nullable field (`anyOf: [{type: 'string', maxLength: 3000}, {type: 'null'}]`) is+ * its one non-null variant for the caller's purposes. Returns that variant, with the+ * wrapper's description and default, so its type, enum, constraints, fields and+ * drill-down hint are summarized instead of the union wrapper, which carried none of+ * them. Anything else comes back unchanged.+ */+function unwrapNullable(schema: JSONSchema): JSONSchema {+ const variants = (schema.anyOf || schema.oneOf) as JSONSchema[] | undefined+ if (!variants) {+ return schema+ }+ const nonNull = variants.filter((v) => v.type !== 'null')+ if (nonNull.length !== 1) {+ return schema+ }+ return carryWrapperMetadata(schema, nonNull[0]!)+}+/*** Properties that conventionally discriminate a union variant. Zod discriminated* unions (e.g. the trends `series` EventsNode/ActionsNode/GroupNode split) carry the@@ -211,7 +296,8 @@ function summarizeObject(schema: JSONSchema, toolName: string, fieldPath?: strinconst result: Record<string, SummarizedProperty> = {}const pathPrefix = fieldPath ? `${fieldPath}.` : ''- for (const [name, prop] of Object.entries(properties)) {+ for (const [name, rawProp] of Object.entries(properties)) {+ const prop = unwrapNullable(rawProp)const entry: SummarizedProperty = {}entry.type = getTypeString(prop)@@ -227,6 +313,7 @@ function summarizeObject(schema: JSONSchema, toolName: string, fieldPath?: strinif (prop.const !== undefined) {entry.const = prop.const}+ copyConstraints(prop, entry)if (requiredFields.includes(name)) {entry.required = true}@@ -283,6 +370,7 @@ function summarizeLeaf(schema: JSONSchema): NodeSummary {if (schema.default !== undefined) {summary.default = schema.default}+ copyConstraints(schema, summary)return summary}@@ -316,9 +404,10 @@ function summarizeNode(return { type: getTypeString(schema), properties: {} }}if (nonNull.length === 1) {- // Unwrap a nullable wrapper. Count it against `depth` so a pathological- // chain of nested nullable unions still terminates at MAX_SUMMARY_DEPTH.- return summarizeNode(nonNull[0]!, toolName, fieldPath, depth + 1)+ // Unwrap a nullable wrapper, keeping its description and default. Count it+ // against `depth` so a pathological chain of nested nullable unions still+ // terminates at MAX_SUMMARY_DEPTH.+ return summarizeNode(carryWrapperMetadata(schema, nonNull[0]!), toolName, fieldPath, depth + 1)}return {type: getTypeString(schema),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create-from-prompt.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create-from-prompt.jsonindex bb0574738bff..cc4c4a0a2251 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create-from-prompt.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create-from-prompt.json@@ -3,6 +3,7 @@"properties": {"description": {"description": "Optional experiment description.",+ "maxLength": 3000,"type": "string"},"feature_flag_key": {diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 1c59ed32af3e..78d810f87a1d 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -1384,6 +1384,35 @@ describe('exec tool', () => {expect(parsed.properties.name.hint).toBeUndefined()})+ // The 2026-08 rejections on over-long experiment descriptions came from+ // exec-mode agents that had no way to see the 3,000-character cap: the+ // generated schema carries `max(3000)`, but the summary the bare `schema`+ // view always returns dropped every scalar constraint.+ it.each(['experiment-create', 'experiment-update'])(+ 'keeps the description cap in the bare schema view and in info for %s',+ async (name) => {+ const base = GENERATED_TOOL_MAP[name]!()+ const exec = createExec([makeMockTool({ name, schema: base.schema })])++ const bare = JSON.parse((await exec.handler(mockContext, { command: `schema ${name}` })) as string)+ expect(bare.properties.description).toMatchObject({ type: 'string', maxLength: 3000 })++ // `info` summarizes only because these schemas overflow TOKEN_CHAR_LIMIT;+ // the raw schema would carry `$schema` and nest the cap inside `anyOf`.+ const info = JSON.parse((await exec.handler(mockContext, { command: `info --json ${name}` })) as string)+ expect(info.inputSchema.$schema).toBeUndefined()+ expect(info.inputSchema.properties.description).toMatchObject({ maxLength: 3000 })+ }+ )++ // The cap is also stated in prose on all three description-taking tools, so an+ // agent that reads only the tool description learns it without opening the+ // schema. Pinned on `experiment-create-from-prompt`, the one whose schema the+ // constraint assertions above do not cover.+ it('states the description cap in prose for experiment-create-from-prompt', () => {+ expect(getToolDefinition('experiment-create-from-prompt').description).toContain('3,000 characters')+ })+it('does not attach a drill-down directive when no field carries a hint', async () => {const tool = makeMockTool({schema: z.object({ name: z.string(), count: z.number() }),diff --git a/services/mcp/tests/unit/schema-utils.test.ts b/services/mcp/tests/unit/schema-utils.test.tsindex 7c43b8f5cf64..39c3e0a3ab28 100644--- a/services/mcp/tests/unit/schema-utils.test.ts+++ b/services/mcp/tests/unit/schema-utils.test.ts@@ -666,4 +666,154 @@ describe('schema-utils', () => {expect(TOKEN_CHAR_LIMIT).toBe(48_000)})})++ describe('scalar constraints', () => {+ // The exec `info` summary is the only schema an exec-mode agent sees. Dropping+ // the length cap here meant the agent learned about it from the rejection.+ it('keeps length, range, pattern and format constraints on object properties', () => {+ const schema = {+ type: 'object',+ properties: {+ description: { type: 'string', maxLength: 3000 },+ name: { type: 'string', minLength: 1, pattern: '^[a-z-]+$' },+ start: { type: 'string', format: 'date-time' },+ rollout: { type: 'integer', minimum: 0, maximum: 100 },+ },+ }++ const result = summarizeSchema(schema, 'my-tool')++ expect(result.properties.description).toEqual({ type: 'string', maxLength: 3000 })+ expect(result.properties.name).toEqual({ type: 'string', minLength: 1, pattern: '^[a-z-]+$' })+ expect(result.properties.start).toEqual({ type: 'string', format: 'date-time' })+ expect(result.properties.rollout).toEqual({ type: 'integer', minimum: 0, maximum: 100 })+ })++ // zod renders `.positive()` as `exclusiveMinimum: 0` (e.g. `dashboard-create-tile.id`).+ it('keeps exclusive numeric bounds', () => {+ const schema = {+ type: 'object',+ properties: {+ id: { type: 'integer', exclusiveMinimum: 0 },+ ratio: { type: 'number', exclusiveMaximum: 1 },+ },+ }++ const result = summarizeSchema(schema, 'my-tool')++ expect(result.properties.id).toEqual({ type: 'integer', exclusiveMinimum: 0 })+ expect(result.properties.ratio).toEqual({ type: 'number', exclusiveMaximum: 1 })+ })++ // zod renders `.nullable()` as `anyOf: [scalar, null]`; the experiment tools'+ // `description` arrives this way, and the summary used to say+ // "union of 1 types" with no cap.+ it('summarizes a nullable scalar as the scalar, keeping its constraints and enum', () => {+ const schema = {+ type: 'object',+ properties: {+ description: {+ anyOf: [{ type: 'string', maxLength: 3000 }, { type: 'null' }],+ description: 'Hypothesis',+ },+ stats: { anyOf: [{ type: 'string', enum: ['bayesian', 'frequentist'] }, { type: 'null' }] },+ config: { anyOf: [{ type: 'object', properties: { a: {} } }, { type: 'null' }] },+ },+ }++ const result = summarizeSchema(schema, 'my-tool')++ expect(result.properties.description).toEqual({+ type: 'string',+ maxLength: 3000,+ description: 'Hypothesis',+ })+ expect(result.properties.stats).toEqual({ type: 'string', enum: ['bayesian', 'frequentist'] })+ // A nullable object is still complex and keeps its drill-down hint.+ expect(result.properties.config!.hint).toContain('schema my-tool config')+ })++ // `query-web-overview.conversionGoal` is a nullable union of object variants:+ // `anyOf: [{anyOf: [ActionConversionGoal, CustomEventConversionGoal]}, null]`.+ it('summarizes a nullable object union as the union, with its drill-down hint', () => {+ const schema = {+ type: 'object',+ properties: {+ conversionGoal: {+ anyOf: [+ {+ anyOf: [+ { type: 'object', properties: { actionId: { type: 'integer' } } },+ { type: 'object', properties: { customEventName: { type: 'string' } } },+ ],+ },+ { type: 'null' },+ ],+ description: 'Goal',+ },+ config: { anyOf: [{ type: 'object', properties: { a: {}, b: {} } }, { type: 'null' }] },+ },+ }++ const result = summarizeSchema(schema, 'my-tool')++ expect(result.properties.conversionGoal).toEqual({+ type: 'union of 2 types',+ description: 'Goal',+ hint: expect.stringContaining('schema my-tool conversionGoal'),+ })+ expect(result.properties.config).toMatchObject({ type: 'object', fields: ['a', 'b'] })+ })++ it('keeps constraints on a leaf schema summarized on its own', () => {+ const result = summarizeSchema({ type: 'string', maxLength: 400 }, 'my-tool')++ expect(result).toMatchObject({ type: 'string', maxLength: 400 })+ })++ // zod puts a field's `default` (and `description`) on the nullable wrapper,+ // not on the variant. `endpoint-run.refresh` is one: `{default: "cache",+ // anyOf: [{type: "string", enum: [...]}, {type: "null"}]}`.+ it('keeps a default that sits on the nullable wrapper, in a property and in a drill-down', () => {+ const refresh = {+ default: 'cache',+ anyOf: [{ type: 'string', enum: ['cache', 'force', 'direct'] }, { type: 'null' }],+ }++ expect(summarizeSchema({ type: 'object', properties: { refresh } }, 'my-tool').properties.refresh).toEqual({+ type: 'string',+ enum: ['cache', 'force', 'direct'],+ default: 'cache',+ })+ // `schema <tool> refresh` summarizes the wrapper on its own.+ expect(summarizeSchema(refresh, 'my-tool')).toMatchObject({+ type: 'string',+ enum: ['cache', 'force', 'direct'],+ default: 'cache',+ })+ })++ // zod's ISO date-time `pattern` is a 310-character regex the agent cannot+ // act on, and it rides on 85 fields; `format` says the same in a word.+ it('drops a pattern that has a format or is too long to read, keeps a short one', () => {+ const schema = {+ type: 'object',+ properties: {+ at: {+ type: 'string',+ format: 'date-time',+ pattern: '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26])-02-29)',+ },+ long: { type: 'string', pattern: 'x'.repeat(81) },+ slug: { type: 'string', pattern: '^[a-z-]+$' },+ },+ }++ const result = summarizeSchema(schema, 'my-tool')++ expect(result.properties.at).toEqual({ type: 'string', format: 'date-time' })+ expect(result.properties.long).toEqual({ type: 'string' })+ expect(result.properties.slug).toEqual({ type: 'string', pattern: '^[a-z-]+$' })+ })+ })})