: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): group query-llm-trace tools under AI observability (#76776)
Radu Raiceae3b2a5805aad
diff --git a/services/mcp/definitions/prompts/query-llm-trace.md b/products/ai_observability/mcp/prompts/query-llm-trace.mdsimilarity index 100%rename from services/mcp/definitions/prompts/query-llm-trace.mdrename to products/ai_observability/mcp/prompts/query-llm-trace.mddiff --git a/services/mcp/definitions/prompts/query-llm-traces-list.md b/products/ai_observability/mcp/prompts/query-llm-traces-list.mdsimilarity index 100%rename from services/mcp/definitions/prompts/query-llm-traces-list.mdrename to products/ai_observability/mcp/prompts/query-llm-traces-list.mddiff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 526a3eedccd3..a0e21455b529 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -1183,3 +1183,34 @@ tools:taggers-update:operation: taggers_updateenabled: false+wrappers:+ query-llm-traces-list:+ schema_ref: AssistantTracesQuery+ enabled: true+ scopes:+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List LLM traces+ description_file: ./prompts/query-llm-traces-list.md+ system_prompt_hint: LLM/AI trace listing and inspection+ exclude_properties:+ - response+ - modifiers+ query-llm-trace:+ schema_ref: AssistantTraceQuery+ enabled: true+ scopes:+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get LLM trace+ description_file: ./prompts/query-llm-trace.md+ system_prompt_hint: Single LLM/AI trace deep-dive+ exclude_properties:+ - response+ - modifiersdiff --git a/services/mcp/definitions/query-wrappers.yaml b/services/mcp/definitions/query-wrappers.yamlindex 8d5b84d8b086..75580fe35a79 100644--- a/services/mcp/definitions/query-wrappers.yaml+++ b/services/mcp/definitions/query-wrappers.yaml@@ -122,38 +122,6 @@ wrappers:- modifiers- samplingFactor- query-llm-traces-list:- schema_ref: AssistantTracesQuery- enabled: true- scopes:- - query:read- annotations:- readOnly: true- destructive: false- idempotent: true- title: List LLM traces- description_file: ./prompts/query-llm-traces-list.md- system_prompt_hint: LLM/AI trace listing and inspection- exclude_properties:- - response- - modifiers-- query-llm-trace:- schema_ref: AssistantTraceQuery- enabled: true- scopes:- - query:read- annotations:- readOnly: true- destructive: false- idempotent: true- title: Get LLM trace- description_file: ./prompts/query-llm-trace.md- system_prompt_hint: Single LLM/AI trace deep-dive- exclude_properties:- - response- - modifiers-query-trends-actors:schema_ref: AssistantTrendsActorsQueryenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c33797125a51..921ee3620e9d 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7200,8 +7200,8 @@},"query-llm-trace": {"description": "Fetch a single LLM trace by its trace ID for deep inspection. Returns the complete trace with all nested events and their full properties — including inputs, outputs, model parameters, costs, and errors. Use after finding a trace via `query-llm-traces-list` to inspect the complete event tree.\n\nUse cases:\n\n- Inspect the full input/output of each generation in a trace\n- Debug a specific error trace found in the list\n- Examine the agent's decision-making flow across spans\n- Review tool calls and their results within a trace\n- Analyze token usage and costs per generation\n\nCRITICAL: This tool requires a `traceId`. Get the trace ID from `query-llm-traces-list` results first.\n\n# Response shape\n\nThe response contains a single trace in JSON format with:\n\n- `id` — the trace ID\n- `traceName` — name of the trace (if set via SDK)\n- `createdAt` — timestamp of the first event in the trace\n- `distinctId` — the person's distinct ID\n- `aiSessionId` — session ID grouping related traces (e.g., a conversation)\n- `totalLatency` — total latency in seconds\n- `inputTokens` / `outputTokens` — token counts across all generations\n- `inputCost` / `outputCost` / `totalCost` — costs in USD\n- `inputState` / `outputState` — JSON input/output state from the root `$ai_trace` event (e.g., conversation messages)\n- `events` — **all** child events in the trace at every nesting depth (not just direct children). Each event has full `properties`.\n\nUnlike `query-llm-traces-list`, this tool does NOT return `errorCount`, `isSupportTrace`, or `tools` — those are summary fields on the list tool only.\n\n# Event types and their properties\n\nEach event in `events` has an `event` field indicating its type. Key properties vary by type:\n\n- **`$ai_generation`** / **`$ai_embedding`** — an LLM or embedding API call. Properties include `$ai_input` (input prompt JSON), `$ai_output_choices` (output message JSON), `$ai_model`, `$ai_provider`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_input_cost_usd`, `$ai_output_cost_usd`, `$ai_total_cost_usd`, `$ai_tools_called`, `$ai_is_error`, `$ai_error`.\n- **`$ai_span`** — a unit of work within a trace (e.g., a retrieval step, tool execution). Properties include `$ai_input_state`, `$ai_output_state`, `$ai_latency`, `$ai_span_name`, `$ai_parent_id`.\n- **`$ai_metric`** — a named evaluation metric. Properties include `$ai_metric_name`, `$ai_metric_value`.\n- **`$ai_feedback`** — user-provided feedback. Properties include `$ai_feedback_text`.\n\nNote: `$ai_trace` events are NOT included in the `events` array — their data is surfaced via the trace-level `inputState`, `outputState`, and `traceName` fields.\n\n# Tree structure (IDs and parent-child relationships)\n\nEvents in a trace form a tree. Each event carries three IDs that define its position:\n\n- `$ai_trace_id` — present on every event, identifies which trace it belongs to (same as the trace's `id`)\n- `$ai_span_id` (or `$ai_generation_id` for generations) — the event's own unique identifier\n- `$ai_parent_id` — points to the parent event's `$ai_span_id`\n\nTo reconstruct the tree:\n\n1. Events where `$ai_parent_id` equals `$ai_trace_id` are **root-level children** of the trace\n2. Other events are children of the event whose `$ai_span_id` matches their `$ai_parent_id`\n3. Group events by `$ai_parent_id` and walk from root children downward\n\nGenerations (`$ai_generation`) and embeddings (`$ai_embedding`) are always leaf nodes. Spans (`$ai_span`) can have children.\n\n# Examples\n\n## Fetch a trace by ID\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\"\n}\n```\n\n## Fetch with a date range hint\n\nIf the trace is old, provide a date range to help the query find it efficiently:\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\",\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Response size\n\nTo protect the agent's context window, very large traces are compacted before they reach you. Long string values are truncated (with a `… [truncated N chars]` marker), oversized arrays and objects have their tail members dropped (`… [N more items omitted]` / an `_omittedKeys` count), and if a trace is still over the size limit, trailing events are dropped and a `_truncated` object reports how many events were omitted. When you see any of these markers, open the trace in PostHog for the full, untruncated data, or narrow the query to the specific events you need. The underlying trace data is never altered — only this response is bounded.\n\n# Reminders\n\n- Always get the `traceId` from `query-llm-traces-list` results — do not guess or fabricate trace IDs.\n- If no date range is provided, the default lookback window is used. For older traces, provide an explicit `dateRange`.\n- The `events` array contains ALL events in the trace (including deeply nested ones), making this suitable for full tree reconstruction.\n- Use `query-llm-traces-list` first to find traces, then this tool to inspect a specific one.",- "category": "Query wrappers",- "feature": "insights",+ "category": "AI observability",+ "feature": "llm_analytics","summary": "Get LLM trace","title": "Get LLM trace","required_scopes": ["query:read"],@@ -7215,8 +7215,8 @@},"query-llm-traces-list": {"description": "List LLM traces to inspect AI/LLM usage across your application. Returns traces with their events, latency, token usage, costs, errors, and other metadata. Use this tool for AI observability — debugging slow generations, investigating errors, analyzing token spend, and auditing LLM behavior.\n\nUse 'read-data-schema' to discover available event properties for filtering (e.g. `$ai_model`, `$ai_provider`).\n\nExamples of use cases include:\n\n- How much are we spending on LLM tokens per day?\n- Which LLM generations are the slowest?\n- Are there any traces with errors in the last 24 hours?\n- What models are being used and how do their costs compare?\n- Show me traces for a specific user to debug their experience.\n- Are there any traces with unusually high token usage?\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Common AI properties include `$ai_model`, `$ai_provider`, `$ai_trace_id`, `$ai_session_id`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_total_cost_usd`, `$ai_is_error`, `$ai_http_status`, `$ai_span_name`.\n- **Note:** `$ai_is_error` and `$ai_error` are valid filter properties but may not appear via `read-data-schema`. Use `$ai_is_error` with operator `exact` and value `[\"true\"]` to find error traces, or use `$ai_error` with `is set` to find traces with error messages.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 7 days as a default time period.\n\n# Traces guidelines\n\nThis is a listing tool, not a visualization/insight tool. It returns a paginated list of LLM traces — it does NOT support series, breakdowns, math aggregations, or chart types.\n\n## Response shape\n\nEach trace in the results contains:\n\n- `id` — unique trace ID\n- `traceName` — name of the trace (if set via SDK)\n- `createdAt` — timestamp of the first event in the trace\n- `distinctId` — the person's distinct ID\n- `aiSessionId` — session ID grouping related traces (e.g., a conversation)\n- `totalLatency` — total latency in seconds\n- `inputTokens` / `outputTokens` — token counts across all generations in the trace\n- `inputCost` / `outputCost` / `totalCost` — costs in USD\n- `inputState` / `outputState` — JSON input/output state of the trace (e.g., conversation messages), from the `$ai_trace` event\n- `errorCount` — number of errors in the trace\n- `isSupportTrace` — whether the trace was from a support impersonation session\n- `tools` — list of tool names called during the trace\n- `events` — list of direct child events (generations, metrics, feedback). Each event's `properties` contains the full event data — see \"Event types and their properties\" below.\n\n## Event types and their properties\n\nEach event in `events` has an `event` field indicating its type. The key properties vary by type:\n\n- **`$ai_generation`** / **`$ai_embedding`** — an LLM or embedding API call. Properties include `$ai_input` (input prompt JSON), `$ai_output_choices` (output message JSON), `$ai_model`, `$ai_provider`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_input_cost_usd`, `$ai_output_cost_usd`, `$ai_total_cost_usd`, `$ai_tools_called`, `$ai_is_error`, `$ai_error`.\n- **`$ai_span`** — a unit of work within a trace (e.g., a retrieval step, a tool execution). Properties include `$ai_input_state`, `$ai_output_state`, `$ai_latency`, `$ai_span_name`, `$ai_parent_id`.\n- **`$ai_trace`** — the root trace event. Properties include `$ai_input_state` (e.g., conversation messages sent), `$ai_output_state` (e.g., final response), `$ai_span_name`.\n- **`$ai_metric`** — a named evaluation metric. Properties include `$ai_metric_name`, `$ai_metric_value`.\n- **`$ai_feedback`** — user-provided feedback. Properties include `$ai_feedback_text`.\n\nAll event types share `$ai_trace_id`, `$ai_span_id`, and `$ai_parent_id` for tree structure (see below).\n\n## Tree structure (IDs and parent-child relationships)\n\nEvents in a trace form a tree. Each event carries three IDs that define its position:\n\n- `$ai_trace_id` — present on every event, identifies which trace it belongs to (same as the trace's `id`)\n- `$ai_span_id` (or `$ai_generation_id` for generations) — the event's own unique identifier\n- `$ai_parent_id` — points to the parent event's `$ai_span_id`\n\nTo reconstruct the tree:\n\n1. Events where `$ai_parent_id` equals `$ai_trace_id` are **root-level children** of the trace\n2. Other events are children of the event whose `$ai_span_id` matches their `$ai_parent_id`\n3. Group events by `$ai_parent_id` and walk from root children downward\n\nGenerations (`$ai_generation`) and embeddings (`$ai_embedding`) are always leaf nodes. Spans (`$ai_span`) can have children.\n\n**Important:** This list tool only returns **direct children** of the trace (events where `$ai_parent_id` = trace ID) plus all `$ai_metric` and `$ai_feedback` events — NOT deeply nested events. For the full event tree with all nested children, use `query-llm-trace` with the trace's `id`.\n\n## Response size\n\nTo protect the agent's context window, the response is bounded before it reaches you. Long string values are truncated (with a `… [truncated N chars]` marker) and oversized arrays/objects have their tail members dropped. If the combined list is still too large, trailing traces are dropped and a final `{ \"_truncated\": { \"omittedTraces\": N, ... } }` entry reports how many. When you see these markers, narrow the query (shorter date range, filters, or a smaller `limit`) or fetch a specific trace with `query-llm-trace`. The underlying data is never altered — only this response is bounded.\n\n## Pagination\n\nUse `limit` and `offset` for pagination. The default limit is 100. The response includes a `hasMore` field indicating whether more results are available.\n\n## Filtering\n\n- `filterTestAccounts` — exclude internal/test users\n- `filterSupportTraces` — exclude support impersonation traces\n- `personId` — filter by a specific person UUID\n- `groupKey` + `groupTypeIndex` — filter by a specific group\n- `randomOrder` — use random ordering instead of newest-first (useful for representative sampling)\n\n# Examples\n\n## Recent traces with errors\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"filterTestAccounts\": true,\n \"properties\": [{ \"key\": \"$ai_is_error\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"true\"] }],\n \"limit\": 50\n}\n```\n\n## Traces for a specific model\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"filterTestAccounts\": true,\n \"properties\": [{ \"key\": \"$ai_model\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"gpt-4o\"] }]\n}\n```\n\n## Traces for a specific person\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"personId\": \"01234567-89ab-cdef-0123-456789abcdef\",\n \"filterTestAccounts\": true\n}\n```\n\n## Random sample of traces (avoids recency bias)\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true,\n \"randomOrder\": true,\n \"limit\": 20\n}\n```\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.\n- This tool returns raw trace data — it does not aggregate or visualize. For aggregated LLM metrics over time (e.g. total token usage per day), use `query-trends` with AI events like `$ai_generation` instead.\n- Use `filterTestAccounts: true` by default to exclude internal users unless the user asks otherwise.\n- The default time range is last 7 days. LLM trace data tends to be recent, so shorter ranges are usually appropriate.\n- For deep inspection of a single trace (full event tree with all nested children and complete properties), use `query-llm-trace` with the trace's `id`.",- "category": "Query wrappers",- "feature": "insights",+ "category": "AI observability",+ "feature": "llm_analytics","summary": "List LLM traces","title": "List LLM traces","required_scopes": ["query:read"],diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 23323727ec3c..75b512385f3b 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7782,8 +7782,8 @@},"query-llm-trace": {"description": "Fetch a single LLM trace by its trace ID for deep inspection. Returns the complete trace with all nested events and their full properties — including inputs, outputs, model parameters, costs, and errors. Use after finding a trace via `query-llm-traces-list` to inspect the complete event tree.\n\nUse cases:\n\n- Inspect the full input/output of each generation in a trace\n- Debug a specific error trace found in the list\n- Examine the agent's decision-making flow across spans\n- Review tool calls and their results within a trace\n- Analyze token usage and costs per generation\n\nCRITICAL: This tool requires a `traceId`. Get the trace ID from `query-llm-traces-list` results first.\n\n# Response shape\n\nThe response contains a single trace in JSON format with:\n\n- `id` — the trace ID\n- `traceName` — name of the trace (if set via SDK)\n- `createdAt` — timestamp of the first event in the trace\n- `distinctId` — the person's distinct ID\n- `aiSessionId` — session ID grouping related traces (e.g., a conversation)\n- `totalLatency` — total latency in seconds\n- `inputTokens` / `outputTokens` — token counts across all generations\n- `inputCost` / `outputCost` / `totalCost` — costs in USD\n- `inputState` / `outputState` — JSON input/output state from the root `$ai_trace` event (e.g., conversation messages)\n- `events` — **all** child events in the trace at every nesting depth (not just direct children). Each event has full `properties`.\n\nUnlike `query-llm-traces-list`, this tool does NOT return `errorCount`, `isSupportTrace`, or `tools` — those are summary fields on the list tool only.\n\n# Event types and their properties\n\nEach event in `events` has an `event` field indicating its type. Key properties vary by type:\n\n- **`$ai_generation`** / **`$ai_embedding`** — an LLM or embedding API call. Properties include `$ai_input` (input prompt JSON), `$ai_output_choices` (output message JSON), `$ai_model`, `$ai_provider`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_input_cost_usd`, `$ai_output_cost_usd`, `$ai_total_cost_usd`, `$ai_tools_called`, `$ai_is_error`, `$ai_error`.\n- **`$ai_span`** — a unit of work within a trace (e.g., a retrieval step, tool execution). Properties include `$ai_input_state`, `$ai_output_state`, `$ai_latency`, `$ai_span_name`, `$ai_parent_id`.\n- **`$ai_metric`** — a named evaluation metric. Properties include `$ai_metric_name`, `$ai_metric_value`.\n- **`$ai_feedback`** — user-provided feedback. Properties include `$ai_feedback_text`.\n\nNote: `$ai_trace` events are NOT included in the `events` array — their data is surfaced via the trace-level `inputState`, `outputState`, and `traceName` fields.\n\n# Tree structure (IDs and parent-child relationships)\n\nEvents in a trace form a tree. Each event carries three IDs that define its position:\n\n- `$ai_trace_id` — present on every event, identifies which trace it belongs to (same as the trace's `id`)\n- `$ai_span_id` (or `$ai_generation_id` for generations) — the event's own unique identifier\n- `$ai_parent_id` — points to the parent event's `$ai_span_id`\n\nTo reconstruct the tree:\n\n1. Events where `$ai_parent_id` equals `$ai_trace_id` are **root-level children** of the trace\n2. Other events are children of the event whose `$ai_span_id` matches their `$ai_parent_id`\n3. Group events by `$ai_parent_id` and walk from root children downward\n\nGenerations (`$ai_generation`) and embeddings (`$ai_embedding`) are always leaf nodes. Spans (`$ai_span`) can have children.\n\n# Examples\n\n## Fetch a trace by ID\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\"\n}\n```\n\n## Fetch with a date range hint\n\nIf the trace is old, provide a date range to help the query find it efficiently:\n\n```json\n{\n \"kind\": \"TraceQuery\",\n \"traceId\": \"c9222e05-8708-41b8-98ea-d4a21849e761\",\n \"dateRange\": { \"date_from\": \"-30d\" }\n}\n```\n\n# Response size\n\nTo protect the agent's context window, very large traces are compacted before they reach you. Long string values are truncated (with a `… [truncated N chars]` marker), oversized arrays and objects have their tail members dropped (`… [N more items omitted]` / an `_omittedKeys` count), and if a trace is still over the size limit, trailing events are dropped and a `_truncated` object reports how many events were omitted. When you see any of these markers, open the trace in PostHog for the full, untruncated data, or narrow the query to the specific events you need. The underlying trace data is never altered — only this response is bounded.\n\n# Reminders\n\n- Always get the `traceId` from `query-llm-traces-list` results — do not guess or fabricate trace IDs.\n- If no date range is provided, the default lookback window is used. For older traces, provide an explicit `dateRange`.\n- The `events` array contains ALL events in the trace (including deeply nested ones), making this suitable for full tree reconstruction.\n- Use `query-llm-traces-list` first to find traces, then this tool to inspect a specific one.",- "category": "Query wrappers",- "feature": "insights",+ "category": "AI observability",+ "feature": "llm_analytics","summary": "Get LLM trace","title": "Get LLM trace","required_scopes": ["query:read"],@@ -7797,8 +7797,8 @@},"query-llm-traces-list": {"description": "List LLM traces to inspect AI/LLM usage across your application. Returns traces with their events, latency, token usage, costs, errors, and other metadata. Use this tool for AI observability — debugging slow generations, investigating errors, analyzing token spend, and auditing LLM behavior.\n\nUse 'read-data-schema' to discover available event properties for filtering (e.g. `$ai_model`, `$ai_provider`).\n\nExamples of use cases include:\n\n- How much are we spending on LLM tokens per day?\n- Which LLM generations are the slowest?\n- Are there any traces with errors in the last 24 hours?\n- What models are being used and how do their costs compare?\n- Show me traces for a specific user to debug their experience.\n- Are there any traces with unusually high token usage?\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.\n\nIMPORTANT: Do not check if a property is set unless the user explicitly asks for it.\n\nWhen using a property filter, you should:\n\n- **Prioritize properties directly related to the context or objective of the user's query.** Common AI properties include `$ai_model`, `$ai_provider`, `$ai_trace_id`, `$ai_session_id`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_total_cost_usd`, `$ai_is_error`, `$ai_http_status`, `$ai_span_name`.\n- **Note:** `$ai_is_error` and `$ai_error` are valid filter properties but may not appear via `read-data-schema`. Use `$ai_is_error` with operator `exact` and value `[\"true\"]` to find error traces, or use `$ai_error` with `is set` to find traces with error messages.\n- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.\n- After selecting a property, **validate that the property value accurately reflects the intended criteria**.\n- **Find the suitable operator for type** (e.g., `contains`, `is set`).\n- If the operator requires a value, use the `read-data-schema` tool to find the property values.\n\nInfer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.\n\nSupported operators for the String type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- contains (icontains)\n- doesn't contain (not_icontains)\n- matches regex (regex)\n- doesn't match regex (not_regex)\n- is set\n- is not set\n\nSupported operators for the Numeric type are:\n\n- equals (exact)\n- doesn't equal (is_not)\n- greater than (gt)\n- less than (lt)\n- is set\n- is not set\n\nSupported operators for the DateTime type are:\n\n- equals (is_date_exact)\n- doesn't equal (is_not for existence check)\n- before (is_date_before)\n- after (is_date_after)\n- is set\n- is not set\n\nSupported operators for the Boolean type are:\n\n- equals\n- doesn't equal\n- is set\n- is not set\n\nAll operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).\n\n## Time period\n\nYou should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 7 days as a default time period.\n\n# Traces guidelines\n\nThis is a listing tool, not a visualization/insight tool. It returns a paginated list of LLM traces — it does NOT support series, breakdowns, math aggregations, or chart types.\n\n## Response shape\n\nEach trace in the results contains:\n\n- `id` — unique trace ID\n- `traceName` — name of the trace (if set via SDK)\n- `createdAt` — timestamp of the first event in the trace\n- `distinctId` — the person's distinct ID\n- `aiSessionId` — session ID grouping related traces (e.g., a conversation)\n- `totalLatency` — total latency in seconds\n- `inputTokens` / `outputTokens` — token counts across all generations in the trace\n- `inputCost` / `outputCost` / `totalCost` — costs in USD\n- `inputState` / `outputState` — JSON input/output state of the trace (e.g., conversation messages), from the `$ai_trace` event\n- `errorCount` — number of errors in the trace\n- `isSupportTrace` — whether the trace was from a support impersonation session\n- `tools` — list of tool names called during the trace\n- `events` — list of direct child events (generations, metrics, feedback). Each event's `properties` contains the full event data — see \"Event types and their properties\" below.\n\n## Event types and their properties\n\nEach event in `events` has an `event` field indicating its type. The key properties vary by type:\n\n- **`$ai_generation`** / **`$ai_embedding`** — an LLM or embedding API call. Properties include `$ai_input` (input prompt JSON), `$ai_output_choices` (output message JSON), `$ai_model`, `$ai_provider`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_input_cost_usd`, `$ai_output_cost_usd`, `$ai_total_cost_usd`, `$ai_tools_called`, `$ai_is_error`, `$ai_error`.\n- **`$ai_span`** — a unit of work within a trace (e.g., a retrieval step, a tool execution). Properties include `$ai_input_state`, `$ai_output_state`, `$ai_latency`, `$ai_span_name`, `$ai_parent_id`.\n- **`$ai_trace`** — the root trace event. Properties include `$ai_input_state` (e.g., conversation messages sent), `$ai_output_state` (e.g., final response), `$ai_span_name`.\n- **`$ai_metric`** — a named evaluation metric. Properties include `$ai_metric_name`, `$ai_metric_value`.\n- **`$ai_feedback`** — user-provided feedback. Properties include `$ai_feedback_text`.\n\nAll event types share `$ai_trace_id`, `$ai_span_id`, and `$ai_parent_id` for tree structure (see below).\n\n## Tree structure (IDs and parent-child relationships)\n\nEvents in a trace form a tree. Each event carries three IDs that define its position:\n\n- `$ai_trace_id` — present on every event, identifies which trace it belongs to (same as the trace's `id`)\n- `$ai_span_id` (or `$ai_generation_id` for generations) — the event's own unique identifier\n- `$ai_parent_id` — points to the parent event's `$ai_span_id`\n\nTo reconstruct the tree:\n\n1. Events where `$ai_parent_id` equals `$ai_trace_id` are **root-level children** of the trace\n2. Other events are children of the event whose `$ai_span_id` matches their `$ai_parent_id`\n3. Group events by `$ai_parent_id` and walk from root children downward\n\nGenerations (`$ai_generation`) and embeddings (`$ai_embedding`) are always leaf nodes. Spans (`$ai_span`) can have children.\n\n**Important:** This list tool only returns **direct children** of the trace (events where `$ai_parent_id` = trace ID) plus all `$ai_metric` and `$ai_feedback` events — NOT deeply nested events. For the full event tree with all nested children, use `query-llm-trace` with the trace's `id`.\n\n## Response size\n\nTo protect the agent's context window, the response is bounded before it reaches you. Long string values are truncated (with a `… [truncated N chars]` marker) and oversized arrays/objects have their tail members dropped. If the combined list is still too large, trailing traces are dropped and a final `{ \"_truncated\": { \"omittedTraces\": N, ... } }` entry reports how many. When you see these markers, narrow the query (shorter date range, filters, or a smaller `limit`) or fetch a specific trace with `query-llm-trace`. The underlying data is never altered — only this response is bounded.\n\n## Pagination\n\nUse `limit` and `offset` for pagination. The default limit is 100. The response includes a `hasMore` field indicating whether more results are available.\n\n## Filtering\n\n- `filterTestAccounts` — exclude internal/test users\n- `filterSupportTraces` — exclude support impersonation traces\n- `personId` — filter by a specific person UUID\n- `groupKey` + `groupTypeIndex` — filter by a specific group\n- `randomOrder` — use random ordering instead of newest-first (useful for representative sampling)\n\n# Examples\n\n## Recent traces with errors\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"filterTestAccounts\": true,\n \"properties\": [{ \"key\": \"$ai_is_error\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"true\"] }],\n \"limit\": 50\n}\n```\n\n## Traces for a specific model\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-7d\" },\n \"filterTestAccounts\": true,\n \"properties\": [{ \"key\": \"$ai_model\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"gpt-4o\"] }]\n}\n```\n\n## Traces for a specific person\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"personId\": \"01234567-89ab-cdef-0123-456789abcdef\",\n \"filterTestAccounts\": true\n}\n```\n\n## Random sample of traces (avoids recency bias)\n\n```json\n{\n \"kind\": \"TracesQuery\",\n \"dateRange\": { \"date_from\": \"-30d\" },\n \"filterTestAccounts\": true,\n \"randomOrder\": true,\n \"limit\": 20\n}\n```\n\n# Reminders\n\n- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.\n- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.\n- This tool returns raw trace data — it does not aggregate or visualize. For aggregated LLM metrics over time (e.g. total token usage per day), use `query-trends` with AI events like `$ai_generation` instead.\n- Use `filterTestAccounts: true` by default to exclude internal users unless the user asks otherwise.\n- The default time range is last 7 days. LLM trace data tends to be recent, so shorter ranges are usually appropriate.\n- For deep inspection of a single trace (full event tree with all nested children and complete properties), use `query-llm-trace` with the trace's `id`.",- "category": "Query wrappers",- "feature": "insights",+ "category": "AI observability",+ "feature": "llm_analytics","summary": "List LLM traces","title": "List LLM traces","required_scopes": ["query:read"],diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex aaddfc2a7de7..135242d13fe0 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -85,6 +85,7 @@ import {TaggersTestHogCreateBody,} from '@/generated/ai_observability/api'import { PromptListInputSchema, ScoreDefinitionConfigSchema } from '@/schema/tool-inputs'+import { createQueryWrapper } from '@/tools/query-wrapper-factory'import {withPostHogUrl,withInformationalResponse,@@ -1872,6 +1873,324 @@ const llmaTraceReviewUpdate = (): ToolBase<},})+// --- Query wrapper schemas from schema.json ---++const AssistantDateRange = z.object({+ date_from: z.string().describe('ISO8601 date string.'),+ date_to: z.string().nullable().describe('ISO8601 date string.').optional(),+})++const AssistantDurationRange = z.object({+ date_from: z+ .string()+ .describe(+ "Duration in the past. Supported units are: `h` (hour), `d` (day), `w` (week), `m` (month), `y` (year), `all` (all time). Use the `Start` suffix to define the exact left date boundary. Examples: `-1d` last day from now, `-180d` last 180 days from now, `mStart` this month start, `-1dStart` yesterday's start."+ ),+})++const AssistantDateRangeFilter = z.union([AssistantDateRange, AssistantDurationRange])++const integer = z.coerce.number().int()++const AssistantStringOrBooleanValuePropertyFilterOperator = z.enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+])++const AssistantGenericPropertyFilterType = z.enum(['event', 'person', 'session', 'feature'])++const AssistantNumericValuePropertyFilterOperator = z.enum(['exact', 'gt', 'lt'])++const AssistantArrayPropertyFilterOperator = z.enum(['exact', 'is_not'])++const AssistantDateTimePropertyFilterOperator = z.enum(['is_date_exact', 'is_date_before', 'is_date_after'])++const AssistantSetPropertyFilterOperator = z.enum(['is_set', 'is_not_set'])++const AssistantGenericPropertyFilter = z.union([+ z.object({+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantStringOrBooleanValuePropertyFilterOperator.describe(+ '`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.'+ ),+ type: AssistantGenericPropertyFilterType,+ value: z+ .string()+ .describe(+ 'Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.'+ ),+ }),+ z.object({+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantNumericValuePropertyFilterOperator,+ type: AssistantGenericPropertyFilterType,+ value: z.coerce.number(),+ }),+ z.object({+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantArrayPropertyFilterOperator.describe(+ '`exact` - exact match of any of the values. `is_not` - does not match any of the values.'+ ),+ type: AssistantGenericPropertyFilterType,+ value: z+ .array(z.string())+ .describe(+ 'Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string "true" or "false".'+ ),+ }),+ z.object({+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantDateTimePropertyFilterOperator,+ type: AssistantGenericPropertyFilterType,+ value: z.string().describe('Value must be a date in ISO 8601 format.'),+ }),+ z.object({+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantSetPropertyFilterOperator.describe(+ "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected."+ ),+ type: AssistantGenericPropertyFilterType,+ }),+])++const AssistantGroupPropertyFilter = z.union([+ z.object({+ group_type_index: integer.describe('Index of the group type from the group mapping.'),+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantStringOrBooleanValuePropertyFilterOperator.describe(+ '`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.'+ ),+ type: z.literal('group').default('group'),+ value: z+ .string()+ .describe(+ 'Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.'+ ),+ }),+ z.object({+ group_type_index: integer.describe('Index of the group type from the group mapping.'),+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantNumericValuePropertyFilterOperator,+ type: z.literal('group').default('group'),+ value: z.coerce.number(),+ }),+ z.object({+ group_type_index: integer.describe('Index of the group type from the group mapping.'),+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantArrayPropertyFilterOperator.describe(+ '`exact` - exact match of any of the values. `is_not` - does not match any of the values.'+ ),+ type: z.literal('group').default('group'),+ value: z+ .array(z.string())+ .describe(+ 'Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string "true" or "false".'+ ),+ }),+ z.object({+ group_type_index: integer.describe('Index of the group type from the group mapping.'),+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantDateTimePropertyFilterOperator,+ type: z.literal('group').default('group'),+ value: z.string().describe('Value must be a date in ISO 8601 format.'),+ }),+ z.object({+ group_type_index: integer.describe('Index of the group type from the group mapping.'),+ key: z.string().describe('Use one of the properties the user has provided in the plan.'),+ operator: AssistantSetPropertyFilterOperator.describe(+ "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected."+ ),+ type: z.literal('group').default('group'),+ }),+])++const AssistantCohortPropertyFilter = z.object({+ key: z.literal('id').default('id'),+ operator: z.enum(['in', 'not_in']).default('in'),+ type: z+ .literal('cohort')+ .describe(+ 'Filter events by cohort membership. Use this to narrow down results to persons belonging to a specific cohort. Use `operator: "in"` to include cohort members, or `operator: "not_in"` to exclude them. Examples:\n- Include: `{ type: "cohort", key: "id", value: 42, operator: "in" }`\n- Exclude: `{ type: "cohort", key: "id", value: 42, operator: "not_in" }`'+ )+ .default('cohort'),+ value: integer.describe('The cohort ID to filter by.'),+})++const AssistantElementPropertyFilter = z.union([+ z.object({+ key: z+ .enum(['tag_name', 'text', 'href', 'selector'])+ .describe(+ 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'+ ),+ operator: AssistantStringOrBooleanValuePropertyFilterOperator.describe(+ '`icontains` - case insensitive contains. `not_icontains` - case insensitive does not contain. `regex` - matches the regex pattern. `not_regex` - does not match the regex pattern.'+ ),+ type: z+ .literal('element')+ .describe(+ 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'+ )+ .default('element'),+ value: z+ .string()+ .describe(+ 'Only use property values from the plan. If the operator is `regex` or `not_regex`, the value must be a valid ClickHouse regex pattern to match against. Otherwise, the value must be a substring that will be matched against the property value. Use the string values `true` or `false` for boolean properties.'+ ),+ }),+ z.object({+ key: z+ .enum(['tag_name', 'text', 'href', 'selector'])+ .describe(+ 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'+ ),+ operator: AssistantNumericValuePropertyFilterOperator,+ type: z+ .literal('element')+ .describe(+ 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'+ )+ .default('element'),+ value: z.coerce.number(),+ }),+ z.object({+ key: z+ .enum(['tag_name', 'text', 'href', 'selector'])+ .describe(+ 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'+ ),+ operator: AssistantArrayPropertyFilterOperator.describe(+ '`exact` - exact match of any of the values. `is_not` - does not match any of the values.'+ ),+ type: z+ .literal('element')+ .describe(+ 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'+ )+ .default('element'),+ value: z+ .array(z.string())+ .describe(+ 'Only use property values from the plan. Always use strings as values. If you have a number, convert it to a string first. If you have a boolean, convert it to a string "true" or "false".'+ ),+ }),+ z.object({+ key: z+ .enum(['tag_name', 'text', 'href', 'selector'])+ .describe(+ 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'+ ),+ operator: AssistantDateTimePropertyFilterOperator,+ type: z+ .literal('element')+ .describe(+ 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'+ )+ .default('element'),+ value: z.string().describe('Value must be a date in ISO 8601 format.'),+ }),+ z.object({+ key: z+ .enum(['tag_name', 'text', 'href', 'selector'])+ .describe(+ 'The element property to filter on. `tag_name` — HTML tag (e.g., `button`, `a`, `input`). `text` — visible text content of the element. `href` — the `href` attribute for links. `selector` — a CSS selector matching the element (e.g., `div.main > button.cta`).'+ ),+ operator: AssistantSetPropertyFilterOperator.describe(+ "`is_set` - the property has any value. `is_not_set` - the property doesn't have a value or wasn't collected."+ ),+ type: z+ .literal('element')+ .describe(+ 'Filter by autocaptured HTML element properties (`$autocapture`, `$rageclick`). Example: `{ type: "element", key: "text", value: "Sign Up", operator: "exact" }`'+ )+ .default('element'),+ }),+])++const AssistantHogQLPropertyFilter = z.object({+ key: z+ .string()+ .describe(+ "A HogQL boolean expression used as a filter condition.\n\nExamples:\n- Filter where a property exceeds a threshold: `toFloat(properties.load_time) > 5.0`\n- Filter with string matching: `properties.$current_url LIKE '%/pricing%'`\n- Filter with multiple conditions: `properties.$browser = 'Chrome' AND toFloat(properties.duration) > 30`"+ ),+ type: z+ .literal('hogql')+ .describe(+ "Filter by a HogQL boolean expression for advanced filtering that can't be expressed with standard property filters."+ )+ .default('hogql'),+})++const AssistantFlagPropertyFilter = z.object({+ key: z.string().describe('The feature flag key.'),+ operator: z.literal('flag_evaluates_to').default('flag_evaluates_to'),+ type: z+ .literal('flag')+ .describe(+ 'Filter events by feature flag state — only include events where a specific flag evaluated to a given value. Examples:\n- Flag enabled: `{ type: "flag", key: "new-onboarding", operator: "flag_evaluates_to", value: true }`\n- Specific variant: `{ type: "flag", key: "checkout-experiment", operator: "flag_evaluates_to", value: "variant-a" }`'+ )+ .default('flag'),+ value: z+ .union([z.coerce.boolean(), z.string()])+ .describe('`true`/`false` for boolean flags, or a variant name string for multivariate flags.'),+})++const AssistantPropertyFilter = z.union([+ AssistantGenericPropertyFilter,+ AssistantGroupPropertyFilter,+ AssistantCohortPropertyFilter,+ AssistantElementPropertyFilter,+ AssistantHogQLPropertyFilter,+ AssistantFlagPropertyFilter,+])++const AssistantTracesQuery = z.object({+ dateRange: AssistantDateRangeFilter.describe('Date range for the query.').optional(),+ filterSupportTraces: z.coerce.boolean().describe('Exclude support impersonation traces.').default(false).optional(),+ filterTestAccounts: z.coerce+ .boolean()+ .describe('Exclude internal and test users by applying the respective filters.')+ .default(true)+ .optional(),+ groupKey: z.string().describe('Filter traces by group key. Requires `groupTypeIndex` to be set.').optional(),+ groupTypeIndex: integer.describe('Group type index when filtering by group.').optional(),+ kind: z.literal('TracesQuery').default('TracesQuery'),+ limit: integer.describe('Maximum number of traces to return.').default(100).optional(),+ offset: integer.describe('Number of traces to skip for pagination.').default(0).optional(),+ personId: z.string().describe('Filter traces by a specific person UUID.').optional(),+ properties: z+ .array(AssistantPropertyFilter)+ .describe(+ 'Property filters to narrow results. Use event properties like `$ai_model`, `$ai_provider`, `$ai_trace_id`, etc. to filter traces.'+ )+ .default([])+ .optional(),+ randomOrder: z.coerce+ .boolean()+ .describe(+ 'Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias.'+ )+ .default(false)+ .optional(),+})++const AssistantTraceQuery = z.object({+ dateRange: AssistantDateRangeFilter.describe('Date range for the query.').optional(),+ kind: z.literal('TraceQuery').default('TraceQuery'),+ properties: z+ .array(AssistantPropertyFilter)+ .describe('Property filters to narrow events within the trace.')+ .default([])+ .optional(),+ traceId: z+ .string()+ .describe('The trace ID to fetch (the `id` field from a trace in `query-llm-traces-list` results).'),+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'llma-clustering-config-get': llmaClusteringConfigGet,'llma-clustering-config-set-event-filters': llmaClusteringConfigSetEventFilters,@@ -1939,4 +2258,10 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'llma-trace-review-get': llmaTraceReviewGet,'llma-trace-review-list': llmaTraceReviewList,'llma-trace-review-update': llmaTraceReviewUpdate,+ 'query-llm-traces-list': createQueryWrapper({+ name: 'query-llm-traces-list',+ schema: AssistantTracesQuery,+ kind: 'TracesQuery',+ }),+ 'query-llm-trace': createQueryWrapper({ name: 'query-llm-trace', schema: AssistantTraceQuery, kind: 'TraceQuery' }),}diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.tsindex b33788de65d0..f8e29dad1a8d 100644--- a/services/mcp/src/tools/generated/query-wrappers.ts+++ b/services/mcp/src/tools/generated/query-wrappers.ts@@ -1204,49 +1204,6 @@ const AssistantLifecycleQuery = z.object({.describe('Event or action to analyze. Lifecycle insights only support a single series.'),})-const AssistantTracesQuery = z.object({- dateRange: AssistantDateRangeFilter.describe('Date range for the query.').optional(),- filterSupportTraces: z.coerce.boolean().describe('Exclude support impersonation traces.').default(false).optional(),- filterTestAccounts: z.coerce- .boolean()- .describe('Exclude internal and test users by applying the respective filters.')- .default(true)- .optional(),- groupKey: z.string().describe('Filter traces by group key. Requires `groupTypeIndex` to be set.').optional(),- groupTypeIndex: integer.describe('Group type index when filtering by group.').optional(),- kind: z.literal('TracesQuery').default('TracesQuery'),- limit: integer.describe('Maximum number of traces to return.').default(100).optional(),- offset: integer.describe('Number of traces to skip for pagination.').default(0).optional(),- personId: z.string().describe('Filter traces by a specific person UUID.').optional(),- properties: z- .array(AssistantPropertyFilter)- .describe(- 'Property filters to narrow results. Use event properties like `$ai_model`, `$ai_provider`, `$ai_trace_id`, etc. to filter traces.'- )- .default([])- .optional(),- randomOrder: z.coerce- .boolean()- .describe(- 'Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias.'- )- .default(false)- .optional(),-})--const AssistantTraceQuery = z.object({- dateRange: AssistantDateRangeFilter.describe('Date range for the query.').optional(),- kind: z.literal('TraceQuery').default('TraceQuery'),- properties: z- .array(AssistantPropertyFilter)- .describe('Property filters to narrow events within the trace.')- .default([])- .optional(),- traceId: z- .string()- .describe('The trace ID to fetch (the `id` field from a trace in `query-llm-traces-list` results).'),-})-const AssistantTrendsActorsQuery = z.object({breakdown: z.array(z.string())@@ -1519,18 +1476,6 @@ export const GENERATED_TOOLS: Record<string, ReturnType<typeof createQueryWrappeuiResourceUri: 'ui://posthog/query-results.html',outputFormat: 'optimized',}),- 'query-llm-traces-list': createQueryWrapper({- name: 'query-llm-traces-list',- schema: AssistantTracesQuery,- kind: 'TracesQuery',- outputFormat: 'json',- }),- 'query-llm-trace': createQueryWrapper({- name: 'query-llm-trace',- schema: AssistantTraceQuery,- kind: 'TraceQuery',- outputFormat: 'json',- }),'query-trends-actors': createQueryWrapper({name: 'query-trends-actors',schema: QueryTrendsActorsSchema,diff --git a/services/mcp/tests/tools/aiObservability.integration.test.ts b/services/mcp/tests/tools/aiObservability.integration.test.tsindex 205d0cdf6685..7fbbba5e5597 100644--- a/services/mcp/tests/tools/aiObservability.integration.test.ts+++ b/services/mcp/tests/tools/aiObservability.integration.test.ts@@ -7,11 +7,13 @@ import {cleanupResources,createTestClient,createTestContext,+ getToolByName,parseToolResponse,setActiveProjectAndOrg,validateEnvironmentVariables,} from '@/shared/test-utils'import getLLMCostsTool from '@/tools/aiObservability/getLLMCosts'+import { GENERATED_TOOLS } from '@/tools/generated/ai_observability'import type { Context } from '@/tools/types'describe('AI observability', { concurrent: false }, () => {@@ -97,4 +99,19 @@ describe('AI observability', { concurrent: false }, () => {expect(Array.isArray(monthData.results)).toBe(true)})})++ describe('query-llm-traces-list', () => {+ it('should execute a traces query and return formatted results', async () => {+ const tool = getToolByName(GENERATED_TOOLS, 'query-llm-traces-list')+ const result = (await tool.handler(context, {+ dateRange: { date_from: '-7d' },+ limit: 10,+ })) as any++ expect(result).toHaveProperty('results')+ expect(result).toHaveProperty('_posthogUrl')+ // TracesQuery may not have a formatter — result could be string or JSON fallback+ expect(result.results !== undefined).toBe(true)+ })+ })})diff --git a/services/mcp/tests/tools/query-wrappers.integration.test.ts b/services/mcp/tests/tools/query-wrappers.integration.test.tsindex 531ad454d2f8..0abd455595a4 100644--- a/services/mcp/tests/tools/query-wrappers.integration.test.ts+++ b/services/mcp/tests/tools/query-wrappers.integration.test.ts@@ -288,21 +288,6 @@ describe('Query Wrapper Integration Tests', { concurrent: false }, () => {})})- describe('query-llm-traces-list', () => {- it('should execute a traces query and return formatted results', async () => {- const tool = getToolByName(GENERATED_TOOLS, 'query-llm-traces-list')- const result = (await tool.handler(context, {- dateRange: { date_from: '-7d' },- limit: 10,- })) as any-- expect(result).toHaveProperty('results')- expect(result).toHaveProperty('_posthogUrl')- // TracesQuery may not have a formatter — result could be string or JSON fallback- expect(result.results !== undefined).toBe(true)- })- })-describe('factory behavior', () => {it('should wrap query in InsightVizNode in the URL', async () => {const tool = getToolByName(GENERATED_TOOLS, 'query-trends')