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): stop advertising docs-search when it is unavailable (#104277)

posthog[bot]67fc24d00c27
diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.ts
index 73893525242f..65f2a11da32f 100644
--- a/services/mcp/src/hono/instructions.ts
+++ b/services/mcp/src/hono/instructions.ts
@@ -33,6 +33,8 @@ import { toMcpInputSchema } from './tool-catalog'
/** Presence of this tool is the runtime signal that the notebook cell surface
* (the `revamped-py-notebooks` flag) is live for this client. */
const NOTEBOOK_ADD_CELL_TOOL = 'notebooks-add-cell'
+const DOCS_SEARCH_TOOL = 'docs-search'
+const BUSINESS_KNOWLEDGE_SEARCH_TOOL = 'business-knowledge-documents-search'
export class InstructionsBuilder {
private readonly formatter: InstructionsFormatter
@@ -78,6 +80,7 @@ export class InstructionsBuilder {
metadataCompact: state.metadataCompact,
groupTypes: state.groupTypes,
notebookCellsEnabled: state.allTools.some((tool) => tool.name === NOTEBOOK_ADD_CELL_TOOL),
+ docsSearchEnabled: state.allTools.some((tool) => tool.name === DOCS_SEARCH_TOOL),
}
}
@@ -178,9 +181,9 @@ export class InstructionsBuilder {
buildExecToolDescription(state?: ResolvedState): string {
const skillsEnabled = state ? this.getExecLearnCapabilities(state).skillsEnabled : false
- const docsSearchEnabled = state?.allTools.some(({ name }) => name === 'docs-search')
+ const docsSearchEnabled = state?.allTools.some(({ name }) => name === DOCS_SEARCH_TOOL)
const businessKnowledgeSearchEnabled = state?.allTools.some(
- ({ name }) => name === 'business-knowledge-documents-search'
+ ({ name }) => name === BUSINESS_KNOWLEDGE_SEARCH_TOOL
)
return this.formatter.buildExecToolDescription({
skillsEnabled,
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index becac90bab27..835c4a738a0f 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -41,6 +41,11 @@ import TOOL_SEARCH from '@/templates/sections/tool-search.md'
import URL_PATTERNS from '@/templates/sections/url-patterns.md'
import { type ExecLearnGuide, LEARN_COMMAND_LINE } from '@/tools/exec-learn'
+/** Naming a command the catalog withholds sends the agent down a path it cannot take. */
+const WHATS_NEW_WITH_DOCS_SEARCH =
+ "Check what's new via the `docs-search` tool or the changelog (https://posthog.com/changelog.md)."
+const WHATS_NEW_CHANGELOG_ONLY = "Check what's new in the changelog (https://posthog.com/changelog.md)."
+
export interface InstructionsContext {
guidelines: string
groupTypes?: GroupType[] | undefined
@@ -59,6 +64,17 @@ export interface InstructionsContext {
* advertised to this client. Gates the Python-in-a-notebook section so we never
* tell an agent to put its analysis in a cell type it can't create. */
notebookCellsEnabled?: boolean | undefined
+ /** Whether `docs-search` is advertised to this client. Gates every mention of
+ * the tool, so the prompt never names a command `search` and `call` cannot
+ * resolve. Carried as a field rather than derived from `tools`, which
+ * `buildExecCommandReference` drops on purpose. */
+ docsSearchEnabled?: boolean | undefined
+}
+
+/** Resolve the field, falling back to the advertised tool list for callers that
+ * build a context without it (the CLI's `--agent-help`). */
+function docsSearchAvailable(ctx: InstructionsContext): boolean {
+ return ctx.docsSearchEnabled ?? ctx.tools?.some(({ name }) => name === 'docs-search') ?? false
}
/**
@@ -69,11 +85,13 @@ export interface InstructionsContext {
*/
export class InstructionsFormatter {
private knowledgeFirstSections(ctx: InstructionsContext): string[] {
- const docsSearchEnabled = ctx.tools?.some(({ name }) => name === 'docs-search')
const businessKnowledgeSearchEnabled = ctx.tools?.some(
({ name }) => name === 'business-knowledge-documents-search'
)
- return this.knowledgeFirstSectionsForCapabilities({ docsSearchEnabled, businessKnowledgeSearchEnabled })
+ return this.knowledgeFirstSectionsForCapabilities({
+ docsSearchEnabled: docsSearchAvailable(ctx),
+ businessKnowledgeSearchEnabled,
+ })
}
private knowledgeFirstSectionsForCapabilities(opts: {
@@ -316,13 +334,15 @@ export class InstructionsFormatter {
AGENT_FEEDBACK,
EXAMPLES,
]
+ const docsSearchEnabled = docsSearchAvailable(ctx)
const renderCtx: InstructionsContext = opts.stripEnvContext
? {
guidelines: ctx.guidelines,
queryTools: ctx.queryTools,
+ docsSearchEnabled,
...(opts.keepEnvContext ? { metadata: ctx.metadata, groupTypes: ctx.groupTypes } : {}),
}
- : { ...ctx, tools: undefined }
+ : { ...ctx, tools: undefined, docsSearchEnabled }
// Tool domains are temporarily omitted from the command reference while we
// probe claude.ai's per-tool size cap (it silently drops oversized entries);
// agents still discover domains at runtime via the `search` command, and
@@ -357,6 +377,7 @@ export class InstructionsFormatter {
query_tools: ctx.queryTools ? buildQueryToolsBlock(ctx.queryTools) : '',
entity_schema_discovery: ENTITY_SCHEMA_DISCOVERY.trim(),
extra_commands: opts.extraCommands ?? '',
+ whats_new_check: docsSearchAvailable(ctx) ? WHATS_NEW_WITH_DOCS_SEARCH : WHATS_NEW_CHANGELOG_ONLY,
}
const body = sections
.map((s) => s.trim())
diff --git a/services/mcp/src/templates/sections/cli-error-handling.md b/services/mcp/src/templates/sections/cli-error-handling.md
index 00f7bc6f27ad..f3b08e5e12ca 100644
--- a/services/mcp/src/templates/sections/cli-error-handling.md
+++ b/services/mcp/src/templates/sections/cli-error-handling.md
@@ -2,4 +2,4 @@
- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.
- If a tool name doesn't exist, run `tools` again to find the correct name.
-- If no tool covers a PostHog capability the user asks about, don't conclude it doesn't exist — PostHog ships changes daily. Check what's new via the `docs-search` tool or the changelog (https://posthog.com/changelog.md).
+- If no tool covers a PostHog capability the user asks about, don't conclude it doesn't exist — PostHog ships changes daily. {whats_new_check}
diff --git a/services/mcp/tests/unit/exec-advertised-commands.test.ts b/services/mcp/tests/unit/exec-advertised-commands.test.ts
new file mode 100644
index 000000000000..02c54652fe86
--- /dev/null
+++ b/services/mcp/tests/unit/exec-advertised-commands.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest'
+
+import { InstructionsBuilder } from '@/hono/instructions'
+import type { ResolvedState } from '@/hono/request-state-resolver'
+import { MCPClientProfile } from '@/lib/client-detection'
+import { getToolDefinitions } from '@/tools/toolDefinitions'
+
+import { makeToolExecutorState } from '../shared/test-utils'
+
+const CATALOG_TOOL_NAMES = Object.keys(getToolDefinitions())
+const CATALOG = new Set(CATALOG_TOOL_NAMES)
+
+/** Tools named in prose that predates any availability gate. Each one is still a
+ * live instance of the same defect, kept as a ratchet rather than fixed here:
+ * `analysis-artifacts` and `url-patterns` name dashboard and link tools, the
+ * metric-discovery sections name the data-catalog trio, and `examples`,
+ * `retrieving-data`, `cli-data-discovery` and `schema-workflow` name query, SQL,
+ * schema and skill tools. `cli-rendering` names a tool as an example of one
+ * `render-ui` can render. Remove a name once its section gates the mention. */
+const UNGATED_BY_DESIGN = new Set([
+ 'actions-get-all',
+ 'agent-feedback',
+ 'business-knowledge-document-window-retrieve',
+ 'dashboard-create',
+ 'dashboard-get',
+ 'dashboard-widgets-batch-add',
+ 'dashboards-get-all',
+ 'data-catalog-metric-run',
+ 'execute-sql',
+ 'experiment-get',
+ 'feature-flag-get-all',
+ 'generate-app-url',
+ 'insight-create',
+ 'insight-get',
+ 'metric-describe',
+ 'metric-list',
+ 'query-funnel',
+ 'query-lifecycle',
+ 'query-llm-traces-list',
+ 'query-paths',
+ 'query-retention',
+ 'query-stickiness',
+ 'query-trends',
+ 'read-data-schema',
+ 'skill-get',
+])
+
+/** Backticked kebab-case names the guidance uses, which is the shape every tool
+ * name has. Single-word tokens (`series`, `call`) are prose and cannot be a tool. */
+function backtickedNames(text: string): string[] {
+ const named = new Set<string>()
+ for (const match of text.matchAll(/`([a-z][a-z0-9]*(?:-[a-z0-9]+)+)`/g)) {
+ const token = match[1]
+ if (token) {
+ named.add(token)
+ }
+ }
+ return [...named].sort()
+}
+
+/** Kebab-case names that are deliberately not exec commands: a built-in skill
+ * loaded by name, and the render-ui tool, which MCP Apps hosts get as its own
+ * MCP tool rather than through the exec catalog. */
+const NOT_EXEC_COMMANDS = new Set(['querying-posthog-data', 'render-ui'])
+
+function advertisedCommands(text: string): string[] {
+ return backtickedNames(text).filter((name) => CATALOG.has(name))
+}
+
+/** Both surfaces an agent reads before its first call, plus the separate
+ * reference Claude web/desktop gets. */
+function execGuidance(toolNames: string[]): string {
+ const builder = new InstructionsBuilder('some guidelines')
+ const state = (vendorClient?: string, renderUiEnabled = false): ResolvedState =>
+ makeToolExecutorState(
+ toolNames.map((name) => ({ name })),
+ { clientProfile: new MCPClientProfile(vendorClient ? { vendorClient } : {}), renderUiEnabled }
+ )
+ return [
+ builder.buildExecToolDescription(state()),
+ builder.buildExecCommandReference(state()),
+ builder.buildExecCommandReference(state('ClaudeAI')),
+ builder.buildExecCommandReference(state(undefined, true)),
+ ].join('\n\n')
+}
+
+/** A command the guidance names is only safe if the guidance stops naming it once
+ * the connection loses the tool — otherwise the agent is sent to a name `search`
+ * and `call` cannot resolve. */
+function namesToolWhenWithheld(name: string): boolean {
+ const available = CATALOG_TOOL_NAMES.filter((tool) => tool !== name)
+ return advertisedCommands(execGuidance(available)).includes(name)
+}
+
+describe('exec guidance advertises only resolvable commands', () => {
+ const advertised = advertisedCommands(execGuidance(CATALOG_TOOL_NAMES))
+ const gated = advertised.filter((name) => !UNGATED_BY_DESIGN.has(name))
+
+ it('gates every advertised command that is not a known exemption', () => {
+ expect(gated.filter(namesToolWhenWithheld)).toEqual([])
+ })
+
+ it('keeps the exemption list free of names that are now gated', () => {
+ const stale = [...UNGATED_BY_DESIGN].filter((name) => !namesToolWhenWithheld(name)).sort()
+ expect(stale).toEqual([])
+ })
+
+ it('names no command that the catalog cannot resolve', () => {
+ const unresolvable = backtickedNames(execGuidance(CATALOG_TOOL_NAMES)).filter(
+ (name) => !CATALOG.has(name) && !NOT_EXEC_COMMANDS.has(name)
+ )
+ expect(unresolvable).toEqual([])
+ })
+
+ it('names docs-search when the connection holds it', () => {
+ expect(advertised).toContain('docs-search')
+ })
+})