Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp): name the successor when a flag-gated exec tool is called (#95940)

posthog[bot]dfe0ff9199b0
diff --git a/products/mcp_analytics/backend/failure_classification.py b/products/mcp_analytics/backend/failure_classification.py
index bad42ef9d81b..15d50aa6a508 100644
--- a/products/mcp_analytics/backend/failure_classification.py
+++ b/products/mcp_analytics/backend/failure_classification.py
@@ -36,6 +36,7 @@ class FailureClass(StrEnum):
INPUT_SCHEMA_MISMATCH = "input_schema_mismatch"
OUTPUT_SCHEMA_VIOLATION = "output_schema_violation"
UNKNOWN_TOOL = "unknown_tool"
+ GATED_TOOL = "gated_tool"
TIMEOUT = "timeout"
UPSTREAM_5XX = "upstream_5xx"
TRANSPORT_FAILURE = "transport_failure"
@@ -90,6 +91,9 @@ classes:
- output_schema_violation: the server's own response violates its declared output schema — \
"Output validation error: invalid structured content"
- unknown_tool: a tool that doesn't exist was called — "Unknown tool: <name>", JSON-RPC -32601
+- gated_tool: the tool exists but this connection cannot see it, so the message names a \
+successor or says the tool is not enabled — "is retired on this PostHog connection. Use <name> \
+instead", "exists, but it is not enabled on this PostHog connection"
- timeout: the operation ran out of time — "timed out after 45s"
- upstream_5xx: a dependency behind the server failed — "API request failed: 503"
- transport_failure: network-level failure — "fetch failed", "connection reset"
@@ -123,12 +127,15 @@ business-conditional.
7. Language is irrelevant: a translated message classifies the same as its English twin.
8. A field's NAME never picks the class ("timeout seconds field must not be greater than 25" is \
input_schema_mismatch, not timeout).
-9. If the message carries an upsell anywhere ("here are your options", plan limits), \
+9. gated_tool vs unknown_tool: the message says the tool exists but is not enabled, or names a \
+replacement = gated_tool. It says the name is unknown = unknown_tool.
+10. If the message carries an upsell anywhere ("here are your options", plan limits), \
entitlement_gap wins. If genuinely no cause is recoverable, internal_error — never guess.
Each input line is numbered. Return exactly one classification per input line, in the same order, \
as JSON of exactly this shape:
-{{"classifications": [{{"line_number": 1, "failure_class": "<one of the 14 class names>"}}, ...]}}"""
+{{"classifications": [{{"line_number": 1, "failure_class": "<one of the {len(FAILURE_CLASSES)} class \
+names>"}}, ...]}}"""
# The LLM reads the raw representative message, never the normalized fingerprint: normalization
# strips numbers, so the status and JSON-RPC codes the boundary rules pivot on (429, 403, -32601)
diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yaml
index f64e53c1ac18..0e595a08fb9c 100644
--- a/products/notebooks/mcp/tools.yaml
+++ b/products/notebooks/mcp/tools.yaml
@@ -109,6 +109,8 @@ tools:
- _create_in_folder
feature_flag: revamped-py-notebooks
feature_flag_behavior: disable
+ superseded_by:
+ - notebooks-create-markdown
notebooks-destroy:
operation: notebooks_destroy
enabled: true
@@ -287,6 +289,8 @@ tools:
- notebook_short_id
feature_flag: notebooks-collaboration
feature_flag_behavior: disable
+ superseded_by:
+ - notebook-edit
notebooks-recording-comments-retrieve:
operation: notebooks_recording_comments_retrieve
enabled: false
@@ -321,6 +325,8 @@ tools:
- notebook_short_id
feature_flag: revamped-py-notebooks
feature_flag_behavior: disable
+ superseded_by:
+ - notebooks-get
notebooks-run-cell:
operation: notebooks_sql_v2_run_create
enabled: false
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 75ae0993f01a..1f0cc910201e 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -46,6 +46,8 @@ tools:
description: ID of the channel whose instructions to read.
feature_flag: context-layer
feature_flag_behavior: disable
+ superseded_by:
+ - context-wiki-page-retrieve
channel-instructions-update:
operation: task_channels_instructions_update
enabled: true
@@ -67,6 +69,8 @@ tools:
input_schema: ChannelInstructionsBaseVersionSchema
feature_flag: context-layer
feature_flag_behavior: disable
+ superseded_by:
+ - context-wiki-page-update
channel-list:
operation: task_channels_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 6e7fba4a7e68..b34e27995632 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1666,7 +1666,8 @@
"readOnlyHint": true
},
"feature_flag": "context-layer",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["context-wiki-page-retrieve"]
},
"channel-instructions-update": {
"description": "Publish a complete replacement for a channel's CONTEXT.md. Read the current version with channel-instructions-retrieve first. Pass its version as base_version. This guard returns a conflict if another update changes the document.",
@@ -1682,7 +1683,8 @@
"readOnlyHint": false
},
"feature_flag": "context-layer",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["context-wiki-page-update"]
},
"channel-list": {
"description": "List the project's channels (public channels plus the requester's personal #me channel). Use this to resolve a channel id from its name before creating or listing canvases or reading instructions. A project can hold hundreds of channels, so pass `limit` (with `offset`) to read one page: the paged response carries `count` and `next`, and without `limit` you get every channel in one array.",
@@ -8056,7 +8058,8 @@
"readOnlyHint": false
},
"feature_flag": "revamped-py-notebooks",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["notebooks-create-markdown"]
},
"notebooks-destroy": {
"description": "Delete a notebook by short_id. The notebook will be soft-deleted and no longer appear in lists.",
@@ -8130,7 +8133,8 @@
"readOnlyHint": false
},
"feature_flag": "notebooks-collaboration",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["notebook-edit"]
},
"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). 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.",
@@ -8146,7 +8150,8 @@
"readOnlyHint": true
},
"feature_flag": "revamped-py-notebooks",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["notebooks-get"]
},
"notebooks-run-cell-interrupt": {
"description": "Stop a running cell. Idempotent — interrupting an already-finished run returns its outcome unchanged. The stdout/stderr captured before the stop still arrive through notebooks-run-cell-result.",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 8758207b0583..d658da8bb250 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1681,7 +1681,8 @@
"readOnlyHint": true
},
"feature_flag": "context-layer",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["context-wiki-page-retrieve"]
},
"channel-instructions-update": {
"description": "Publish a complete replacement for a channel's CONTEXT.md. Read the current version with channel-instructions-retrieve first. Pass its version as base_version. This guard returns a conflict if another update changes the document.",
@@ -1697,7 +1698,8 @@
"readOnlyHint": false
},
"feature_flag": "context-layer",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["context-wiki-page-update"]
},
"channel-list": {
"description": "List the project's channels (public channels plus the requester's personal #me channel). Use this to resolve a channel id from its name before creating or listing canvases or reading instructions. A project can hold hundreds of channels, so pass `limit` (with `offset`) to read one page: the paged response carries `count` and `next`, and without `limit` you get every channel in one array.",
@@ -8415,6 +8417,8 @@
"required_scopes": ["notebook:write"],
"feature_flag": "notebooks-collaboration",
"hidden_when_flag_on": "revamped-py-notebooks",
+ "superseded_by": ["notebooks-update-cell", "notebooks-add-cell"],
+ "redirect_hint": "Read the notebook with notebooks-get first: the revamped notebooks are cell-based, so an edit targets one cell.",
"annotations": {
"destructiveHint": false,
"idempotentHint": false,
@@ -8481,7 +8485,8 @@
"readOnlyHint": false
},
"feature_flag": "revamped-py-notebooks",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["notebooks-create-markdown"]
},
"notebooks-create-markdown": {
"description": "Create a notebook for deep, step-by-step data analysis: query PostHog and connected data warehouse data with SQL (HogQL), or analyze with Python code. SQL and Python cells can also read and query dataframes fetched or created by upstream cells in the notebook. Run a cell, read its result, decide the next step; add markdown cells to explain and summarize findings, and embed saved insights. Give it a title and optionally an initial markdown body. Returns the notebook_id to use with notebooks-add-cell. This is the default artifact for an analysis with a narrative — a deep dive, a one-off investigation, a 'why did X change' — where the reader needs the reasoning and caveats, not just a number; a dashboard is for metrics tracked repeatedly over time. Reach for a notebook without being asked whenever the work needs Python, so the code, its output, and its errors are visible to the user next to the result instead of running where they can't see them.",
@@ -8585,7 +8590,8 @@
"readOnlyHint": false
},
"feature_flag": "notebooks-collaboration",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["notebook-edit"]
},
"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). 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.",
@@ -8601,7 +8607,8 @@
"readOnlyHint": true
},
"feature_flag": "revamped-py-notebooks",
- "feature_flag_behavior": "disable"
+ "feature_flag_behavior": "disable",
+ "superseded_by": ["notebooks-get"]
},
"notebooks-run-cell-interrupt": {
"description": "Stop a running cell. Idempotent — interrupting an already-finished run returns its outcome unchanged. The stdout/stderr captured before the stop still arrive through notebooks-run-cell-result.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 3edaa0599152..a65ec37ddc07 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -279,6 +279,8 @@
"required_scopes": ["notebook:write"],
"feature_flag": "notebooks-collaboration",
"hidden_when_flag_on": "revamped-py-notebooks",
+ "superseded_by": ["notebooks-update-cell", "notebooks-add-cell"],
+ "redirect_hint": "Read the notebook with notebooks-get first: the revamped notebooks are cell-based, so an edit targets one cell.",
"annotations": {
"destructiveHint": false,
"idempotentHint": false,
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index b6fae8e076b2..c554dd223823 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -1970,6 +1970,9 @@ function generateDefinitionsJson(
const featureEntitlement = toolConfig.feature_entitlement ?? category.feature_entitlement
const featureFlagBehavior = toolConfig.feature_flag_behavior ?? category.feature_flag_behavior
const featureFlagVariant = toolConfig.feature_flag_variant ?? category.feature_flag_variant
+ // Successors are per-tool: a category gate says what retires a tool, never what replaces it.
+ const supersededBy = toolConfig.superseded_by
+ const redirectHint = toolConfig.redirect_hint
if (toolConfig.confirmed_action) {
// Two-tool typed-confirm paradigm: emit `<name>-prepare` and
@@ -1998,6 +2001,8 @@ function generateDefinitionsJson(
...(featureEntitlement ? { feature_entitlement: featureEntitlement } : {}),
...(featureFlagBehavior ? { feature_flag_behavior: featureFlagBehavior } : {}),
...(featureFlagVariant ? { feature_flag_variant: featureFlagVariant } : {}),
+ ...(supersededBy?.length ? { superseded_by: supersededBy } : {}),
+ ...(redirectHint ? { redirect_hint: redirectHint } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
definitions[`${name}-execute`] = {
@@ -2022,6 +2027,8 @@ function generateDefinitionsJson(
...(featureEntitlement ? { feature_entitlement: featureEntitlement } : {}),
...(featureFlagBehavior ? { feature_flag_behavior: featureFlagBehavior } : {}),
...(featureFlagVariant ? { feature_flag_variant: featureFlagVariant } : {}),
+ ...(supersededBy?.length ? { superseded_by: supersededBy } : {}),
+ ...(redirectHint ? { redirect_hint: redirectHint } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
} else {
@@ -2043,6 +2050,8 @@ function generateDefinitionsJson(
...(featureEntitlement ? { feature_entitlement: featureEntitlement } : {}),
...(featureFlagBehavior ? { feature_flag_behavior: featureFlagBehavior } : {}),
...(featureFlagVariant ? { feature_flag_variant: featureFlagVariant } : {}),
+ ...(supersededBy?.length ? { superseded_by: supersededBy } : {}),
+ ...(redirectHint ? { redirect_hint: redirectHint } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
}
@@ -2072,6 +2081,8 @@ function generateDefinitionsJson(
...(wrapperConfig.feature_flag_variant
? { feature_flag_variant: wrapperConfig.feature_flag_variant }
: {}),
+ ...(wrapperConfig.superseded_by?.length ? { superseded_by: wrapperConfig.superseded_by } : {}),
+ ...(wrapperConfig.redirect_hint ? { redirect_hint: wrapperConfig.redirect_hint } : {}),
...(wrapperConfig.system_prompt_hint ? { system_prompt_hint: wrapperConfig.system_prompt_hint } : {}),
}
}
@@ -2247,6 +2258,8 @@ function generateQueryWrapperDefinitionsJson(
...(toolConfig.feature_entitlement ? { feature_entitlement: toolConfig.feature_entitlement } : {}),
...(toolConfig.feature_flag_behavior ? { feature_flag_behavior: toolConfig.feature_flag_behavior } : {}),
...(toolConfig.feature_flag_variant ? { feature_flag_variant: toolConfig.feature_flag_variant } : {}),
+ ...(toolConfig.superseded_by?.length ? { superseded_by: toolConfig.superseded_by } : {}),
+ ...(toolConfig.redirect_hint ? { redirect_hint: toolConfig.redirect_hint } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
}
diff --git a/services/mcp/scripts/lint-tool-names.ts b/services/mcp/scripts/lint-tool-names.ts
index 8bf9f0e5b0d7..c357f7543d15 100644
--- a/services/mcp/scripts/lint-tool-names.ts
+++ b/services/mcp/scripts/lint-tool-names.ts
@@ -23,6 +23,10 @@
* `_posthogUrl` link on tool results), checked against the generated app-url manifest
* plus the SettingSectionId union. Pointing it at an API path is the easy mistake.
*
+ * superseded_by: each redirect target must name a tool that exists, and never the tool
+ * declaring it. Exec drops a target it cannot resolve, so a stale name costs the retired
+ * tool its redirect and leaves no trace.
+ *
* Usage:
* pnpm --filter=@posthog/mcp lint-tool-names
*/
@@ -45,6 +49,29 @@ const DEFINITIONS_DIR = path.resolve(MCP_ROOT, 'definitions')
const PRODUCTS_DIR = path.resolve(REPO_ROOT, 'products')
const SCHEMA_DIR = path.resolve(MCP_ROOT, 'schema')
+// A tool config as this lint reads it: enough to check the name and the redirect it declares.
+type LintedToolConfig = { enabled: boolean; superseded_by?: string[] }
+
+// A declared redirect, kept with the source that carries it.
+type SupersededDeclaration = { source: string; successors: string[] }
+
+// First source wins, so a YAML-declared redirect reports against the editable YAML instead of the
+// generated JSON that copies it.
+function recordSuperseded(
+ superseded: Map<string, SupersededDeclaration>,
+ tool: string,
+ successors: unknown,
+ source: string
+): void {
+ if (!Array.isArray(successors) || superseded.has(tool)) {
+ return
+ }
+ superseded.set(tool, {
+ source,
+ successors: successors.filter((name): name is string => typeof name === 'string'),
+ })
+}
+
function validateToolName(name: string, source: string, violations: Violation[]): void {
if (name.length > MAX_TOOL_NAME_LENGTH) {
violations.push({ source, tool: name, reason: `${name.length} chars (max ${MAX_TOOL_NAME_LENGTH})` })
@@ -58,7 +85,11 @@ function validateToolName(name: string, source: string, violations: Violation[])
}
}
-function validateYamlDefinitions(violations: Violation[], knownToolNames: Set<string>): boolean {
+function validateYamlDefinitions(
+ violations: Violation[],
+ knownToolNames: Set<string>,
+ superseded: Map<string, SupersededDeclaration>
+): boolean {
const definitions = discoverDefinitions({ definitionsDir: DEFINITIONS_DIR, productsDir: PRODUCTS_DIR })
let hasErrors = false
@@ -79,14 +110,15 @@ function validateYamlDefinitions(violations: Violation[], knownToolNames: Set<st
continue
}
const tools = isQueryWrappers
- ? (result.data as { wrappers: Record<string, { enabled: boolean }> }).wrappers
- : (result.data as { tools: Record<string, { enabled: boolean }> }).tools
+ ? (result.data as { wrappers: Record<string, LintedToolConfig> }).wrappers
+ : (result.data as { tools: Record<string, LintedToolConfig> }).tools
for (const [name, config] of Object.entries(tools)) {
if (!config.enabled) {
continue
}
knownToolNames.add(name)
validateToolName(name, label, violations)
+ recordSuperseded(superseded, name, config.superseded_by, label)
}
}
@@ -221,7 +253,45 @@ function validateUrlPrefixes(violations: Violation[]): void {
}
}
-function validateJsonDefinitions(fileName: string, violations: Violation[], knownToolNames: Set<string>): boolean {
+/**
+ * `superseded_by` names the tools that took over a retired tool's job, and exec resolves those
+ * names against the live catalog before it names any of them. A name that no longer resolves is
+ * dropped there, so the retired tool falls back to the generic "not enabled" message and its
+ * redirect goes quiet. A self-reference never resolves either: exec reaches the redirect only when
+ * the declaring tool is itself absent from the catalog.
+ */
+function validateSupersededBy(
+ superseded: Map<string, SupersededDeclaration>,
+ knownToolNames: Set<string>,
+ violations: Violation[]
+): void {
+ for (const [tool, { source, successors }] of superseded) {
+ for (const successor of successors) {
+ if (successor === tool) {
+ violations.push({
+ source,
+ tool: `superseded_by on ${tool}`,
+ reason: 'a tool cannot supersede itself (name the tool that took over its job)',
+ })
+ continue
+ }
+ if (!knownToolNames.has(successor)) {
+ violations.push({
+ source,
+ tool: `superseded_by on ${tool}: ${successor || '(empty)'}`,
+ reason: 'no tool by that name (point the redirect at the current tool name)',
+ })
+ }
+ }
+ }
+}
+
+function validateJsonDefinitions(
+ fileName: string,
+ violations: Violation[],
+ knownToolNames: Set<string>,
+ superseded: Map<string, SupersededDeclaration>
+): boolean {
const filePath = path.resolve(SCHEMA_DIR, fileName)
if (!fs.existsSync(filePath)) {
return false
@@ -229,9 +299,10 @@ function validateJsonDefinitions(fileName: string, violations: Violation[], know
const label = path.relative(REPO_ROOT, filePath)
const content = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as Record<string, unknown>
- for (const name of Object.keys(content)) {
+ for (const [name, definition] of Object.entries(content)) {
knownToolNames.add(name)
validateToolName(name, label, violations)
+ recordSuperseded(superseded, name, (definition as { superseded_by?: unknown }).superseded_by, label)
}
return false
}
@@ -329,14 +400,17 @@ function main(): void {
const violations: Violation[] = []
let hasErrors = false
const knownToolNames = new Set<string>()
+ const superseded = new Map<string, SupersededDeclaration>()
- hasErrors = validateYamlDefinitions(violations, knownToolNames) || hasErrors
+ hasErrors = validateYamlDefinitions(violations, knownToolNames, superseded) || hasErrors
validateUrlPrefixes(violations)
for (const jsonFile of ['tool-definitions.json', 'generated-tool-definitions.json']) {
- hasErrors = validateJsonDefinitions(jsonFile, violations, knownToolNames) || hasErrors
+ hasErrors = validateJsonDefinitions(jsonFile, violations, knownToolNames, superseded) || hasErrors
}
+ validateSupersededBy(superseded, knownToolNames, violations)
+
const referenceFindings: ReferenceFinding[] = []
collectToolReferenceFindings(referenceFindings, knownToolNames)
emitReferenceFindings(referenceFindings)
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index f81767875829..d9332086221e 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -175,6 +175,14 @@ export const ToolConfigSchema = z
feature_flag_behavior: z.enum(['enable', 'disable']).optional(),
/** Variant of `feature_flag` to match exactly. Requires `feature_flag` to be set. */
feature_flag_variant: z.string().optional(),
+ /**
+ * Tool names that took over this tool's job. Set it on any tool a gate
+ * retires (`feature_flag_behavior: 'disable'`), so a call to the retired
+ * name reports the successor instead of reading as an unknown tool.
+ */
+ superseded_by: z.array(z.string()).optional(),
+ /** Extra guidance appended to the successor message, for a redirect a bare tool name cannot carry. */
+ redirect_hint: z.string().optional(),
/**
* Response field filtering. Supports dot-path patterns with wildcards (e.g. 'filters.groups.*.key').
* For list endpoints, applied to each item in `results`. `include` and `exclude` are mutually exclusive.
@@ -535,6 +543,14 @@ export const QueryWrapperToolConfigSchema = z
feature_flag_behavior: z.enum(['enable', 'disable']).optional(),
/** Variant of `feature_flag` to match exactly. Requires `feature_flag` to be set. */
feature_flag_variant: z.string().optional(),
+ /**
+ * Tool names that took over this tool's job. Set it on any tool a gate
+ * retires (`feature_flag_behavior: 'disable'`), so a call to the retired
+ * name reports the successor instead of reading as an unknown tool.
+ */
+ superseded_by: z.array(z.string()).optional(),
+ /** Extra guidance appended to the successor message, for a redirect a bare tool name cannot carry. */
+ redirect_hint: z.string().optional(),
})
.strict()
.refine((data) => !(data.description && data.description_file), {
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 456d4f006b4d..200e85b0ccb1 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -13,7 +13,13 @@ import type { RequestProperties } from '@/lib/request-properties'
import { filterStaffOnlyTools } from '@/lib/staff-only-tools'
import type { McpMode } from '@/lib/utils'
import { TASKS_CONTEXT_TOOL_NAMES } from '@/tools/tasksContext'
-import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'
+import {
+ type FlagGatedTool,
+ getFlagGatedTools,
+ getRequiredFeatureFlags,
+ getScopeGatedTools,
+ type ScopeGatedTool,
+} from '@/tools/toolDefinitions'
import type { Context, Tool, Env, ZodObjectAny } from '@/tools/types'
import { McpSessionRedisStore } from './cache/McpSessionRedisStore'
@@ -41,6 +47,7 @@ export interface ResolvedState {
sessionContext: MCPSessionContext | null
allTools: Tool<ZodObjectAny>[]
scopeGatedTools: ScopeGatedTool[]
+ flagGatedTools: FlagGatedTool[]
/**
* Whether the caller's team may reach third-party MCP tools through `exec`.
* Gated on the same flag as the gateway UI — the tools are the gateway's payoff,
@@ -240,6 +247,8 @@ export class RequestStateResolver {
// Scope-gated hints are only consumed by the exec `search` command, which
// only exists in single-exec mode — skip the extra scan otherwise.
const scopeGatedTools = useSingleExec ? getScopeGatedTools(apiKeyScopes, filterOptions) : []
+ // Only exec redirects a call to a gated tool; tools mode just omits it.
+ const flagGatedTools = useSingleExec ? getFlagGatedTools(filterOptions) : []
const [groupTypes, metadata, metadataCompact] = await Promise.all([
cachedProjectId && hasScope(apiKeyScopes, 'group:read')
@@ -261,6 +270,7 @@ export class RequestStateResolver {
sessionContext,
allTools,
scopeGatedTools,
+ flagGatedTools,
gatewayToolsEnabled:
useSingleExec &&
!readOnly &&
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 525d5980f948..0c7fc2973ec9 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -566,6 +566,7 @@ export class ToolExecutor {
{
isInlineExecUiHost: state.clientProfile.isInlineExecUiHost(),
helpCatalog: this.instructionsBuilder.buildExecHelpCatalog(state),
+ flagGatedTools: state.flagGatedTools,
...(state.gatewayToolsEnabled ? { gatewayToolsProvider: () => this.gatewayToolsFor(state) } : {}),
// A verb-only report lands first; `search` then reports again with its query
// and counts. Merge so the richer report wins without losing the verb.
@@ -859,7 +860,10 @@ function execCommandAnalyticsProperties(execArgs: unknown, state: ResolvedState)
}
const { verb, targetTool } = describeExecCommand(
command,
- (name) => state.allTools.some((t) => t.name === name) || state.scopeGatedTools.some((t) => t.name === name)
+ (name) =>
+ state.allTools.some((t) => t.name === name) ||
+ state.scopeGatedTools.some((t) => t.name === name) ||
+ state.flagGatedTools.some((t) => t.name === name)
)
return {
...(verb !== undefined ? { $mcp_exec_verb: verb } : {}),
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.ts
index f3bfe6fd585c..36e50a9bdd92 100644
--- a/services/mcp/src/lib/errors.ts
+++ b/services/mcp/src/lib/errors.ts
@@ -147,6 +147,7 @@ export type ExecCommandErrorReason =
| 'unknown_command'
| 'unknown_tool'
| 'deprecated_tool'
+ | 'gated_tool'
| 'missing_scope'
| 'invalid_json'
| 'usage'
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index f1aaa8d5cb7c..a7c2a9c5becc 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -11,7 +11,7 @@ import { formatResponse } from '@/lib/response'
import type { ExecHelpCatalog } from './exec-help'
import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'
import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'
-import type { ScopeGatedTool } from './toolDefinitions'
+import { getToolDefinitions, type FlagGatedTool, type ScopeGatedTool } from './toolDefinitions'
import {
POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,
POSTHOG_INFORMATIONAL_RESPONSE_KEY,
@@ -134,6 +134,11 @@ export interface ExecToolOptions {
gatewayToolsProvider?: () => Promise<Tool<ZodObjectAny>[]>
/** Reports what the agent asked for, so non-`call` verbs stop being invisible. */
trackCommand?: ExecCommandTracker
+ /**
+ * Tools a feature flag removed from this connection's catalog. Lets a call to
+ * a retired name name its successor instead of reading as an unknown tool.
+ */
+ flagGatedTools?: FlagGatedTool[]
}
function makeExecSchema(commandReference: string): z.ZodObject<{ command: z.ZodString }> {
@@ -321,12 +326,13 @@ export function createExecInnerToolCallResolver(
}
}
-// Tools that were removed from the MCP server — or flag-gated out of the active
-// catalog. When the model attempts to call one that isn't present, surface a
-// targeted redirect to the replacement instead of dumping the full tool catalog.
-// Keep the redirect text editorial — schemas don't carry "use X instead"
-// guidance. A redirect only fires when the tool is absent, so an entry for a
-// conditionally-gated tool is inert whenever that tool is registered.
+// Tools deleted from the MCP server. When the model attempts to call one,
+// surface a targeted redirect to the replacement instead of dumping the full
+// tool catalog. Keep the redirect text editorial — schemas don't carry
+// "use X instead" guidance.
+// A tool a feature flag removed still has a definition, so it declares its own
+// successor through `superseded_by` and is answered by `flagGatedToolMessage`
+// instead of by an entry here.
const DEPRECATED_TOOL_REDIRECTS: Record<string, (allTools: Tool<ZodObjectAny>[]) => string> = {
// Removed in favor of SQL-based schema discovery via `system.information_schema.*`.
'read-data-warehouse-schema': () =>
@@ -747,13 +753,57 @@ function stripOutputFormatProperty(jsonSchema: Record<string, unknown>): Record<
return { ...jsonSchema, properties: rest }
}
-function findTool(tools: Tool<ZodObjectAny>[], scopeGatedTools: ScopeGatedTool[], name: string): Tool<ZodObjectAny> {
+/** A lowercase hyphenated token, the shape every name in the tool catalog takes. */
+const HINT_TOOL_NAME_PATTERN = /[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g
+
+/**
+ * Whether every tool the hint names is one this connection can call. A hint is
+ * free text, so it can name a tool that is behind its own gate here — the second
+ * dead end the successor filter exists to prevent. A hyphenated word the catalog
+ * has no tool for is prose, so it never suppresses the hint.
+ */
+function hintNamesOnlyAvailableTools(hint: string, available: Set<string>): boolean {
+ const definitions = getToolDefinitions()
+ return (hint.match(HINT_TOOL_NAME_PATTERN) ?? []).every(
+ (token) => definitions[token] === undefined || available.has(token)
+ )
+}
+
+/**
+ * Message for a tool a feature flag removed from this connection's catalog.
+ * Names only the successors the catalog can actually serve, because a successor
+ * behind its own gate is no more callable than the tool it replaced. The hint is
+ * held to the same rule. Never names the flag — the agent cannot act on a flag
+ * key, and the key is internal.
+ */
+function flagGatedToolMessage(gated: FlagGatedTool, tools: Tool<ZodObjectAny>[]): string {
+ const available = new Set(tools.map((t) => t.name))
+ const reachable = gated.supersededBy.filter((successor) => available.has(successor))
+ const hint =
+ gated.redirectHint && hintNamesOnlyAvailableTools(gated.redirectHint, available) ? ` ${gated.redirectHint}` : ''
+ if (reachable.length === 0) {
+ return `Tool "${gated.name}" exists, but it is not enabled on this PostHog connection. The capability was not removed. Run "search ${gated.name}" to find an enabled tool for the same job.${hint}`
+ }
+ const successors = reachable.map((successor) => `"${successor}"`).join(' or ')
+ return `Tool "${gated.name}" is retired on this PostHog connection. Use ${successors} instead.${hint}`
+}
+
+function findTool(
+ tools: Tool<ZodObjectAny>[],
+ scopeGatedTools: ScopeGatedTool[],
+ flagGatedTools: FlagGatedTool[],
+ name: string
+): Tool<ZodObjectAny> {
const tool = tools.find((t) => t.name === name)
if (!tool) {
const redirect = DEPRECATED_TOOL_REDIRECTS[name]
if (redirect) {
throw new ExecCommandError(redirect(tools), 'deprecated_tool')
}
+ const flagGatedTool = flagGatedTools.find((candidate) => candidate.name === name)
+ if (flagGatedTool) {
+ throw new ExecCommandError(flagGatedToolMessage(flagGatedTool, tools), 'gated_tool')
+ }
const scopeGatedTool = scopeGatedTools.find((candidate) => candidate.name === name)
if (scopeGatedTool) {
throw new ExecCommandError(
@@ -780,6 +830,7 @@ export function createExecTool(
options: ExecToolOptions = {}
): Tool<ExecSchema> {
const ExecSchema = makeExecSchema(commandReference)
+ const flagGatedTools = options.flagGatedTools ?? []
return {
name: 'exec',
@@ -961,7 +1012,7 @@ export function createExecTool(
if (!infoArgs) {
throw new ExecCommandError('Usage: info [--json] <tool_name>', 'usage')
}
- const tool = findTool(await resolveTools(), scopeGatedTools, infoArgs)
+ const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, infoArgs)
// `io: 'input'` mirrors the advertised `tools/list` schema and the executor's
// validation: fields with a Zod `.default()` (e.g. a query `kind` discriminator)
// are optional and auto-filled. The default `io: 'output'` would list them as
@@ -1006,7 +1057,7 @@ export function createExecTool(
throw new ExecCommandError('Usage: schema <tool_name> [field_path]', 'usage')
}
const { verb: schemaToolName, rest: fieldPath } = parseCommand(rest)
- const schemaTool = findTool(await resolveTools(), scopeGatedTools, schemaToolName)
+ const schemaTool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, schemaToolName)
// See the `info` command: `io: 'input'` keeps this in sync with the advertised
// schema and validation, so `.default()` fields aren't shown as required.
const fullJsonSchema =
@@ -1063,7 +1114,7 @@ export function createExecTool(
throw new ExecCommandError('Usage: call [--json] [--confirm] <tool_name> <json_input>', 'usage')
}
const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)
- const tool = findTool(await resolveTools(), scopeGatedTools, toolName)
+ const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, toolName)
if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {
throw new ExecCommandError(
`Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`,
diff --git a/services/mcp/src/tools/toolDefinitions.ts b/services/mcp/src/tools/toolDefinitions.ts
index 441dca32c80f..e0335ff038c5 100644
--- a/services/mcp/src/tools/toolDefinitions.ts
+++ b/services/mcp/src/tools/toolDefinitions.ts
@@ -30,6 +30,14 @@ export const ToolDefinitionSchema = z
* flag while the tool keeps its own gating flag.
*/
hidden_when_flag_on: z.string().optional(),
+ /**
+ * Tool names that took over this tool's job. Declared next to the gate
+ * that retires the tool, so a call to the retired name can name its
+ * successor instead of reporting the name as unknown.
+ */
+ superseded_by: z.array(z.string()).optional(),
+ /** Extra guidance appended to the successor message, for a redirect a bare tool name cannot carry. */
+ redirect_hint: z.string().optional(),
/**
* AvailableFeature the org's plan must include for this tool to be
* advertised (e.g. `'audit_logs'`), matching the backend's
@@ -269,7 +277,11 @@ export function toolPassesEntitlementGate(
return availableFeatures.includes(definition.feature_entitlement)
}
-export function getToolsForFeatures(options?: ToolFilterOptions): string[] {
+/**
+ * Every catalog filter, with the flag gate optional: {@link getToolsForFeatures}
+ * drops what the flags hide, {@link getFlagGatedTools} keeps exactly that set.
+ */
+function filterToolEntries(options: ToolFilterOptions | undefined, applyFlagGate: boolean): [string, ToolDefinition][] {
const { features, tools, readOnly, aiConsentGiven, featureFlags, scopedTeams, availableFeatures, isCloud } =
options || {}
const toolDefinitions = getToolDefinitions()
@@ -310,7 +322,9 @@ export function getToolsForFeatures(options?: ToolFilterOptions): string[] {
}
// Filter by feature flags — see {@link toolPassesFlagGate} for the predicate.
- entries = entries.filter(([_, definition]) => toolPassesFlagGate(definition, featureFlags))
+ if (applyFlagGate) {
+ entries = entries.filter(([_, definition]) => toolPassesFlagGate(definition, featureFlags))
+ }
// Filter by billing entitlement — see {@link toolPassesEntitlementGate}.
entries = entries.filter(([_, definition]) => toolPassesEntitlementGate(definition, availableFeatures, isCloud))
@@ -323,7 +337,49 @@ export function getToolsForFeatures(options?: ToolFilterOptions): string[] {
)
}
- return entries.map(([toolName, _]) => toolName)
+ return entries
+}
+
+export function getToolsForFeatures(options?: ToolFilterOptions): string[] {
+ return filterToolEntries(options, true).map(([toolName, _]) => toolName)
+}
+
+export interface FlagGatedTool {
+ name: string
+ /** Tool names the definition declares as this tool's successors, in the order it lists them. */
+ supersededBy: string[]
+ /** Free-text guidance the definition adds to the redirect. */
+ redirectHint?: string
+}
+
+/**
+ * Tools a feature flag removed from the active catalog, while every other filter
+ * kept them. The exec dispatcher reads this so a call to a retired name reports
+ * the successor, or reports that the tool is not enabled — never that the name
+ * is unknown, which reads to an agent as a removed capability.
+ *
+ * Staff-only tools are left out for the same reason {@link getScopeGatedTools}
+ * leaves them out: the hint would advertise a staff surface to a customer.
+ */
+export function getFlagGatedTools(options?: ToolFilterOptions): FlagGatedTool[] {
+ const excluded = new Set(options?.excludeTools ?? [])
+ const gated: FlagGatedTool[] = []
+
+ for (const [name, definition] of filterToolEntries(options, false)) {
+ if (excluded.has(name) || toolPassesFlagGate(definition, options?.featureFlags)) {
+ continue
+ }
+ if (isStaffOnlyTool(definition.required_scopes ?? [])) {
+ continue
+ }
+ gated.push({
+ name,
+ supersededBy: definition.superseded_by ?? [],
+ ...(definition.redirect_hint ? { redirectHint: definition.redirect_hint } : {}),
+ })
+ }
+
+ return gated
}
export interface ScopeGatedTool {
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index 417e1c043c37..44ab717ddc57 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -63,6 +63,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {
},
allTools: [],
scopeGatedTools: [],
+ flagGatedTools: [],
gatewayToolsEnabled: false,
distinctId: 'distinct-id',
renderUiEnabled: false,
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index c04509cc5521..875bc86cbd43 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -68,6 +68,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ flagGatedTools: [],
gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index 800bfc2e8097..f7b665652333 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -102,6 +102,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ flagGatedTools: [],
gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
@@ -502,6 +503,25 @@ describe('ToolExecutor metrics', () => {
expect(call?.[4]).toMatchObject(expected)
})
+ // A name a feature flag retired is one we own, so it is recordable like any
+ // other. Recorded as unrecognized instead, the `gated_tool` class counts the
+ // wasted round trips without naming the rename that caused them.
+ it('stamps the retired tool a flag gate removed, not the unrecognized sentinel', async () => {
+ const state = execState()
+ // What the resolver produces with the gate on: the flag filter drops the
+ // tool from the catalog, and `getFlagGatedTools` picks it up.
+ state.allTools = state.allTools.filter((tool) => tool.name !== 'notebooks-create')
+ state.flagGatedTools = [{ name: 'notebooks-create', supersededBy: ['notebooks-create-markdown'] }]
+
+ await executor.handleToolCall({ name: 'exec', arguments: { command: 'call notebooks-create {}' } }, state)
+
+ expect(mockTrackToolCall.mock.calls.at(-1)?.[4]).toMatchObject({
+ $mcp_exec_verb: 'call',
+ $mcp_exec_target_tool: 'notebooks-create',
+ $mcp_error_code: 'gated_tool',
+ })
+ })
+
it('emits inner tool name for counter and duration on inner tool call', async () => {
await executor.handleToolCall(
{ name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index c0769819291c..43364781a7c8 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -73,6 +73,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ flagGatedTools: [],
gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 21df17069824..f44c8ed4a15e 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -68,6 +68,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ flagGatedTools: [],
gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
diff --git a/services/mcp/tests/integration/skill-analytics.integration.test.ts b/services/mcp/tests/integration/skill-analytics.integration.test.ts
index 0658b6a92478..931fb0d6cca4 100644
--- a/services/mcp/tests/integration/skill-analytics.integration.test.ts
+++ b/services/mcp/tests/integration/skill-analytics.integration.test.ts
@@ -126,6 +126,7 @@ describe.skipIf(!API_TOKEN)('skill read reaches PostHog with $mcp_skill_name', (
sessionContext: null,
allTools: tools,
scopeGatedTools: [],
+ flagGatedTools: [],
gatewayToolsEnabled: false,
distinctId: 'e2e-distinct-id',
renderUiEnabled: false,
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 76173a76e786..c6f9ce644b32 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -1177,6 +1177,77 @@ describe('exec tool', () => {
})
})
+ describe('flag-gated tool redirects', () => {
+ const notebooksCreateMarkdown = makeMockTool({ name: 'notebooks-create-markdown' })
+
+ it('names the successor a flag retired the tool for', async () => {
+ const exec = createExec([notebooksCreateMarkdown], undefined, {
+ flagGatedTools: [{ name: 'notebooks-create', supersededBy: ['notebooks-create-markdown'] }],
+ })
+ await expect(exec.handler(mockContext, { command: 'call notebooks-create {}' })).rejects.toThrow(
+ /retired[\s\S]*notebooks-create-markdown/
+ )
+ await expect(exec.handler(mockContext, { command: 'info notebooks-create' })).rejects.toThrow(
+ /notebooks-create-markdown/
+ )
+ })
+
+ it('reports a gated tool with no successor as not enabled, not as unknown', async () => {
+ const exec = createExec([notebooksCreateMarkdown], undefined, {
+ flagGatedTools: [{ name: 'notebooks-add-cell', supersededBy: [] }],
+ })
+ await expect(exec.handler(mockContext, { command: 'call notebooks-add-cell {}' })).rejects.toThrow(
+ /is not enabled on this PostHog connection/
+ )
+ await expect(exec.handler(mockContext, { command: 'call notebooks-add-cell {}' })).rejects.not.toThrow(
+ /Unknown tool/
+ )
+ })
+
+ // A successor behind its own gate is no more callable than the tool it replaced,
+ // so pointing at it would send the agent on a second dead-end round trip.
+ it('falls back to the not-enabled message when no declared successor is registered', async () => {
+ const exec = createExec([makeMockTool()], undefined, {
+ flagGatedTools: [{ name: 'notebooks-create', supersededBy: ['notebooks-create-markdown'] }],
+ })
+ await expect(exec.handler(mockContext, { command: 'call notebooks-create {}' })).rejects.toThrow(
+ /is not enabled on this PostHog connection/
+ )
+ })
+
+ // The hint is free text, so an author can name a tool that is behind its own
+ // gate here. Held to the same rule as the successors, or the redirect trades
+ // one dead end for another.
+ it.each<[string, string, boolean]>([
+ ['a tool the catalog serves', 'Pair it with notebooks-create-markdown for the new shape.', true],
+ ['a tool this connection cannot serve', 'Read the notebook with notebooks-get first.', false],
+ ['a hyphenated word that is not a tool', 'The revamped notebooks are cell-based.', true],
+ ])('holds a hint naming %s to the same reachability rule', async (_case, redirectHint, kept) => {
+ const exec = createExec([notebooksCreateMarkdown], undefined, {
+ flagGatedTools: [
+ { name: 'notebooks-create', supersededBy: ['notebooks-create-markdown'], redirectHint },
+ ],
+ })
+
+ const message = await exec.handler(mockContext, { command: 'call notebooks-create {}' }).then(
+ () => '',
+ (error: Error) => error.message
+ )
+
+ expect(message).toContain('is retired on this PostHog connection')
+ expect(message.includes(redirectHint)).toBe(kept)
+ })
+
+ it('still reports a name we do not own as unknown', async () => {
+ const exec = createExec([notebooksCreateMarkdown], undefined, {
+ flagGatedTools: [{ name: 'notebooks-create', supersededBy: ['notebooks-create-markdown'] }],
+ })
+ await expect(exec.handler(mockContext, { command: 'call not-a-posthog-tool {}' })).rejects.toThrow(
+ /Unknown tool[\s\S]*search not-a-posthog-tool/
+ )
+ })
+ })
+
describe('deprecated tool redirects', () => {
it.each([
['read-data-warehouse-schema', 'execute-sql'],
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 3ebc81a9088b..6ad06645cc85 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -7,6 +7,7 @@ import { SessionManager } from '@/lib/SessionManager'
import { getToolsFromContext } from '@/tools'
import {
getAdvertisedOAuthScopes,
+ getFlagGatedTools,
getToolDefinitions,
getRequiredFeatureFlags,
getToolsForFeatures,
@@ -1071,6 +1072,41 @@ describe('Tool Filtering - Feature Flags', () => {
})
})
+describe('getFlagGatedTools', () => {
+ it('reports a retired tool with the successor its definition declares', () => {
+ const gated = getFlagGatedTools({ featureFlags: { 'revamped-py-notebooks': true } })
+
+ expect(gated.find((tool) => tool.name === 'notebooks-create')?.supersededBy).toEqual([
+ 'notebooks-create-markdown',
+ ])
+ })
+
+ it('leaves out a tool the flags keep in the catalog', () => {
+ const gated = getFlagGatedTools({ featureFlags: { 'revamped-py-notebooks': false } })
+
+ expect(gated.map((tool) => tool.name)).not.toContain('notebooks-create')
+ })
+
+ it('reports a tool an unset flag never enabled, so a caller learns it exists', () => {
+ const gated = getFlagGatedTools({ featureFlags: {} })
+
+ const entry = gated.find((tool) => tool.name === 'notebooks-add-cell')
+ expect(entry).not.toBeUndefined()
+ expect(entry?.supersededBy).toEqual([])
+ })
+
+ // The successor lives on the definition next to the gate that retires the tool.
+ // Without it, a call to the retired name reads to an agent as a removed capability.
+ it('every retired tool declares a successor or says why it has none', () => {
+ const undeclared = Object.entries(getToolDefinitions())
+ .filter(([_, def]) => def.feature_flag_behavior === 'disable' || def.hidden_when_flag_on)
+ .filter(([_, def]) => !def.superseded_by?.length && !def.redirect_hint)
+ .map(([name]) => name)
+
+ expect(undeclared).toEqual([])
+ })
+})
+
describe('toolPassesEntitlementGate', () => {
const gated = { feature_entitlement: 'audit_logs' } as ToolDefinition
const ungated = {} as ToolDefinition