: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
fix(aio): link llm trace queries to the trace page, not an empty insight (#82737)
Radu Raicea4057bd4fc9d5
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 4d8c53248067..9effb93f0b11 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -1411,6 +1411,7 @@ wrappers:exclude_properties:- response- modifiers+ url_prefix: /ai-observability/tracesquery-llm-trace:schema_ref: AssistantTraceQueryenabled: true@@ -1426,3 +1427,4 @@ wrappers:exclude_properties:- response- modifiers+ url_prefix: /ai-observability/traces/{traceId}diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex d39742da77c9..6c91d67db75f 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -699,6 +699,7 @@ A bare id leaves the reader copying a string and guessing which page it belongs- **Take the link off the tool result when it has one.** A result carrying a `*url` field (`_posthogUrl` and friends) already holds the canonical link, so surface it verbatim rather than rewriting or stripping it.- **Otherwise call `generate-app-url`** and use the `url` it returns verbatim. Never assemble a path around an id you retyped: a wrong slug reads as a working link and drops the reader on a 404.+- **Never assemble an `/insights/new#q=…` link yourself.** Wrapping a query you ran into an insight URL only renders for the query kinds the insight editor accepts as a source; a trace, log, or session query wrapped that way opens a blank new insight with no error, so the reader sees an empty chart and has no way to tell the link is broken. Link the entity's own page instead.- **When neither source reaches the entity itself, keep the bare id.** Some entities have no detail page in the URL catalog (an insight alert, for one: `alert-get` returns its url, the catalog has only the `/alerts` list). Don't substitute a link to the list page the entity sits on, which reads as a link to the thing and drops the reader somewhere they still have to search.- **Full URLs only** (origin plus path), because a bare path is not clickable in the inbox or in Slack. Take the origin from the link the tool returned rather than from memory, since this project may not sit on the host you assume, and never include `/-/`.- **The anchor text names the entity**, so the sentence still reads without the URL. Keep the id itself in the prose or a `code` span wherever a reader may need to paste it into a query."""diff --git a/products/signals/skills/signals-scout-ai-observability/SKILL.md b/products/signals/skills/signals-scout-ai-observability/SKILL.mdindex bde4f5a5940b..7de89d89dffd 100644--- a/products/signals/skills/signals-scout-ai-observability/SKILL.md+++ b/products/signals/skills/signals-scout-ai-observability/SKILL.md@@ -73,7 +73,7 @@ The lenses below are the surfaces worth watching. **Do not run all of them everyWhen a lens flags something, don't report the top-line number — localize and sample:- **Localize.** Slice the contributing `$ai_generation` / `$ai_trace` events by a dimension (model, `$ai_span_name`, tool, user, `ai_product`, a custom dim) to show _which_ slice drove the move — that's the difference between "cost is up" and a reportable finding.-- **Sample.** Pull one or two representative traces via `query-llm-trace` (or a failing generation sampled from the raw `$ai_evaluation` rows) and cite concrete trace / generation / evaluation IDs in the evidence. `llma-evaluation-summary-create` groups failures into patterns with example IDs when it's available, but it's billed and can 500 — don't depend on it.+- **Sample.** Pull one or two representative traces via `query-llm-trace` (or a failing generation sampled from the raw `$ai_evaluation` rows) and cite concrete trace / generation / evaluation IDs in the evidence. `llma-evaluation-summary-create` groups failures into patterns with example IDs when it's available, but it's billed and can 500 — don't depend on it. A trace you cite links to `/ai-observability/traces/<trace_id>`: use the `_posthogUrl` on the query result. If you only have an id from raw SQL, call `query-llm-trace` with that id and the relevant date range, then use its `_posthogUrl`; if the trace cannot be fetched, cite the bare id. Never build the link by serializing the trace query into `/insights/new#q=…`, which opens an empty insight because `TraceQuery` isn't an insight source.- **Group as a pattern** when a trend spans many traces: describe the shared shape (same model + same span, same tool error, same prompt version) rather than listing rows.### Save memory as you godiff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.tsindex f5841b7643f1..f81767875829 100644--- a/services/mcp/scripts/yaml-config-schema.ts+++ b/services/mcp/scripts/yaml-config-schema.ts@@ -515,6 +515,10 @@ export const QueryWrapperToolConfigSchema = z/*** Override the URL enrichment prefix. When set, `_posthogUrl` uses* `{baseUrl}{url_prefix}` instead of the default `/insights/new#q=...`.+ * Required for any query kind the insight editor can't render as an+ * `InsightVizNode` source (TraceQuery, TracesQuery, ...), which would+ * otherwise link to an empty insight. May contain `{param}` placeholders+ * filled from the query body, e.g. `/ai-observability/traces/{traceId}`.*/url_prefix: z.string().optional(),/**diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex eb0b13f6f9dd..12a0927d3af6 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -2613,6 +2613,12 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {name: 'query-llm-traces-list',schema: AssistantTracesQuery,kind: 'TracesQuery',+ urlPrefix: '/ai-observability/traces',+ }),+ 'query-llm-trace': createQueryWrapper({+ name: 'query-llm-trace',+ schema: AssistantTraceQuery,+ kind: 'TraceQuery',+ urlPrefix: '/ai-observability/traces/{traceId}',}),- 'query-llm-trace': createQueryWrapper({ name: 'query-llm-trace', schema: AssistantTraceQuery, kind: 'TraceQuery' }),}diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.tsindex 3669a42fe9ca..f92130aa7f7d 100644--- a/services/mcp/src/tools/query-wrapper-factory.ts+++ b/services/mcp/src/tools/query-wrapper-factory.ts@@ -25,7 +25,11 @@ interface QueryWrapperConfig<T extends ZodObjectAny> {* override entirely and returns raw JSON. Omit to fall back to the default TOON encoding.*/outputFormat?: 'optimized' | 'json'- /** When set, `_posthogUrl` uses `{baseUrl}{urlPrefix}` instead of `/insights/new#q=...`. */+ /**+ * When set, `_posthogUrl` uses `{baseUrl}{urlPrefix}` instead of `/insights/new#q=...`.+ * May contain `{param}` placeholders filled from the query body, e.g.+ * `/ai-observability/traces/{traceId}`.+ */urlPrefix?: string}@@ -70,6 +74,47 @@ function withoutTestAccountFilterDefault<T extends ZodObjectAny>(schema: T): T {}) as unknown as T}+/**+ * Kea Router decodes paths before route matching, and scenes decode captured parameters again.+ * Double encoding keeps opaque values within the route matcher character set through both steps.+ */+function encodeRouterPathSegment(value: string): string {+ const encodedValue = encodeURIComponent(value).replace(+ /[!'()*]/g,+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`+ )+ return encodeURIComponent(encodedValue).replace(+ /[!'()*]/g,+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`+ )+}++/**+ * Fill `{param}` placeholders in a `urlPrefix` from the query body. A placeholder the query+ * leaves unset (or sets to something other than a non-empty string/number) truncates the path+ * at that segment, so the link falls back to the closest parent page instead of pointing at a+ * literal `{traceId}`.+ */+function resolveUrlPrefix(urlPrefix: string, query: Record<string, unknown>): string {+ if (!urlPrefix.includes('{')) {+ return urlPrefix+ }+ const segments: string[] = []+ for (const segment of urlPrefix.split('/')) {+ if (!segment.includes('{')) {+ segments.push(segment)+ continue+ }+ const paramName = /^\{(\w+)\}$/.exec(segment)?.[1]+ const value = paramName === undefined ? undefined : query[paramName]+ if ((typeof value !== 'string' && typeof value !== 'number') || value === '') {+ break+ }+ segments.push(encodeRouterPathSegment(String(value)))+ }+ return segments.join('/')+}+function buildInsightUrl(kind: 'InsightVizNode' | 'DataTableNode',query: Record<string, unknown>,@@ -77,7 +122,7 @@ function buildInsightUrl(urlPrefix?: string): string {if (urlPrefix) {- return `${baseUrl}${urlPrefix}`+ return `${baseUrl}${resolveUrlPrefix(urlPrefix, query)}`}const q = encodeURIComponent(JSON.stringify({ kind, source: query }))return `${baseUrl}/insights/new#q=${q}`diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.tsindex 97cc3bbef77b..66ce570f395d 100644--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts@@ -206,6 +206,31 @@ describe('createQueryWrapper _posthogUrl', () => {expect(result._posthogUrl).toBe('http://localhost:8010/project/1/error_tracking')expect(result._posthogUrl).not.toContain('InsightVizNode')})++ const traceSchema = z.object({ traceId: z.string().optional() })++ it.each([+ ['fills a placeholder from the query body', { traceId: 'abc-123' }, '/ai-observability/traces/abc-123'],+ ['encodes a placeholder value', { traceId: 'a/b c' }, '/ai-observability/traces/a%252Fb%2520c'],+ [+ 'encodes an opaque placeholder value',+ { traceId: 'trace](id /?#' },+ '/ai-observability/traces/trace%255D%2528id%2520%252F%253F%2523',+ ],+ ['drops the segment when the placeholder is unset', {}, '/ai-observability/traces'],+ ])('%s', async (_name, params, expectedPath) => {+ const context = createMockContext()+ const tool = createQueryWrapper({+ name: 'test',+ schema: traceSchema,+ kind: 'TraceQuery',+ urlPrefix: '/ai-observability/traces/{traceId}',+ })()++ const result = (await tool.handler(context, params)) as any++ expect(result._posthogUrl).toBe(`http://localhost:8010/project/1${expectedPath}`)+ })})describe('createQueryWrapper output_format handling', () => {