: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
chore(mcp): remove discovery hints from tool results (#127791)
Adam Bowker6f169a873220
diff --git a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.mdindex 1127e1f8159e..5256629f87df 100644--- a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md+++ b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md@@ -108,9 +108,8 @@ reads as alias-free.A `learn` call also carries `exec_learn_kind` (`search`, `load`, `list` for `learn skills` and a bare `learn`, `describe`, `guide`),stamped before the availability check so a rejected skill command still records its form, plusthe raw `exec_search_query` for `search` (and for a `load` that searches inside the skill with `-s`) and `exec_learn_target` (the qualified skill) for `load`.-A successful call carries `mcp_result_empty: true` when the handler returned zero rows, and-`mcp_discovery_hint` (`empty_state` or `related_capability`) when the response builder appended a-hint footer (`services/mcp/src/lib/discovery-hints.ts`). `execute-sql` calls additionally emit a separate `$ai_generation` event+A successful call carries `mcp_result_empty: true` when the handler returned zero rows.+`execute-sql` calls additionally emit a separate `$ai_generation` eventcarrying `$ai_trace_id`, `$ai_input`, `$ai_output_choices`, and `$ai_latency`.## Exec-mode propertiesdiff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.tsindex 39f405dcd0d9..4b82f50f3e3d 100644--- a/services/mcp/src/lib/build-tool-result.ts+++ b/services/mcp/src/lib/build-tool-result.ts@@ -1,6 +1,6 @@import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'-import { type DiscoveryHint, type DiscoveryHintKind, getDiscoveryHint, isEmptyToolResult } from '@/lib/discovery-hints'+import { isEmptyToolResult } from '@/lib/empty-tool-result'import { estimateTokens } from '@/lib/estimate-tokens'import { getNextPageHint } from '@/lib/next-page-hint'import { formatResponse } from '@/lib/response'@@ -81,7 +81,6 @@ export function isToolCallPayload(value: unknown): value is ToolResultPayload {interface BuiltResponseText {structuredContentOnly: booleanfooters: string[]- discoveryHint: DiscoveryHintKind | undefinedresultEmpty: boolean}@@ -99,10 +98,7 @@ export function markExecPayload(payload: ToolResultPayload): ToolResultPayload {export function toolResultAnalyticsProperties(response: ToolResultPayload): Record<string, unknown> {const built = builtResponseText.get(response)- return {- ...(built?.discoveryHint ? { mcp_discovery_hint: built.discoveryHint } : {}),- ...(built?.resultEmpty ? { mcp_result_empty: true } : {}),- }+ return built?.resultEmpty ? { mcp_result_empty: true } : {}}/**@@ -237,12 +233,7 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultconst footers: string[] = []- let discoveryHint: DiscoveryHint | undefinedif (!isStringResult && !useJson && !structuredContentOnly && !isPrepareConfirmedActionResult(handlerResult)) {- discoveryHint = getDiscoveryHint({ toolName, handlerResult })- if (discoveryHint) {- footers.push(discoveryHint.text)- }const nextPageHint = getNextPageHint(toolName, rawResult)if (nextPageHint) {footers.push(nextPageHint)@@ -261,7 +252,6 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultbuiltResponseText.set(payload, {structuredContentOnly,footers,- discoveryHint: discoveryHint?.kind,resultEmpty: isEmptyToolResult(handlerResult, toolName),})if (hasUiResource && !suppressStructuredContent) {diff --git a/services/mcp/src/lib/discovery-hints.ts b/services/mcp/src/lib/discovery-hints.tsdeleted file mode 100644index 46ecd88ff82f..000000000000--- a/services/mcp/src/lib/discovery-hints.ts+++ /dev/null@@ -1,109 +0,0 @@-/**- * Discovery hints appended to successful tool results.- *- * Two kinds, keyed off the tool name (the success-path counterpart of- * `getToolRecoveryHint`, which only fires on 5xx errors):- *- * - Empty-state hints: a query-style tool returned zero rows. For products- * that need instrumentation (error tracking, logs, replay, AI observability)- * an empty result often means "not set up yet", not "nothing matched" — so- * instead of a bare empty array the agent gets pointed at the skill that- * gets data flowing, plus the mundane alternative (widen the date range).- *- * - Related-capability hints: the result is non-empty and there is an adjacent- * capability the agent is unlikely to know about at this point of use (error- * alerts after listing issues, subscriptions after creating an insight).- *- * Both registries are opt-in per tool: emptiness is not intrinsically- * distinguishable from "correctly filtered to nothing", and a blanket hint on- * every tool would be noise. Keep entries to one short paragraph and only add- * tools where the adjacent capability is a genuine next step, not marketing.- */--/**- * Fired when the tool result is empty (see `isEmptyToolResult`). Wording rule:- * lead with the not-instrumented-yet explanation and its skill, then give the- * ordinary explanation (filters/date range) so the agent doesn't push setup- * docs at a user who just over-filtered.- */-const EMPTY_STATE_HINTS: Record<string, string> = {- 'query-error-tracking-issues-list':- 'No issues matched. If this project has never captured exceptions, error tracking may not be instrumented yet — load the `instrument-error-tracking` skill to set it up. If issues normally show up here, widen the `dateRange` or loosen the filters instead.',- 'query-logs':- 'No log rows matched. If this project has never ingested logs, load the `instrument-logs` skill to start shipping them. Otherwise widen the `dateRange` or drop filters — `logs-count` is a cheap way to check whether any logs exist at all.',- 'query-session-recordings-list':- 'No recordings matched. If session replay has never captured anything here, load the `diagnosing-missing-recordings` skill to check SDK setup, sampling, and capture settings. Otherwise widen the date range or loosen the filters.',- 'logs-context':- 'No logs matched around this anchor. Widen `padding` or the `dateRange`, or drop `severityLevels`. If the anchor is a trace, check that the services write `trace_id` on their logs — `logs-count` with a `trace_id` filter is a cheap check.',- 'apm-service-health':- 'No spans matched. If this project has never ingested traces, the services are not instrumented yet. Otherwise widen the `dateRange`, or drop `environment` and `serviceNames` — `apm-services-list` shows the services that sent spans.',- 'logs-group-by':- 'No groups matched. Widen the `dateRange` or drop filters. If the group key is an attribute, check its name and source with `logs-attributes-list`.',- 'get-llm-total-costs-for-project':- 'No LLM cost data found. If AI observability is not capturing `$ai_generation` events yet, load the `instrument-llm-analytics` skill to wire it up. Otherwise widen the date range.',-}--/** Fired when the tool result is non-empty: the adjacent capability to reach for next. */-const RELATED_CAPABILITY_HINTS: Record<string, string> = {- 'query-error-tracking-issues-list':- 'Related: error alerts can notify Slack or a webhook when an issue is created, reopens, or starts spiking — load the `authoring-error-tracking-alerts` skill to set one up.',- 'query-logs':- 'Related: a check like this can run continuously as a log alert — load the `authoring-log-alerts` skill to author a low-noise one.',- 'get-llm-total-costs-for-project':- 'Related: to explain who or what drives this spend, load the `analyzing-expensive-users` skill.',- 'insight-create':- 'Related: this insight can go on a dashboard (`building-a-dashboard` skill) or be delivered to email/Slack on a schedule (`managing-subscriptions` skill).',-}--const PRIMARY_RESULT_KEYS: Record<string, string> = {- 'apm-service-health': 'services',- 'logs-context': 'timeline',- 'logs-group-by': 'groups',-}--/**- * Empty means "zero rows", in the two shapes the registered tools return:- * a bare array, or the standardized `{ results: [...] }` envelope produced by- * `withPostHogUrl` / `pickResponseFields` / the query-wrapper factory. Any- * other shape is treated as non-empty — hints only register tools whose- * shapes are known, so this never has to guess.- */-export function isEmptyToolResult(handlerResult: unknown, toolName?: string): boolean {- if (Array.isArray(handlerResult)) {- return handlerResult.length === 0- }- if (typeof handlerResult === 'object' && handlerResult !== null) {- const key = (toolName && PRIMARY_RESULT_KEYS[toolName]) || 'results'- const rows = (handlerResult as Record<string, unknown>)[key]- return Array.isArray(rows) && rows.length === 0- }- return false-}--interface DiscoveryHintInput {- /** The tool that produced the result. */- toolName: string- /** Raw handler return value, before serialization. */- handlerResult: unknown-}--export type DiscoveryHintKind = 'empty_state' | 'related_capability'--export interface DiscoveryHint {- kind: DiscoveryHintKind- text: string-}--/**- * Returns the discovery hint for a successful tool call, or `undefined` when- * none is registered. At most one hint fires per call: the empty-state hint- * when the result is empty, the related-capability hint otherwise.- */-export function getDiscoveryHint({ toolName, handlerResult }: DiscoveryHintInput): DiscoveryHint | undefined {- if (isEmptyToolResult(handlerResult, toolName)) {- const text = EMPTY_STATE_HINTS[toolName]- return text ? { kind: 'empty_state', text } : undefined- }- const text = RELATED_CAPABILITY_HINTS[toolName]- return text ? { kind: 'related_capability', text } : undefined-}diff --git a/services/mcp/src/lib/empty-tool-result.ts b/services/mcp/src/lib/empty-tool-result.tsnew file mode 100644index 000000000000..4313b150b2bb--- /dev/null+++ b/services/mcp/src/lib/empty-tool-result.ts@@ -0,0 +1,23 @@+const PRIMARY_RESULT_KEYS: Record<string, string> = {+ 'apm-service-health': 'services',+ 'logs-context': 'timeline',+ 'logs-group-by': 'groups',+}++/**+ * Empty means "zero rows", in the two shapes the registered tools return:+ * a bare array, or the standardized `{ results: [...] }` envelope produced by+ * `withPostHogUrl` / `pickResponseFields` / the query-wrapper factory. Any+ * other shape is treated as non-empty, so this never has to guess.+ */+export function isEmptyToolResult(handlerResult: unknown, toolName?: string): boolean {+ if (Array.isArray(handlerResult)) {+ return handlerResult.length === 0+ }+ if (typeof handlerResult === 'object' && handlerResult !== null) {+ const key = (toolName && PRIMARY_RESULT_KEYS[toolName]) || 'results'+ const rows = (handlerResult as Record<string, unknown>)[key]+ return Array.isArray(rows) && rows.length === 0+ }+ return false+}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex b38101a8636a..7e74d929f13e 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -6,7 +6,7 @@ import { getToolInputProperties, type ShouldRecordInputKeyFn } from '@posthog/mcimport { classifyAuthMethod } from '@/lib/auth-method'import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'import { isPostHogCodeConsumer } from '@/lib/client-detection'-import { isEmptyToolResult } from '@/lib/discovery-hints'+import { isEmptyToolResult } from '@/lib/empty-tool-result'import {ExecCommandError,type ExecCommandErrorReason,diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex dd660ddf1706..f4362795b168 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -615,7 +615,7 @@ describe('ToolExecutor metrics', () => {})})- it('stamps the discovery hint kind and emptiness the response builder recorded', async () => {+ it('stamps the emptiness the response builder recorded', async () => {vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('query-error-tracking-issues-list', async () => ({ results: [] })) as any)@@ -626,7 +626,6 @@ describe('ToolExecutor metrics', () => {)expect(trackToolCallExtras('query-error-tracking-issues-list')).toMatchObject({- mcp_discovery_hint: 'empty_state',mcp_result_empty: true,})})@@ -774,7 +773,6 @@ describe('ToolExecutor metrics', () => {const extras = mockTrackToolCall.mock.calls.at(-1)?.[4]expect(extras?.mcp_result_empty).toBe(empty ? true : undefined)- expect(extras).not.toHaveProperty('mcp_discovery_hint')})// In exec mode the inner arguments are JSON inside `command`, so the directdiff --git a/services/mcp/tests/unit/discovery-hints.test.ts b/services/mcp/tests/unit/discovery-hints.test.tsdeleted file mode 100644index f5c16ff56898..000000000000--- a/services/mcp/tests/unit/discovery-hints.test.ts+++ /dev/null@@ -1,182 +0,0 @@-import { describe, expect, it } from 'vitest'--import { buildToolResultPayload, markExecPayload, toolResultAnalyticsProperties } from '@/lib/build-tool-result'-import { getDiscoveryHint, isEmptyToolResult } from '@/lib/discovery-hints'-import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'--describe('isEmptyToolResult', () => {- it('treats an empty array as empty', () => {- expect(isEmptyToolResult([])).toBe(true)- })-- it('treats an empty `results` envelope as empty', () => {- expect(isEmptyToolResult({ results: [], _posthogUrl: 'https://us.posthog.com/project/2' })).toBe(true)- })-- it('treats populated results as non-empty', () => {- expect(isEmptyToolResult([{ id: 1 }])).toBe(false)- expect(isEmptyToolResult({ results: [{ id: 1 }] })).toBe(false)- })-- it('treats unknown shapes as non-empty rather than guessing', () => {- expect(isEmptyToolResult({ id: 123, name: 'My insight' })).toBe(false)- expect(isEmptyToolResult({ results: {} })).toBe(false)- expect(isEmptyToolResult('plain string')).toBe(false)- expect(isEmptyToolResult(null)).toBe(false)- expect(isEmptyToolResult(undefined)).toBe(false)- })-})--describe('getDiscoveryHint', () => {- it('returns the instrumentation hint when a registered query tool comes back empty', () => {- const hint = getDiscoveryHint({- toolName: 'query-error-tracking-issues-list',- handlerResult: { results: [] },- })-- expect(hint?.kind).toBe('empty_state')- expect(hint?.text).toContain('instrument-error-tracking')- expect(hint?.text).toContain('dateRange')- })-- it('returns the related-capability hint when the same tool has results', () => {- const hint = getDiscoveryHint({- toolName: 'query-error-tracking-issues-list',- handlerResult: { results: [{ id: 'issue-1' }] },- })-- expect(hint?.kind).toBe('related_capability')- expect(hint?.text).toContain('authoring-error-tracking-alerts')- expect(hint?.text).not.toContain('instrument-error-tracking')- })-- it.each([- ['query-logs', 'instrument-logs'],- ['query-session-recordings-list', 'diagnosing-missing-recordings'],- ['get-llm-total-costs-for-project', 'instrument-llm-analytics'],- ])('points %s at %s when empty', (toolName, skillName) => {- expect(getDiscoveryHint({ toolName, handlerResult: { results: [] } })?.text).toContain(skillName)- })-- it.each([- ['logs-context', { anchor: {}, timeline: [] }],- ['apm-service-health', { summary: {}, services: [] }],- ['logs-group-by', { groups: [] }],- ])('treats an empty primary array as empty for %s', (toolName, handlerResult) => {- const hint = getDiscoveryHint({ toolName, handlerResult })-- expect(hint?.kind).toBe('empty_state')- expect(hint?.text).toContain('dateRange')- })-- it('does not fire the empty-state hint when logs-context has timeline rows', () => {- const hint = getDiscoveryHint({ toolName: 'logs-context', handlerResult: { timeline: [{ body: 'x' }] } })-- expect(hint?.kind).not.toBe('empty_state')- })-- it('cross-sells subscriptions and dashboards after insight creation', () => {- const hint = getDiscoveryHint({ toolName: 'insight-create', handlerResult: { id: 1, short_id: 'abc' } })-- expect(hint?.text).toContain('managing-subscriptions')- expect(hint?.text).toContain('building-a-dashboard')- })-- it('returns undefined for unregistered tools, empty or not', () => {- expect(getDiscoveryHint({ toolName: 'dashboard-get', handlerResult: { results: [] } })).toBeUndefined()- expect(getDiscoveryHint({ toolName: 'dashboard-get', handlerResult: { id: 1 } })).toBeUndefined()- })-- it('returns undefined for a registered empty-state tool with results and no cross-sell entry', () => {- expect(- getDiscoveryHint({- toolName: 'query-session-recordings-list',- handlerResult: { results: [{ session_id: 's1' }] },- })- ).toBeUndefined()- })-})--describe('buildToolResultPayload discovery hint footer', () => {- it('appends the hint as a footer on the text channel', () => {- const payload = buildToolResultPayload({- handlerResult: { results: [], _posthogUrl: 'https://us.posthog.com/project/2/error_tracking' },- toolName: 'query-error-tracking-issues-list',- params: {},- })-- const text = payload.content[0]?.text ?? ''- expect(text).toContain('instrument-error-tracking')- // Footer, not preamble: the serialized result still leads.- expect(text.indexOf('_posthogUrl')).toBeLessThan(text.indexOf('instrument-error-tracking'))- })-- it('does not fire for tools without a registered hint', () => {- const payload = buildToolResultPayload({- handlerResult: { results: [] },- toolName: 'dashboard-templates-list',- params: {},- })-- expect(payload.content[0]?.text).not.toContain('skill')- })-- it('keeps output_format=json machine-parseable by skipping the footer', () => {- const payload = buildToolResultPayload({- handlerResult: { results: [] },- toolName: 'query-error-tracking-issues-list',- params: { output_format: 'json' },- })-- expect(() => JSON.parse(payload.content[0]?.text ?? '')).not.toThrow()- expect(payload.content[0]?.text).not.toContain('instrument-error-tracking')- })-- it.each([- [- 'an empty result with a hint',- { results: [] },- {},- { mcp_discovery_hint: 'empty_state', mcp_result_empty: true },- ],- [- 'a populated result with a hint',- { results: [{ id: 'issue-1' }] },- {},- { mcp_discovery_hint: 'related_capability' },- ],- [- 'an empty json result, where no footer fires',- { results: [] },- { output_format: 'json' },- { mcp_result_empty: true },- ],- ])(- 'records %s for the tool-call event, before and after the exec stamp',- (_label, handlerResult, params, expected) => {- const payload = buildToolResultPayload({- handlerResult,- toolName: 'query-error-tracking-issues-list',- params,- })-- expect(toolResultAnalyticsProperties(payload)).toEqual(expected)- expect(toolResultAnalyticsProperties(markExecPayload(payload))).toEqual(expected)- }- )-- it('appends the footer after a formatted-results override', () => {- const payload = buildToolResultPayload({- handlerResult: {- results: [],- [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: 'No issues in the last 7 days.',- },- toolName: 'query-error-tracking-issues-list',- params: {},- })-- const text = payload.content[0]?.text ?? ''- expect(text.startsWith('No issues in the last 7 days.')).toBe(true)- expect(text).toContain('instrument-error-tracking')- })-})diff --git a/services/mcp/tests/unit/empty-tool-result.test.ts b/services/mcp/tests/unit/empty-tool-result.test.tsnew file mode 100644index 000000000000..6f9127f7e402--- /dev/null+++ b/services/mcp/tests/unit/empty-tool-result.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest'++import { buildToolResultPayload, markExecPayload, toolResultAnalyticsProperties } from '@/lib/build-tool-result'+import { isEmptyToolResult } from '@/lib/empty-tool-result'++describe('isEmptyToolResult', () => {+ it('treats an empty array as empty', () => {+ expect(isEmptyToolResult([])).toBe(true)+ })++ it('treats an empty `results` envelope as empty', () => {+ expect(isEmptyToolResult({ results: [], _posthogUrl: 'https://us.posthog.com/project/2' })).toBe(true)+ })++ it('treats populated results as non-empty', () => {+ expect(isEmptyToolResult([{ id: 1 }])).toBe(false)+ expect(isEmptyToolResult({ results: [{ id: 1 }] })).toBe(false)+ })++ it('treats unknown shapes as non-empty rather than guessing', () => {+ expect(isEmptyToolResult({ id: 123, name: 'My insight' })).toBe(false)+ expect(isEmptyToolResult({ results: {} })).toBe(false)+ expect(isEmptyToolResult('plain string')).toBe(false)+ expect(isEmptyToolResult(null)).toBe(false)+ expect(isEmptyToolResult(undefined)).toBe(false)+ })++ it.each([+ ['logs-context', 'timeline'],+ ['apm-service-health', 'services'],+ ['logs-group-by', 'groups'],+ ])('reads the primary array of %s from `%s`', (toolName, key) => {+ expect(isEmptyToolResult({ [key]: [] }, toolName)).toBe(true)+ expect(isEmptyToolResult({ [key]: [{ id: 1 }] }, toolName)).toBe(false)+ })+})++describe('toolResultAnalyticsProperties', () => {+ it.each([+ ['an empty result', { results: [] }, {}, { mcp_result_empty: true }],+ ['a populated result', { results: [{ id: 'issue-1' }] }, {}, {}],+ ['an empty json result', { results: [] }, { output_format: 'json' }, { mcp_result_empty: true }],+ ])(+ 'records %s for the tool-call event, before and after the exec stamp',+ (_label, handlerResult, params, expected) => {+ const payload = buildToolResultPayload({+ handlerResult,+ toolName: 'query-error-tracking-issues-list',+ params,+ })++ expect(toolResultAnalyticsProperties(payload)).toEqual(expected)+ expect(toolResultAnalyticsProperties(markExecPayload(payload))).toEqual(expected)+ }+ )+})