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.

feat(mcp): stamp learn form, skills flag and result shape on tool calls (#106319)

Jake Ruth9dbe91a4334a
diff --git a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md
index 34dd5c781082..5223f58bcb15 100644
--- a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md
+++ b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md
@@ -92,7 +92,13 @@ Per-event additions: `$mcp_error_status` (upstream HTTP status), `$mcp_error_cod
which keys the caller actually sent), and exec-mode calls carry `$mcp_exec_verb` (which dispatcher
verb ran) and `$mcp_exec_target_tool` (the tool that `info`/`schema`/`call` named). Those four are
stamped in `tool-executor.ts` but are **not registered in `posthog/taxonomy/taxonomy.py`**, so they
-have no descriptions in the property picker — they still query fine. `execute-sql` calls additionally emit a separate `$ai_generation` event
+have no descriptions in the property picker — they still query fine.
+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, plus
+the 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
carrying `$ai_trace_id`, `$ai_input`, `$ai_output_choices`, and `$ai_latency`.
## Exec-mode properties
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index dc01f15002da..1fa4a58af711 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -6,6 +6,7 @@ import {
buildToolResultPayload,
estimateResponseTokens,
isToolCallPayload,
+ toolResultAnalyticsProperties,
type ToolResultPayload,
} from '@/lib/build-tool-result'
import {
@@ -74,6 +75,7 @@ interface ExecMetricState {
innerFailure: { error: unknown } | undefined
/** Which kind of skill lookup missed, when the dispatcher rewrote a 404. */
skillLookupMissKind: SkillLookupMissKind | undefined
+ resultEmpty: boolean
}
/**
@@ -433,6 +435,7 @@ export class ToolExecutor {
...skillShape,
input_tokens: estimateTokens(validation.data),
output_tokens: estimateResponseTokens(response),
+ ...toolResultAnalyticsProperties(response),
},
analyticsMeta,
this.servedToolDescription(tool.name)
@@ -528,6 +531,7 @@ export class ToolExecutor {
commandMeta: undefined,
innerFailure: undefined,
skillLookupMissKind: undefined,
+ resultEmpty: false,
}
const resolved = this.resolveExecTool(state, execMetrics, analyticsMeta)
@@ -600,6 +604,8 @@ export class ToolExecutor {
input_tokens: estimateTokens(validation.data),
output_tokens: estimateResponseTokens(response),
...execMetrics.commandMeta,
+ ...(execMetrics.resultEmpty ? { mcp_result_empty: true } : {}),
+ ...toolResultAnalyticsProperties(response),
},
analyticsMeta,
this.servedToolDescription(execToolName())
@@ -687,6 +693,7 @@ export class ToolExecutor {
execMetrics.innerFailure = { error: properties.error }
}
execMetrics.skillLookupMissKind = properties.skill_lookup_miss_kind
+ execMetrics.resultEmpty = properties.result_empty === true
const status = properties.success ? 'success' : properties.validation_error ? 'validation_error' : 'error'
toolCallsTotal.inc({ tool: toolName, status })
// Mirror the native path: schema rejections never start a handler, so
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.ts
index 37b6b87af434..95892071d39b 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 { getDiscoveryHint } from '@/lib/discovery-hints'
+import { type DiscoveryHint, type DiscoveryHintKind, getDiscoveryHint, isEmptyToolResult } from '@/lib/discovery-hints'
import { estimateTokens } from '@/lib/estimate-tokens'
import { formatResponse } from '@/lib/response'
import { isPrepareConfirmedActionResult } from '@/tools/confirmed-action-runtime'
@@ -79,6 +79,8 @@ export function isToolCallPayload(value: unknown): value is ToolResultPayload {
interface BuiltResponseText {
structuredContentOnly: boolean
footers: string[]
+ discoveryHint: DiscoveryHintKind | undefined
+ resultEmpty: boolean
}
const builtResponseText = new WeakMap<ToolResultPayload, BuiltResponseText>()
@@ -93,6 +95,14 @@ export function markExecPayload(payload: ToolResultPayload): ToolResultPayload {
return marked
}
+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 } : {}),
+ }
+}
+
/**
* Placeholder that replaces the text content when the payload rides in
* `structuredContent` alone (see `buildToolResultPayload`). Kept short and
@@ -221,10 +231,11 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
const footers: string[] = []
+ let discoveryHint: DiscoveryHint | undefined
if (!isStringResult && !useJson && !structuredContentOnly && !isPrepareConfirmedActionResult(handlerResult)) {
- const discoveryHint = getDiscoveryHint({ toolName, handlerResult })
+ discoveryHint = getDiscoveryHint({ toolName, handlerResult })
if (discoveryHint) {
- footers.push(discoveryHint)
+ footers.push(discoveryHint.text)
}
}
@@ -237,7 +248,12 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResult
const payload: ToolResultPayload = {
content: [{ type: 'text', text }],
}
- builtResponseText.set(payload, { structuredContentOnly, footers })
+ builtResponseText.set(payload, {
+ structuredContentOnly,
+ footers,
+ discoveryHint: discoveryHint?.kind,
+ resultEmpty: isEmptyToolResult(handlerResult),
+ })
if (hasUiResource && !suppressStructuredContent) {
payload.structuredContent = structuredContent as Record<string, unknown>
}
diff --git a/services/mcp/src/lib/discovery-hints.ts b/services/mcp/src/lib/discovery-hints.ts
index 6fbfc6243c6e..afadc8d5ba1d 100644
--- a/services/mcp/src/lib/discovery-hints.ts
+++ b/services/mcp/src/lib/discovery-hints.ts
@@ -74,14 +74,23 @@ interface DiscoveryHintInput {
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): string | undefined {
+export function getDiscoveryHint({ toolName, handlerResult }: DiscoveryHintInput): DiscoveryHint | undefined {
if (isEmptyToolResult(handlerResult)) {
- return EMPTY_STATE_HINTS[toolName]
+ const text = EMPTY_STATE_HINTS[toolName]
+ return text ? { kind: 'empty_state', text } : undefined
}
- return RELATED_CAPABILITY_HINTS[toolName]
+ const text = RELATED_CAPABILITY_HINTS[toolName]
+ return text ? { kind: 'related_capability', text } : undefined
}
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 69fd6f151e52..f90a7aaa451b 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'
import { isPostHogCodeConsumer } from '@/lib/client-detection'
+import { isEmptyToolResult } from '@/lib/discovery-hints'
import {
ExecCommandError,
type ExecCommandErrorReason,
@@ -15,7 +16,7 @@ import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'
import { formatResponse } from '@/lib/response'
import { APP_DATA_META_KEY } from '@/ui-apps/types'
-import { type ExecLearnCatalog } from './exec-learn'
+import { type ExecLearnCatalog, QUALIFIED_IDENTIFIER, tokenizeLearnInput } from './exec-learn'
import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'
import { type BuiltInSkillHint, formatSkillLookupMiss, type SkillLookupMissKind } from './skills/notFound'
import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'
@@ -141,6 +142,7 @@ export interface ExecInnerCallProperties {
output?: unknown
/** Which kind of skill lookup missed, when the dispatcher rewrote a 404. */
skill_lookup_miss_kind?: SkillLookupMissKind
+ result_empty?: boolean
}
export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void
@@ -162,10 +164,51 @@ export interface ExecCommandMeta {
exec_search_match_count?: number
/** How many of those matches came from a connected third-party server. */
exec_search_gateway_match_count?: number
+ exec_learn_kind?: ExecLearnKind
+ exec_learn_target?: string
}
export type ExecCommandTracker = (meta: ExecCommandMeta) => void
+export type ExecLearnKind = 'search' | 'load' | 'list' | 'describe' | 'guide'
+
+export function classifyLearnCommand(
+ rest: string
+): Pick<ExecCommandMeta, 'exec_learn_kind' | 'exec_search_query' | 'exec_learn_target'> {
+ let tokens: string[]
+ try {
+ tokens = tokenizeLearnInput(rest)
+ } catch {
+ return {}
+ }
+ const [first, ...args] = tokens
+ if (first === '-s') {
+ return { exec_learn_kind: 'search', exec_search_query: args.join(' ').slice(0, MAX_SEARCH_PATTERN_LENGTH) }
+ }
+ if (first === '-d') {
+ return { exec_learn_kind: 'describe' }
+ }
+ if (first === undefined || first === 'skills') {
+ return { exec_learn_kind: 'list' }
+ }
+ if (first !== undefined && QUALIFIED_IDENTIFIER.test(first)) {
+ const searchIndex = args.indexOf('-s')
+ return {
+ exec_learn_kind: 'load',
+ exec_learn_target: first.slice(0, MAX_SEARCH_PATTERN_LENGTH),
+ ...(searchIndex === -1
+ ? {}
+ : {
+ exec_search_query: args
+ .slice(searchIndex + 1)
+ .join(' ')
+ .slice(0, MAX_SEARCH_PATTERN_LENGTH),
+ }),
+ }
+ }
+ return { exec_learn_kind: 'guide' }
+}
+
export interface ExecToolOptions {
requireDestructiveConfirmation?: boolean
learnCatalog?: ExecLearnCatalog
@@ -1548,6 +1591,8 @@ export function createExecTool(
switch (verb) {
case 'learn': {
+ // Before the availability check, so a rejected skill command still records its form.
+ options.trackCommand?.({ exec_verb: verb, ...classifyLearnCommand(rest) })
const learnCatalog = options.learnCatalog
if (!learnCatalog) {
// `learn` is only advertised when a catalog exists, so without one
@@ -1886,6 +1931,8 @@ export function createExecTool(
throw err
}
const durationMs = Date.now() - startedAt
+ // The text path below builds no payload, so emptiness is reported from here.
+ const resultShape = isEmptyToolResult(result) ? { result_empty: true } : {}
const formattedOverride =
result !== null && typeof result === 'object'
? (result as Record<string, unknown>)[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]
@@ -1909,6 +1956,7 @@ export function createExecTool(
output_tokens: estimateTokens(outputText),
input,
output: outputText,
+ ...resultShape,
})
if (!includeAppData) {
return outputText
@@ -1958,6 +2006,7 @@ export function createExecTool(
output_tokens: estimateResponseTokens(payload),
input,
output: payload,
+ ...resultShape,
})
return payload
}
@@ -1983,6 +2032,7 @@ export function createExecTool(
output_tokens: estimateTokens(outputText),
input,
output: outputText,
+ ...resultShape,
})
return outputText
}
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index 7eeb7e65076b..3f0c5f74b8bb 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -445,6 +445,22 @@ describe('ToolExecutor metrics', () => {
})
})
+ it('stamps the discovery hint kind and emptiness the response builder recorded', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('query-error-tracking-issues-list', async () => ({ results: [] })) as any
+ )
+
+ await executor.handleToolCall(
+ { name: 'query-error-tracking-issues-list', arguments: {} },
+ makeToolExecutorState([{ name: 'query-error-tracking-issues-list' }])
+ )
+
+ expect(trackToolCallExtras('query-error-tracking-issues-list')).toMatchObject({
+ mcp_discovery_hint: 'empty_state',
+ mcp_result_empty: true,
+ })
+ })
+
it('records error for unknown tool', async () => {
await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeToolExecutorState([]))
@@ -483,6 +499,15 @@ describe('ToolExecutor metrics', () => {
// records that it was unrecognized rather than the token itself.
['frobnicate whatever', { $mcp_exec_verb: 'unrecognized' }],
['call not-a-real-tool {}', { $mcp_exec_verb: 'call', $mcp_exec_target_tool: 'unrecognized' }],
+ [
+ 'learn -s "funnel conversion"',
+ {
+ $mcp_exec_verb: 'learn',
+ exec_learn_kind: 'search',
+ exec_search_query: 'funnel conversion',
+ $mcp_error_code: 'unknown_command',
+ },
+ ],
])('stamps the exec verb and target for "%s"', async (command, expected) => {
await executor.handleToolCall({ name: 'exec', arguments: { command } }, execState())
@@ -490,6 +515,21 @@ describe('ToolExecutor metrics', () => {
expect(call?.[4]).toMatchObject(expected)
})
+ it.each([
+ ['an empty results envelope', async () => ({ results: [] }), true],
+ ['a populated result', async () => ({ results: [{ id: 1 }] }), false],
+ ])('reports emptiness of %s on an exec-routed call', async (_label, handler, empty) => {
+ const tool = { ...makeFakeTool('query-error-tracking-issues-list', handler).base }
+ await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'call query-error-tracking-issues-list {}' } },
+ makeToolExecutorState([{ name: 'query-error-tracking-issues-list', ...tool }], { useSingleExec: true })
+ )
+
+ const extras = mockTrackToolCall.mock.calls.at(-1)?.[4]
+ expect(extras?.mcp_result_empty).toBe(empty ? true : undefined)
+ expect(extras).not.toHaveProperty('mcp_discovery_hint')
+ })
+
// 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.
diff --git a/services/mcp/tests/unit/discovery-hints.test.ts b/services/mcp/tests/unit/discovery-hints.test.ts
index f94252f565a7..a701b760317b 100644
--- a/services/mcp/tests/unit/discovery-hints.test.ts
+++ b/services/mcp/tests/unit/discovery-hints.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
-import { buildToolResultPayload } from '@/lib/build-tool-result'
+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'
@@ -34,8 +34,9 @@ describe('getDiscoveryHint', () => {
handlerResult: { results: [] },
})
- expect(hint).toContain('instrument-error-tracking')
- expect(hint).toContain('dateRange')
+ 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', () => {
@@ -44,8 +45,9 @@ describe('getDiscoveryHint', () => {
handlerResult: { results: [{ id: 'issue-1' }] },
})
- expect(hint).toContain('authoring-error-tracking-alerts')
- expect(hint).not.toContain('instrument-error-tracking')
+ expect(hint?.kind).toBe('related_capability')
+ expect(hint?.text).toContain('authoring-error-tracking-alerts')
+ expect(hint?.text).not.toContain('instrument-error-tracking')
})
it.each([
@@ -53,14 +55,14 @@ describe('getDiscoveryHint', () => {
['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: [] } })).toContain(skillName)
+ expect(getDiscoveryHint({ toolName, handlerResult: { results: [] } })?.text).toContain(skillName)
})
it('cross-sells subscriptions and dashboards after insight creation', () => {
const hint = getDiscoveryHint({ toolName: 'insight-create', handlerResult: { id: 1, short_id: 'abc' } })
- expect(hint).toContain('managing-subscriptions')
- expect(hint).toContain('building-a-dashboard')
+ expect(hint?.text).toContain('managing-subscriptions')
+ expect(hint?.text).toContain('building-a-dashboard')
})
it('returns undefined for unregistered tools, empty or not', () => {
@@ -113,6 +115,39 @@ describe('buildToolResultPayload discovery hint footer', () => {
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: {
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 3e71cab8b393..67a2f3aed0de 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -16,6 +16,7 @@ import {
describeApiValidationError,
describeExecCommand,
describeValidationError,
+ type ExecCommandMeta,
type ExecInnerCallProperties,
type ExecToolOptions,
formatInputValidationError,
@@ -92,6 +93,49 @@ describe('exec tool', () => {
]
const learnCatalog = new ExecLearnCatalog(guides, { posthog: undefined })
+ it.each([
+ ['learn -s "funnel conversion"', { exec_learn_kind: 'search', exec_search_query: 'funnel conversion' }],
+ [
+ 'learn posthog:building-a-dashboard README.md',
+ { exec_learn_kind: 'load', exec_learn_target: 'posthog:building-a-dashboard' },
+ ],
+ [
+ 'learn posthog:building-a-dashboard README.md -s "date range"',
+ {
+ exec_learn_kind: 'load',
+ exec_learn_target: 'posthog:building-a-dashboard',
+ exec_search_query: 'date range',
+ },
+ ],
+ ['learn skills', { exec_learn_kind: 'list' }],
+ ['learn -d posthog:building-a-dashboard', { exec_learn_kind: 'describe' }],
+ ['learn analytics', { exec_learn_kind: 'guide' }],
+ ['learn', { exec_learn_kind: 'list' }],
+ ])('reports the learn form for "%s" whether or not learn is available', async (command, expected) => {
+ for (const catalogOption of [{ learnCatalog }, {}]) {
+ const tracked: ExecCommandMeta[] = []
+ const exec = createExec(undefined, undefined, {
+ ...catalogOption,
+ trackCommand: (meta) => tracked.push(meta),
+ })
+
+ await exec.handler(mockContext, { command }).catch(() => undefined)
+
+ expect(tracked.at(-1)).toEqual({ exec_verb: 'learn', ...expected })
+ }
+ })
+
+ it('keeps a malformed learn command a usage error and stamps no form', async () => {
+ const tracked: ExecCommandMeta[] = []
+ const exec = createExec(undefined, undefined, { learnCatalog, trackCommand: (meta) => tracked.push(meta) })
+
+ await expect(exec.handler(mockContext, { command: 'learn -s "unterminated' })).rejects.toMatchObject({
+ reason: 'usage',
+ message: 'Unterminated quote in learn command.',
+ })
+ expect(tracked.at(-1)).toEqual({ exec_verb: 'learn' })
+ })
+
it('lists guide metadata and skill discovery commands without loading content', async () => {
const exec = createExec(undefined, undefined, { learnCatalog })