: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
feat(mcp): append discovery hints to MCP tool results (#78431)
Joe Martin80d71b4afa7d
diff --git a/services/mcp/src/lib/build-tool-result.ts b/services/mcp/src/lib/build-tool-result.tsindex 02ae1a87bd86..60b7a944272d 100644--- a/services/mcp/src/lib/build-tool-result.ts+++ b/services/mcp/src/lib/build-tool-result.ts@@ -1,5 +1,6 @@import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'+import { getDiscoveryHint } from '@/lib/discovery-hints'import { estimateTokens } from '@/lib/estimate-tokens'import { formatResponse } from '@/lib/response'import { isPrepareConfirmedActionResult } from '@/tools/confirmed-action-runtime'@@ -187,10 +188,22 @@ export function buildToolResultPayload(opts: BuildToolResultOptions): ToolResultconst structuredContentOnly =!!forceUiDataToMeta && hasUiResource && !isStringResult && !useJson && formattedResults === undefined- const text = structuredContentOnly+ let text = structuredContentOnly? STRUCTURED_CONTENT_ONLY_TEXT: (formattedResults ?? (useJson ? JSON.stringify(rawResult) : formatResponse(rawResult)))+ // Discovery hints ride the text channel as a footer, mirroring how error+ // responses carry `getToolRecoveryHint`. Skipped when the caller asked for+ // raw JSON (the text must stay machine-parseable) and when the text is only+ // the structuredContent pointer (the model reads the structured field, and+ // `estimateResponseTokens` keys off the exact pointer string).+ if (!isStringResult && !useJson && !structuredContentOnly && !isPrepareConfirmedActionResult(handlerResult)) {+ const discoveryHint = getDiscoveryHint({ toolName, handlerResult })+ if (discoveryHint) {+ text = `${text}\n\n${discoveryHint}`+ }+ }+const payload: ToolResultPayload = {content: [{ type: 'text', text }],}diff --git a/services/mcp/src/lib/discovery-hints.ts b/services/mcp/src/lib/discovery-hints.tsnew file mode 100644index 000000000000..6fbfc6243c6e--- /dev/null+++ b/services/mcp/src/lib/discovery-hints.ts@@ -0,0 +1,87 @@+/**+ * 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.',+ '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).',+}++/**+ * 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): boolean {+ if (Array.isArray(handlerResult)) {+ return handlerResult.length === 0+ }+ if (typeof handlerResult === 'object' && handlerResult !== null) {+ const results = (handlerResult as Record<string, unknown>).results+ return Array.isArray(results) && results.length === 0+ }+ return false+}++interface DiscoveryHintInput {+ /** The tool that produced the result. */+ toolName: string+ /** Raw handler return value, before serialization. */+ handlerResult: unknown+}++/**+ * 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 {+ if (isEmptyToolResult(handlerResult)) {+ return EMPTY_STATE_HINTS[toolName]+ }+ return RELATED_CAPABILITY_HINTS[toolName]+}diff --git a/services/mcp/tests/unit/discovery-hints.test.ts b/services/mcp/tests/unit/discovery-hints.test.tsnew file mode 100644index 000000000000..f94252f565a7--- /dev/null+++ b/services/mcp/tests/unit/discovery-hints.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest'++import { buildToolResultPayload } 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).toContain('instrument-error-tracking')+ expect(hint).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).toContain('authoring-error-tracking-alerts')+ expect(hint).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: [] } })).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')+ })++ 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('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')+ })+})