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.

fix(aio): bound llm trace responses and add opt-in summaries (#94657)

posthog[bot]63afd7a8d027
diff --git a/docs/internal/ai-observability-mcp-traces.md b/docs/internal/ai-observability-mcp-traces.md
new file mode 100644
index 000000000000..b59250375bbe
--- /dev/null
+++ b/docs/internal/ai-observability-mcp-traces.md
@@ -0,0 +1,34 @@
+# Reading LLM traces over MCP
+
+`query-llm-trace` and `query-llm-traces-list` accept an optional `detail` parameter:
+
+| Value | Content |
+| ------------------ | ----------------------------------------------------------------------------------------------------- |
+| `"full"` (default) | Full event properties, subject to response size limits. |
+| `"summary"` | Trace and event metadata with short previews of prompts, outputs, span states, and custom properties. |
+
+Omitting `detail` preserves the existing full-detail behavior. Summary mode is opt-in on both tools.
+The MCP wrapper consumes this parameter; it is not part of the backend `TraceQuery` or `TracesQuery` schema.
+
+## Investigation workflow
+
+Use `detail: "summary"` to find candidate traces or survey a trace's events, costs, timing, and errors.
+Summarized traces include `_detail: { "mode": "summary" }`.
+
+Once a trace needs investigation, use `query-llm-trace` with `detail: "full"` and retain the relevant
+date and property filters. Full detail is needed for exact tool arguments, conversation extraction,
+and searches for content that a preview may omit. A known trace can be read in full directly.
+
+The [exploring-llm-traces skill](../../products/ai_observability/skills/exploring-llm-traces/SKILL.md)
+teaches this workflow and includes scripts for parsing saved full-detail responses.
+
+## Response limits
+
+Both modes compact large responses before returning them to the MCP client. The compactor accounts
+for JSON escaping in values and keys, then checks the serialized result against its budget.
+Summary mode has a smaller budget than full detail.
+
+Long values, omitted array items or object keys, and dropped events or traces carry truncation markers.
+`detail: "full"` does not disable these limits. Missing content in a truncated response does not prove
+it was absent from the stored trace. Narrow the query or open the returned `_posthogUrl` for the complete data.
+The stored trace is unchanged by response compaction.
diff --git a/products/ai_observability/mcp/prompts/query-llm-trace.md b/products/ai_observability/mcp/prompts/query-llm-trace.md
index 5aac1c0dc42e..e14c9ebb2ea9 100644
--- a/products/ai_observability/mcp/prompts/query-llm-trace.md
+++ b/products/ai_observability/mcp/prompts/query-llm-trace.md
@@ -1,4 +1,6 @@
-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.
+Fetch a single LLM trace by its trace ID for deep inspection. Returns the trace and every nested event, with model parameters, costs, tool calls, and errors. Use after finding a trace via `query-llm-traces-list` to inspect the complete event tree.
+
+By default the response returns full event properties, subject to response size limits. Set `detail` to `"summary"` for metadata and short previews when browsing a trace. Omitted `detail` preserves the existing full-detail behavior.
Use cases:
@@ -23,7 +25,7 @@ The response contains a single trace in JSON format with:
- `inputTokens` / `outputTokens` — token counts across all generations
- `inputCost` / `outputCost` / `totalCost` — costs in USD
- `inputState` / `outputState` — JSON input/output state from the root `$ai_trace` event (e.g., conversation messages)
-- `events` — **all** child events in the trace at every nesting depth (not just direct children). Each event has full `properties`.
+- `events` — **all** child events in the trace at every nesting depth (not just direct children), subject to response size limits. Each event has `properties`, returned in full by default and previewed under `detail: "summary"`.
Unlike `query-llm-traces-list`, this tool does NOT return `errorCount`, `isSupportTrace`, or `tools` — those are summary fields on the list tool only.
@@ -77,9 +79,18 @@ If the trace is old, provide a date range to help the query find it efficiently:
}
```
+# Detail level
+
+`detail` controls how much of each event you get back.
+
+- `"full"` (default) returns every property in full, bounded by the response size limit below. Existing callers that omit `detail` keep this behavior.
+- `"summary"` opts into trace fields, plus each event's `id`, `createdAt`, `event` type, and its navigation properties: `$ai_trace_id`, `$ai_span_id`, `$ai_generation_id`, `$ai_parent_id`, `$ai_span_name`, `$ai_model`, `$ai_provider`, `$ai_latency`, token counts, costs, `$ai_tools_called`, `$ai_is_error`, `$ai_error`, `$ai_http_status`, `$ai_metric_name`, `$ai_metric_value`, and `$ai_feedback_text`. Prompts, outputs, span states, and any other property come back as short previews. A summarized trace carries `_detail: { "mode": "summary" }`.
+
+For an overview, explicitly request `detail: "summary"`, find the events that matter from their metadata and previews, then re-run with `detail: "full"` if you still need the content. Keep relevant date and property filters when requesting full detail.
+
# Response size
-To 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.
+To 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. Both detail modes enforce size limits; `detail: "full"` does not guarantee that every event or property fits.
# Reminders
@@ -87,3 +98,4 @@ To protect the agent's context window, very large traces are compacted before th
- If no date range is provided, the default lookback window is used. For older traces, provide an explicit `dateRange`.
- The `events` array contains ALL events in the trace (including deeply nested ones), making this suitable for full tree reconstruction.
- Use `query-llm-traces-list` first to find traces, then this tool to inspect a specific one.
+- Only ask for `detail: "full"` on a trace you have already narrowed down. A full-detail read of an unremarkable trace spends context you will need later.
diff --git a/products/ai_observability/mcp/prompts/query-llm-traces-list.md b/products/ai_observability/mcp/prompts/query-llm-traces-list.md
index c964ea016f24..c41ee28fb1e3 100644
--- a/products/ai_observability/mcp/prompts/query-llm-traces-list.md
+++ b/products/ai_observability/mcp/prompts/query-llm-traces-list.md
@@ -1,5 +1,7 @@
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.
+Set `detail: "summary"` to preview event content when picking candidate traces, then read the one you pick with `query-llm-trace`. Omitting `detail` preserves the existing full-detail response, subject to size limits.
+
Use 'read-data-schema' to discover available event properties for filtering (e.g. `$ai_model`, `$ai_provider`).
Examples of use cases include:
@@ -94,7 +96,7 @@ Each trace in the results contains:
- `errorCount` — number of errors in the trace
- `isSupportTrace` — whether the trace was from a support impersonation session
- `tools` — list of tool names called during the trace
-- `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.
+- `events` — list of direct child events (generations, metrics, feedback). Each event's `properties` contains the event data, returned in full by default and previewed under `detail: "summary"`, subject to response size limits. See "Event types and their properties" below.
## Event types and their properties
@@ -126,9 +128,18 @@ Generations (`$ai_generation`) and embeddings (`$ai_embedding`) are always leaf
**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`.
+## Detail level
+
+`detail` controls how much of each event you get back.
+
+- `"full"` (default) returns every property in full, subject to response size limits. Existing callers that omit `detail` keep this behavior.
+- `"summary"` opts into trace and event metadata with previews of prompts, outputs, span states, and other content. A summarized trace carries `_detail: { "mode": "summary" }`.
+
+Request `detail: "summary"` when finding candidate traces from their metadata; read the one you picked with `query-llm-trace` and `detail: "full"` when you need its content.
+
## Response size
-To 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.
+To 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.
## Pagination
diff --git a/products/ai_observability/skills/exploring-llm-traces/SKILL.md b/products/ai_observability/skills/exploring-llm-traces/SKILL.md
index b7835fd08e41..74f4c0e34ddb 100644
--- a/products/ai_observability/skills/exploring-llm-traces/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-traces/SKILL.md
@@ -53,13 +53,18 @@ If the URL has neither explicit dates nor `timestamp`, use a safe default like `
For exact trace and session URLs, skip schema discovery for the standard `$ai_*` fields used below. These are AI observability built-ins, not project-specific custom properties.
-### Step 2 — Fetch trace data
+### Step 2 — Browse trace summaries
+
+Explicitly set `detail: "summary"` when browsing traces. This keeps metadata and short content previews
+without spending context on full prompts and outputs. Omitting `detail` still returns full detail for
+compatibility with existing callers.
For a trace URL, call `posthog:query-llm-trace` with:
```json
{
"traceId": "<trace_id>",
+ "detail": "summary",
"dateRange": { "date_from": "-7d" }
}
```
@@ -68,6 +73,7 @@ For a session URL, call `posthog:query-llm-traces-list` with:
```json
{
+ "detail": "summary",
"dateRange": { "date_from": "<timestamp_minus_36h>", "date_to": "<timestamp_plus_36h>" },
"filterTestAccounts": false,
"limit": 20,
@@ -79,8 +85,8 @@ Use the URL's `date_from` / `date_to` values in the session query if present.
If the URL only has `timestamp`, calculate the absolute date range from that timestamp instead of using a relative range like `-1h`.
Set `filterTestAccounts: false` for an exact URL so the requested trace is not hidden by account filters.
-The result contains the event tree with all properties.
-The response may be large — when it exceeds the inline limit, Claude Code auto-persists it to a file.
+The result contains trace and event metadata with previews of prompts, outputs, span states, and custom properties.
+A trace with `_detail: { "mode": "summary" }` contains previews, not the complete content.
From the result you get:
@@ -90,7 +96,28 @@ From the result you get:
- Parent-child relationships via `$ai_parent_id`
- `_posthogUrl` — **always include this in your response** so the user can click through to the UI
-### Step 3 — Parse large results with scripts
+### Step 3 — Read the content needed for the investigation
+
+Once you have selected a trace, request `posthog:query-llm-trace` with `detail: "full"` before inspecting
+exact tool arguments, checking which context the model received, or searching conversation content:
+
+```json
+{
+ "traceId": "<trace_id>",
+ "detail": "full",
+ "dateRange": { "date_from": "-7d" }
+}
+```
+
+Preserve the date range from the original URL or discovery query instead of copying the example range.
+Keep relevant property filters to narrow the read. If the user already identified the trace and needs
+exact content, you can request full detail directly.
+
+Both modes enforce response size limits. Check truncation markers before drawing conclusions: an omitted
+event or a keyword missing from a preview is not evidence that it was absent from the trace. If full detail
+is still truncated, narrow the query to the relevant events or open `_posthogUrl` for the complete data.
+
+### Step 4 — Parse large full-detail results with scripts
When the result is persisted to a file (large traces with full `$ai_input`/`$ai_output_choices`),
use the [parsing scripts](./scripts/) to explore it.
@@ -160,7 +187,7 @@ When presenting findings, always include the relevant PostHog URL so the user ca
## Finding traces
-Use `posthog:query-llm-traces-list` to search and filter traces.
+Use `posthog:query-llm-traces-list` with `detail: "summary"` to search and filter traces.
**CRITICAL: Never assume event names, property names, or property values from training data.**
Every project instruments different custom properties. For open-ended searches and custom filters, call
@@ -189,6 +216,7 @@ Do not confirm `$ai_*` properties, but confirm any other like `email` of a perso
```json
posthog:query-llm-traces-list
{
+ "detail": "summary",
"dateRange": {"date_from": "-1h"},
"filterTestAccounts": true,
"limit": 20,
@@ -203,6 +231,7 @@ Multiple filters are AND-ed together:
```json
posthog:query-llm-traces-list
{
+ "detail": "summary",
"dateRange": {"date_from": "-1h"},
"filterTestAccounts": true,
"properties": [
@@ -217,6 +246,7 @@ You can also filter by person properties (discover them via `read-data-schema` w
```json
posthog:query-llm-traces-list
{
+ "detail": "summary",
"dateRange": {"date_from": "-1h"},
"filterTestAccounts": true,
"properties": [
@@ -237,6 +267,7 @@ Use `posthog:read-data-schema` to discover what custom properties exist, then fi
```json
posthog:query-llm-traces-list
{
+ "detail": "summary",
"dateRange": {"date_from": "-7d"},
"properties": [
{"type": "event", "key": "project_id", "value": "proj_abc123", "operator": "exact"}
@@ -252,6 +283,8 @@ For more complex SQL patterns, read these references:
## Parsing large trace results
Trace tool results are JSON. When too large to read inline, Claude Code persists them to a file.
+Use a full-detail response for content extraction and keyword searches; the scripts cannot recover
+content omitted from a summary or a truncated response.
### Persisted file format
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5fdf5fae7008..03dab6c058ba 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8981,7 +8981,7 @@
"system_prompt_hint": "List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day"
},
"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.",
+ "description": "Fetch a single LLM trace by its trace ID for deep inspection. Returns the trace and every nested event, with model parameters, costs, tool calls, and errors. Use after finding a trace via `query-llm-traces-list` to inspect the complete event tree.\n\nBy default the response returns full event properties, subject to response size limits. Set `detail` to `\"summary\"` for metadata and short previews when browsing a trace. Omitted `detail` preserves the existing full-detail behavior.\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), subject to response size limits. Each event has `properties`, returned in full by default and previewed under `detail: \"summary\"`.\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# Detail level\n\n`detail` controls how much of each event you get back.\n\n- `\"full\"` (default) returns every property in full, bounded by the response size limit below. Existing callers that omit `detail` keep this behavior.\n- `\"summary\"` opts into trace fields, plus each event's `id`, `createdAt`, `event` type, and its navigation properties: `$ai_trace_id`, `$ai_span_id`, `$ai_generation_id`, `$ai_parent_id`, `$ai_span_name`, `$ai_model`, `$ai_provider`, `$ai_latency`, token counts, costs, `$ai_tools_called`, `$ai_is_error`, `$ai_error`, `$ai_http_status`, `$ai_metric_name`, `$ai_metric_value`, and `$ai_feedback_text`. Prompts, outputs, span states, and any other property come back as short previews. A summarized trace carries `_detail: { \"mode\": \"summary\" }`.\n\nFor an overview, explicitly request `detail: \"summary\"`, find the events that matter from their metadata and previews, then re-run with `detail: \"full\"` if you still need the content. Keep relevant date and property filters when requesting full detail.\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. Both detail modes enforce size limits; `detail: \"full\"` does not guarantee that every event or property fits.\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.\n- Only ask for `detail: \"full\"` on a trace you have already narrowed down. A full-detail read of an unremarkable trace spends context you will need later.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get LLM trace",
@@ -8996,7 +8996,7 @@
"system_prompt_hint": "Single LLM/AI trace deep-dive"
},
"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`.",
+ "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\nSet `detail: \"summary\"` to preview event content when picking candidate traces, then read the one you pick with `query-llm-trace`. Omitting `detail` preserves the existing full-detail response, subject to size limits.\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 event data, returned in full by default and previewed under `detail: \"summary\"`, subject to response size limits. 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## Detail level\n\n`detail` controls how much of each event you get back.\n\n- `\"full\"` (default) returns every property in full, subject to response size limits. Existing callers that omit `detail` keep this behavior.\n- `\"summary\"` opts into trace and event metadata with previews of prompts, outputs, span states, and other content. A summarized trace carries `_detail: { \"mode\": \"summary\" }`.\n\nRequest `detail: \"summary\"` when finding candidate traces from their metadata; read the one you picked with `query-llm-trace` and `detail: \"full\"` when you need its content.\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": "AI observability",
"feature": "llm_analytics",
"summary": "List LLM traces",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4510f56400af..6636135964c3 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9539,7 +9539,7 @@
"system_prompt_hint": "List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day"
},
"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.",
+ "description": "Fetch a single LLM trace by its trace ID for deep inspection. Returns the trace and every nested event, with model parameters, costs, tool calls, and errors. Use after finding a trace via `query-llm-traces-list` to inspect the complete event tree.\n\nBy default the response returns full event properties, subject to response size limits. Set `detail` to `\"summary\"` for metadata and short previews when browsing a trace. Omitted `detail` preserves the existing full-detail behavior.\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), subject to response size limits. Each event has `properties`, returned in full by default and previewed under `detail: \"summary\"`.\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# Detail level\n\n`detail` controls how much of each event you get back.\n\n- `\"full\"` (default) returns every property in full, bounded by the response size limit below. Existing callers that omit `detail` keep this behavior.\n- `\"summary\"` opts into trace fields, plus each event's `id`, `createdAt`, `event` type, and its navigation properties: `$ai_trace_id`, `$ai_span_id`, `$ai_generation_id`, `$ai_parent_id`, `$ai_span_name`, `$ai_model`, `$ai_provider`, `$ai_latency`, token counts, costs, `$ai_tools_called`, `$ai_is_error`, `$ai_error`, `$ai_http_status`, `$ai_metric_name`, `$ai_metric_value`, and `$ai_feedback_text`. Prompts, outputs, span states, and any other property come back as short previews. A summarized trace carries `_detail: { \"mode\": \"summary\" }`.\n\nFor an overview, explicitly request `detail: \"summary\"`, find the events that matter from their metadata and previews, then re-run with `detail: \"full\"` if you still need the content. Keep relevant date and property filters when requesting full detail.\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. Both detail modes enforce size limits; `detail: \"full\"` does not guarantee that every event or property fits.\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.\n- Only ask for `detail: \"full\"` on a trace you have already narrowed down. A full-detail read of an unremarkable trace spends context you will need later.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get LLM trace",
@@ -9554,7 +9554,7 @@
"system_prompt_hint": "Single LLM/AI trace deep-dive"
},
"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`.",
+ "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\nSet `detail: \"summary\"` to preview event content when picking candidate traces, then read the one you pick with `query-llm-trace`. Omitting `detail` preserves the existing full-detail response, subject to size limits.\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 event data, returned in full by default and previewed under `detail: \"summary\"`, subject to response size limits. 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## Detail level\n\n`detail` controls how much of each event you get back.\n\n- `\"full\"` (default) returns every property in full, subject to response size limits. Existing callers that omit `detail` keep this behavior.\n- `\"summary\"` opts into trace and event metadata with previews of prompts, outputs, span states, and other content. A summarized trace carries `_detail: { \"mode\": \"summary\" }`.\n\nRequest `detail: \"summary\"` when finding candidate traces from their metadata; read the one you picked with `query-llm-trace` and `detail: \"full\"` when you need its content.\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": "AI observability",
"feature": "llm_analytics",
"summary": "List LLM traces",
diff --git a/services/mcp/src/lib/trace-compaction.ts b/services/mcp/src/lib/trace-compaction.ts
index 385c1b79f75b..a578b694b828 100644
--- a/services/mcp/src/lib/trace-compaction.ts
+++ b/services/mcp/src/lib/trace-compaction.ts
@@ -5,13 +5,19 @@
* completions, and tool payloads. Left unbounded these responses have reached
* tens of millions of tokens, which exhausts the calling agent's context window.
*
+ * Two layers keep that in check. `summary` detail replaces event content with
+ * short previews so the summary response is trace metadata plus enough of each
+ * prompt and output to decide what to read next. On top of that, compaction
+ * walks the result within a character budget, truncating long string values and
+ * dropping content that doesn't fit, and stops traversing once the budget is
+ * spent so it never materializes a full clone of a pathological trace. A final
+ * pass measures the real encoded output and shrinks again if the walk's estimate
+ * was wrong, so the response cannot breach the cap.
+ *
* Compaction is a client-boundary safeguard only — the underlying query and the
- * PostHog UI still have the complete, untruncated trace. It walks the result
- * within a character budget, truncating long string values and dropping content
- * that doesn't fit, and stops traversing once the budget is spent so it never
- * materializes a full clone or a full serialization of a pathological trace.
- * Everything it shortens or drops is flagged so the agent knows to open the
- * trace in PostHog for the full data.
+ * PostHog UI still have the complete, untruncated trace. Everything it shortens
+ * or drops is flagged so the agent knows to ask for `detail: "full"` or open the
+ * trace in PostHog.
*/
/** Longest single string value kept verbatim; longer values are truncated. */
@@ -25,17 +31,93 @@ export const PER_VALUE_CHAR_LIMIT = 10_000
*/
export const MAX_TRACE_CHARS = 500_000
-// Room reserved for events (and their truncation flag) when budgeting the
-// non-event trace fields, so an oversized `inputState`/`outputState` can't starve
-// the events out entirely.
-const EVENTS_RESERVE = 50_000
+/**
+ * Cap for `summary` detail (~30K tokens). Much tighter than the full-detail cap,
+ * because the point of a summary is to survey a trace without spending the
+ * agent's context on prompt and completion bodies.
+ */
+export const MAX_SUMMARY_CHARS = 120_000
+
+/** How much of each previewed value a summary keeps. */
+export const SUMMARY_PREVIEW_CHARS = 600
+
+/**
+ * How much of an event's content reaches the client. `summary` keeps identity,
+ * timing, model, cost, tool, and error metadata verbatim and previews everything
+ * else. `full` keeps all properties, bounded by the compaction budget.
+ */
+export type TraceDetail = 'summary' | 'full'
+
+// Share of the budget the non-event trace fields may spend, so an oversized
+// `inputState`/`outputState` can't starve the events out entirely. A ratio rather
+// than a fixed reserve, because a fixed one leaves nothing for `id` and the other
+// identity fields once a trace's share of a list budget drops below it.
+const BASE_FIELDS_BUDGET_RATIO = 0.9
// Room reserved for the `_truncated` metadata object.
const META_RESERVE = 500
// Below this remaining budget we stop adding more items rather than emit useless
// fragments. Also the floor budget handed to a forced-keep first event.
const MIN_ITEM_BUDGET = 256
+// Both allowances are sized for the full-trace budget. A preview budget is three
+// orders of magnitude smaller, where a flat reserve and a flat floor consume the
+// whole allowance and every nested value comes back empty, so scale them down
+// with the budget once it gets that small.
+const SMALL_BUDGET_RESERVE_RATIO = 0.1
+const SMALL_BUDGET_MIN_ITEM_RATIO = 0.25
+
// Smallest budget a trace may get in a multi-trace (list) response.
const MIN_TRACE_BUDGET = 2_000
+// How many times the encoded-size check may re-run the walk with a smaller
+// budget before it gives up and returns the minimal placeholder.
+const MAX_FIT_PASSES = 4
+// Extra shrink applied on each re-run so a pass lands inside the cap instead of
+// converging on it one percent at a time.
+const FIT_HEADROOM = 1.2
+
+/**
+ * Event properties that stay verbatim in a summary. These are the fields an
+ * agent needs to navigate a trace: tree position, timing, model, spend, tool
+ * calls, and failures. Everything else is content and gets previewed.
+ */
+const SUMMARY_METADATA_PROPERTIES = new Set([
+ '$ai_trace_id',
+ '$ai_span_id',
+ '$ai_generation_id',
+ '$ai_parent_id',
+ '$ai_span_name',
+ '$ai_session_id',
+ '$ai_model',
+ '$ai_provider',
+ '$ai_latency',
+ '$ai_input_tokens',
+ '$ai_output_tokens',
+ '$ai_cache_read_input_tokens',
+ '$ai_reasoning_tokens',
+ '$ai_input_cost_usd',
+ '$ai_output_cost_usd',
+ '$ai_total_cost_usd',
+ '$ai_tools_called',
+ '$ai_is_error',
+ '$ai_error',
+ '$ai_http_status',
+ '$ai_metric_name',
+ '$ai_metric_value',
+ '$ai_feedback_text',
+])
+
+/** Trace-level fields that carry conversation content rather than metadata. */
+const SUMMARY_PREVIEWED_TRACE_FIELDS = new Set(['inputState', 'outputState'])
+
+const SUMMARY_NOTE =
+ 'Event content is previewed. Re-run this tool with detail: "full" for complete prompts, outputs, and custom properties, or open the trace in PostHog.'
+
+function metaReserveFor(budget: number): number {
+ return Math.min(META_RESERVE, Math.floor(Math.max(0, budget) * SMALL_BUDGET_RESERVE_RATIO))
+}
+
+function minItemBudgetFor(budget: number): number {
+ return Math.min(MIN_ITEM_BUDGET, Math.floor(Math.max(0, budget) * SMALL_BUDGET_MIN_ITEM_RATIO))
+}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -49,6 +131,17 @@ function serializedLength(value: unknown): number {
}
}
+/**
+ * Length of a string once encoded as a JSON value, including its quotes. JSON
+ * escaping can multiply a value's size several times over: a quote or a newline
+ * costs two characters, and a control character costs six. Budgeting on the raw
+ * character count let a trace of escape-heavy text serialize to several times
+ * the cap.
+ */
+function encodedStringLength(value: string): number {
+ return JSON.stringify(value).length
+}
+
/**
* Assign a key without triggering the inherited `__proto__` setter. Trace
* payloads are arbitrary parsed JSON and can legitimately carry an own
@@ -65,17 +158,31 @@ function assignKey(target: Record<string, unknown>, key: string, value: unknown)
}
function truncateString(value: string, budget: number): string {
- const limit = Math.min(PER_VALUE_CHAR_LIMIT, Math.max(0, budget))
- if (value.length <= limit) {
+ const cap = Math.max(0, budget)
+ if (value.length <= PER_VALUE_CHAR_LIMIT && encodedStringLength(value) <= cap) {
+ return value
+ }
+ let kept = value.slice(0, Math.min(PER_VALUE_CHAR_LIMIT, value.length))
+ // Shrink by the measured overshoot rather than by a character count, because
+ // escaping decides how much of the budget each character actually costs.
+ while (kept.length > 0) {
+ const encoded = encodedStringLength(kept)
+ if (encoded <= cap) {
+ break
+ }
+ const shrunkTo = cap <= 0 ? 0 : Math.floor(kept.length / ((encoded / cap) * FIT_HEADROOM))
+ kept = kept.slice(0, Math.min(shrunkTo, kept.length - 1))
+ }
+ if (kept.length >= value.length) {
return value
}
- const dropped = value.length - limit
- return `${value.slice(0, limit)}… [truncated ${dropped} of ${value.length} chars — open the trace in PostHog for the full value]`
+ const dropped = value.length - kept.length
+ return `${kept}… [truncated ${dropped} of ${value.length} chars — open the trace in PostHog for the full value]`
}
interface Compacted {
value: unknown
- /** Approximate serialized length of `value` (accurate for ASCII, the common case). */
+ /** Serialized length of `value`, measured for strings and keys. */
cost: number
}
@@ -95,24 +202,26 @@ function compactValue(value: unknown, budget: number): Compacted {
}
if (type === 'string') {
const out = truncateString(value as string, budget)
- return { value: out, cost: out.length + 2 }
+ return { value: out, cost: encodedStringLength(out) }
}
+ const reserve = metaReserveFor(budget)
+ const minItemBudget = minItemBudgetFor(budget)
if (Array.isArray(value)) {
const out: unknown[] = []
let cost = 2 // "[]"
let i = 0
for (; i < value.length; i++) {
- if (budget - cost < MIN_ITEM_BUDGET) {
+ if (budget - cost < minItemBudget) {
break
}
- const child = compactValue(value[i], budget - cost - META_RESERVE)
+ const child = compactValue(value[i], budget - cost - reserve)
out.push(child.value)
cost += child.cost + 1 // + comma
}
if (i < value.length) {
const marker = `… [${value.length - i} more items omitted to fit the response size limit]`
out.push(marker)
- cost += marker.length + 3
+ cost += encodedStringLength(marker) + 1
}
return { value: out, cost }
}
@@ -127,11 +236,11 @@ function compactValue(value: unknown, budget: number): Compacted {
// its serialized size against the budget before admitting the member —
// otherwise a single ~1MB property name slips past the cap even after
// its value is compacted to nothing.
- const keyCost = key.length + 3 // "key":
- if (budget - cost - keyCost < MIN_ITEM_BUDGET) {
+ const keyCost = encodedStringLength(key) + 1 // "key":
+ if (budget - cost - keyCost < minItemBudget) {
break
}
- const child = compactValue(val, budget - cost - keyCost - META_RESERVE)
+ const child = compactValue(val, budget - cost - keyCost - reserve)
assignKey(out, key, child.value)
cost += keyCost + child.cost + 1 // "key":value,
}
@@ -145,7 +254,67 @@ function compactValue(value: unknown, budget: number): Compacted {
}
/**
- * Compact a single trace to fit `budget` characters. Non-event fields are
+ * Re-measure the encoded output and re-run the walk with a smaller budget while
+ * it still exceeds the cap. The walk budgets an estimate of the encoded size, so
+ * an estimate that is wrong for one payload shape would otherwise reach the
+ * client as an oversized frame. This measures the compacted output only, never
+ * the raw input, so the check itself stays cheap.
+ */
+function fitToEncodedBudget(budget: number, compact: (walkBudget: number) => unknown, fallback: unknown): unknown {
+ let walkBudget = budget
+ let out = compact(walkBudget)
+ for (let pass = 0; pass < MAX_FIT_PASSES; pass++) {
+ const encoded = serializedLength(out)
+ if (encoded <= budget) {
+ return out
+ }
+ walkBudget = Math.max(MIN_ITEM_BUDGET, Math.floor((walkBudget * budget) / encoded / FIT_HEADROOM))
+ out = compact(walkBudget)
+ }
+ return serializedLength(out) <= budget ? out : fallback
+}
+
+/** Shorten one value to a preview an agent can scan without reading it in full. */
+function previewValue(value: unknown): unknown {
+ return compactValue(value, SUMMARY_PREVIEW_CHARS).value
+}
+
+function summarizeEvent(event: unknown): unknown {
+ if (!isRecord(event)) {
+ return previewValue(event)
+ }
+ const out: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(event)) {
+ if (key !== 'properties' || !isRecord(value)) {
+ assignKey(out, key, value)
+ continue
+ }
+ const properties: Record<string, unknown> = {}
+ for (const [propertyKey, propertyValue] of Object.entries(value)) {
+ assignKey(
+ properties,
+ propertyKey,
+ SUMMARY_METADATA_PROPERTIES.has(propertyKey) ? propertyValue : previewValue(propertyValue)
+ )
+ }
+ assignKey(out, 'properties', properties)
+ }
+ return out
+}
+
+/** Preview the trace-level fields that carry conversation content. */
+function summarizeTraceFields(fields: Record<string, unknown>): void {
+ for (const key of SUMMARY_PREVIEWED_TRACE_FIELDS) {
+ if (key in fields) {
+ assignKey(fields, key, previewValue(fields[key]))
+ }
+ }
+ assignKey(fields, '_detail', { mode: 'summary', note: SUMMARY_NOTE })
+}
+
+/**
+ * Compact a single trace to fit `budget` characters, previewing event content
+ * first when `detail` is `summary`. Non-event fields are
* budgeted first (so a huge `inputState` can't starve the events), then events
* are filled in until the budget runs out; the first event is compacted to fit
* rather than kept verbatim, so no single event can breach the cap. Dropped
@@ -155,14 +324,19 @@ function compactValue(value: unknown, budget: number): Compacted {
* which is not guaranteed to be parent-before-child order, so a truncated trace
* may not be fully tree-reconstructable — hence the pointer back to PostHog.
*/
-export function compactTrace(trace: unknown, budget: number = MAX_TRACE_CHARS): unknown {
+export function compactTrace(trace: unknown, budget: number = MAX_TRACE_CHARS, detail: TraceDetail = 'full'): unknown {
if (!isRecord(trace)) {
return trace
}
+ return fitToEncodedBudget(
+ budget,
+ (walkBudget) => compactTraceWithin(trace, walkBudget, detail),
+ minimalTracePlaceholder(trace)
+ )
+}
+
+function compactTraceWithin(trace: Record<string, unknown>, budget: number, detail: TraceDetail): unknown {
const events = Array.isArray(trace.events) ? trace.events : null
- if (!events) {
- return compactValue(trace, budget).value
- }
const rest: Record<string, unknown> = {}
for (const [key, val] of Object.entries(trace)) {
@@ -170,7 +344,13 @@ export function compactTrace(trace: unknown, budget: number = MAX_TRACE_CHARS):
assignKey(rest, key, val)
}
}
- const baseCompacted = compactValue(rest, Math.max(0, budget - EVENTS_RESERVE))
+ if (detail === 'summary') {
+ summarizeTraceFields(rest)
+ }
+ if (!events) {
+ return compactValue(rest, budget).value
+ }
+ const baseCompacted = compactValue(rest, Math.max(0, budget * BASE_FIELDS_BUDGET_RATIO))
const base = baseCompacted.value as Record<string, unknown>
let remaining = budget - baseCompacted.cost - META_RESERVE
@@ -180,7 +360,11 @@ export function compactTrace(trace: unknown, budget: number = MAX_TRACE_CHARS):
if (kept.length >= 1 && remaining < MIN_ITEM_BUDGET) {
break
}
- const child = compactValue(events[i], Math.max(MIN_ITEM_BUDGET, remaining))
+ // Summarize inside the loop so events past the budget are never visited.
+ // Summarizing the whole trace up front would build a second copy of a
+ // payload that is already large enough to be the problem.
+ const event = detail === 'summary' ? summarizeEvent(events[i]) : events[i]
+ const child = compactValue(event, Math.max(MIN_ITEM_BUDGET, remaining))
kept.push(child.value)
remaining -= child.cost + 1
}
@@ -198,6 +382,21 @@ export function compactTrace(trace: unknown, budget: number = MAX_TRACE_CHARS):
return base
}
+/** What a trace collapses to when even the smallest walk budget doesn't fit. */
+function minimalTracePlaceholder(trace: Record<string, unknown>): Record<string, unknown> {
+ const events = Array.isArray(trace.events) ? trace.events : []
+ return {
+ ...(typeof trace.id === 'string' ? { id: trace.id } : {}),
+ events: [],
+ _truncated: {
+ omittedEvents: events.length,
+ totalEvents: events.length,
+ reason: 'Trace could not be compacted below the response size limit.',
+ note: 'Open the trace in PostHog for the complete, untruncated data, or narrow the query to the events you need.',
+ },
+ }
+}
+
/**
* Compact the `results` array from a trace query. `query-llm-trace` returns a
* single trace, which gets the full per-trace budget. `query-llm-traces-list`
@@ -205,35 +404,45 @@ export function compactTrace(trace: unknown, budget: number = MAX_TRACE_CHARS):
* trailing traces beyond it are dropped and flagged — without this an entire
* page of individually-bounded traces could still add up to tens of megabytes.
*/
-export function compactTraceResults(results: unknown): unknown {
+export function compactTraceResults(results: unknown, detail: TraceDetail = 'full'): unknown {
if (!Array.isArray(results)) {
return results
}
+ const budget = detail === 'summary' ? MAX_SUMMARY_CHARS : MAX_TRACE_CHARS
if (results.length <= 1) {
- return results.map((trace) => compactTrace(trace, MAX_TRACE_CHARS))
+ return results.map((trace) => compactTrace(trace, budget, detail))
}
+ return fitToEncodedBudget(budget, (walkBudget) => compactTraceList(results, walkBudget, detail), [
+ listTruncationSentinel(results.length, results.length),
+ ])
+}
+function compactTraceList(results: unknown[], budget: number, detail: TraceDetail): unknown[] {
const out: unknown[] = []
- let remaining = MAX_TRACE_CHARS
+ let remaining = budget
let i = 0
for (; i < results.length; i++) {
if (out.length >= 1 && remaining < MIN_TRACE_BUDGET) {
break
}
- const compacted = compactTrace(results[i], Math.min(MAX_TRACE_CHARS, Math.max(MIN_TRACE_BUDGET, remaining)))
+ const compacted = compactTrace(results[i], Math.min(budget, Math.max(MIN_TRACE_BUDGET, remaining)), detail)
out.push(compacted)
remaining -= serializedLength(compacted) + 1
}
const omitted = results.length - i
if (omitted > 0) {
- out.push({
- _truncated: {
- omittedTraces: omitted,
- totalTraces: results.length,
- reason: 'The combined trace list exceeded the response size limit.',
- note: 'Narrow the query (shorter date range, more filters, or a smaller limit), or fetch individual traces with query-llm-trace.',
- },
- })
+ out.push(listTruncationSentinel(omitted, results.length))
}
return out
}
+
+function listTruncationSentinel(omitted: number, total: number): Record<string, unknown> {
+ return {
+ _truncated: {
+ omittedTraces: omitted,
+ totalTraces: total,
+ reason: 'The combined trace list exceeded the response size limit.',
+ note: 'Narrow the query (shorter date range, more filters, or a smaller limit), or fetch individual traces with query-llm-trace.',
+ },
+ }
+}
diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.ts
index f92130aa7f7d..c5f910d79aa0 100644
--- a/services/mcp/src/tools/query-wrapper-factory.ts
+++ b/services/mcp/src/tools/query-wrapper-factory.ts
@@ -1,6 +1,6 @@
import { z } from 'zod'
-import { compactTraceResults } from '@/lib/trace-compaction'
+import { type TraceDetail, compactTraceResults } from '@/lib/trace-compaction'
import {
POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,
POSTHOG_META_KEY,
@@ -14,6 +14,29 @@ import {
// returned so a single huge trace can't blow the caller's context window.
const TRACE_QUERY_KINDS = new Set(['TraceQuery', 'TracesQuery'])
+const TRACE_DETAIL_FIELD = 'detail'
+const DEFAULT_TRACE_DETAIL: TraceDetail = 'full'
+const TRACE_DETAIL_DESCRIPTION =
+ 'How much of each event to return. "full" (default) returns complete event properties, subject to response size limits, preserving existing behavior when detail is omitted. Set "summary" to browse trace and event metadata (IDs, timestamps, model, latency, tokens, cost, tools called, errors) with short previews of prompts and outputs.'
+
+/**
+ * Add the `detail` control to the trace wrappers only. The field is a tool-level
+ * control rather than part of the query body, and the backend trace queries
+ * forbid unknown fields, so the handler strips it before POSTing.
+ */
+function withTraceDetail<T extends ZodObjectAny>(schema: T, kind: string): T {
+ if (!TRACE_QUERY_KINDS.has(kind) || !(schema instanceof z.ZodObject)) {
+ return schema
+ }
+ return schema.extend({
+ [TRACE_DETAIL_FIELD]: z
+ .enum(['summary', 'full'])
+ .default(DEFAULT_TRACE_DETAIL)
+ .optional()
+ .describe(TRACE_DETAIL_DESCRIPTION),
+ }) as unknown as T
+}
+
interface QueryWrapperConfig<T extends ZodObjectAny> {
name: string
schema: T
@@ -132,7 +155,8 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC
// Both the advertised tool schema and the handler's re-parse must use the
// stripped schema — parsing with the original would re-apply the `false`
// default and make omission indistinguishable from an explicit `false`.
- const schema = withoutTestAccountFilterDefault(config.schema)
+ const schema = withTraceDetail(withoutTestAccountFilterDefault(config.schema), config.kind)
+ const isTraceQuery = TRACE_QUERY_KINDS.has(config.kind)
return () => ({
name: config.name,
schema,
@@ -144,6 +168,14 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC
const { output_format: callerOutputFormat, ...queryParams } = params as typeof params & {
output_format?: 'optimized' | 'json'
}
+ // `detail` is a trace-wrapper control, not part of the query body either.
+ // Only the trace wrappers advertise it, so anywhere else a field of that
+ // name belongs to the backend query and stays in `queryParams`.
+ const traceDetailParams = queryParams as { [TRACE_DETAIL_FIELD]?: TraceDetail }
+ const traceDetail = traceDetailParams[TRACE_DETAIL_FIELD] ?? DEFAULT_TRACE_DETAIL
+ if (isTraceQuery) {
+ delete traceDetailParams[TRACE_DETAIL_FIELD]
+ }
const query: Record<string, unknown> = {
...queryParams,
kind: config.kind,
@@ -193,7 +225,7 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC
const data = await context.api.query({ projectId }).runQuery({ query })
const shouldSurfaceFormatted = effectiveOutputFormat !== 'json' && data.formatted_results
- const results = TRACE_QUERY_KINDS.has(config.kind) ? compactTraceResults(data.results) : data.results
+ const results = isTraceQuery ? compactTraceResults(data.results, traceDetail) : data.results
// Include `query` in the payload so UI apps (TrendsVisualizer, LifecycleVisualizer)
// can honor query-level filters like `lifecycleFilter.toggledLifecycles` and
// `trendsFilter.display`.
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-trace.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-trace.json
index 0a757dafb87a..dfe12dd91e99 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-trace.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-trace.json
@@ -37,6 +37,12 @@
],
"description": "Date range for the query."
},
+ "detail": {
+ "default": "full",
+ "description": "How much of each event to return. \"full\" (default) returns complete event properties, subject to response size limits, preserving existing behavior when detail is omitted. Set \"summary\" to browse trace and event metadata (IDs, timestamps, model, latency, tokens, cost, tools called, errors) with short previews of prompts and outputs.",
+ "enum": ["summary", "full"],
+ "type": "string"
+ },
"kind": {
"const": "TraceQuery",
"default": "TraceQuery",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-traces-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-traces-list.json
index b693a3907adb..bdb3a9751f47 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-traces-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-llm-traces-list.json
@@ -37,6 +37,12 @@
],
"description": "Date range for the query."
},
+ "detail": {
+ "default": "full",
+ "description": "How much of each event to return. \"full\" (default) returns complete event properties, subject to response size limits, preserving existing behavior when detail is omitted. Set \"summary\" to browse trace and event metadata (IDs, timestamps, model, latency, tokens, cost, tools called, errors) with short previews of prompts and outputs.",
+ "enum": ["summary", "full"],
+ "type": "string"
+ },
"filterSupportTraces": {
"default": false,
"description": "Exclude support impersonation traces.",
diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.ts
index 66ce570f395d..2b674b353eae 100644
--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts
+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts
@@ -432,6 +432,8 @@ describe('createQueryWrapper trace compaction', () => {
events: [{ properties: { $ai_input: 'x'.repeat(20_000) } }],
}
+ const fullDetailParams = { kind: 'TraceQuery', detail: 'full' } as { kind: string }
+
it('compacts oversized string values for TraceQuery results', async () => {
const tool = createQueryWrapper({ name: 'test', schema, kind: 'TraceQuery' })()
@@ -447,6 +449,47 @@ describe('createQueryWrapper trace compaction', () => {
expect(result.results[0].events[0].properties.$ai_input).toBe('x'.repeat(20_000))
})
+
+ it.each(['TraceQuery', 'TracesQuery'])('%s preserves full content unless summary is requested', async (kind) => {
+ const tool = createQueryWrapper({ name: 'test', schema, kind })()
+ const trace = {
+ id: 'trace-1',
+ inputState: 'input'.repeat(1_000),
+ events: [{ properties: { custom_payload: 'x'.repeat(5_000) } }],
+ }
+
+ const byDefault = (await tool.handler(contextWithResults([trace]), tool.schema.parse({ kind }))) as any
+ const full = (await tool.handler(
+ contextWithResults([trace]),
+ tool.schema.parse({ kind, detail: 'full' })
+ )) as any
+ const summary = (await tool.handler(
+ contextWithResults([trace]),
+ tool.schema.parse({ kind, detail: 'summary' })
+ )) as any
+
+ expect(byDefault.results).toEqual([trace])
+ expect(full.results).toEqual(byDefault.results)
+ expect(summary.results[0]._detail.mode).toBe('summary')
+ expect(summary.results[0].inputState.length).toBeLessThan(1_000)
+ expect(summary.results[0].events[0].properties.custom_payload.length).toBeLessThan(1_000)
+ })
+
+ it('strips detail from the trace query body, which the backend rejects unknown fields on', async () => {
+ const runQuery = vi.fn().mockResolvedValue({ results: [] })
+ const context = {
+ api: {
+ query: vi.fn().mockReturnValue({ runQuery }),
+ getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),
+ },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },
+ } as unknown as Context
+
+ const tool = createQueryWrapper({ name: 'test', schema, kind: 'TraceQuery' })()
+ await tool.handler(context, fullDetailParams)
+
+ expect(runQuery).toHaveBeenCalledWith({ query: { kind: 'TraceQuery' } })
+ })
})
describe('createQueryWrapper actors dispatch', () => {
diff --git a/services/mcp/tests/unit/trace-compaction.test.ts b/services/mcp/tests/unit/trace-compaction.test.ts
index 30726031a26d..18e02ee0e9c2 100644
--- a/services/mcp/tests/unit/trace-compaction.test.ts
+++ b/services/mcp/tests/unit/trace-compaction.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest'
-import { compactTrace, compactTraceResults, MAX_TRACE_CHARS, PER_VALUE_CHAR_LIMIT } from '@/lib/trace-compaction'
+import {
+ MAX_SUMMARY_CHARS,
+ MAX_TRACE_CHARS,
+ PER_VALUE_CHAR_LIMIT,
+ compactTrace,
+ compactTraceResults,
+} from '@/lib/trace-compaction'
describe('compactTrace', () => {
it('truncates a long string property while leaving short values and structure intact', () => {
@@ -71,6 +77,43 @@ describe('compactTrace', () => {
expect(JSON.stringify(result).length).toBeLessThanOrEqual(MAX_TRACE_CHARS)
})
+ it.each([
+ ['double quotes', '"'],
+ ['newlines', '\n'],
+ ['control characters', String.fromCharCode(1)],
+ ])('holds the cap for content made of %s, which JSON escaping inflates', (_label, character) => {
+ // Budgeting on raw character count treats these as one character each while
+ // JSON encodes them as two or six, so the walk's estimate is several times
+ // under the real encoded size.
+ const events = Array.from({ length: 500 }, (_, i) => ({
+ id: `e${i}`,
+ properties: { $ai_input: character.repeat(PER_VALUE_CHAR_LIMIT) },
+ }))
+
+ const result = compactTrace({ id: 'trace-1', events })
+
+ expect(JSON.stringify(result).length).toBeLessThanOrEqual(MAX_TRACE_CHARS)
+ })
+
+ it('holds the cap for a trace that encodes to more than 64MB', () => {
+ // The MCP transport rejects frames past 64MB, so the cap has to bind on
+ // input that large rather than only on the traces seen so far.
+ const chunk = 'x'.repeat(PER_VALUE_CHAR_LIMIT)
+ const trace = {
+ id: 'trace-1',
+ events: Array.from({ length: 7_000 }, (_, i) => ({
+ id: `e${i}`,
+ properties: { $ai_input: chunk, $ai_output_choices: chunk },
+ })),
+ }
+ expect(JSON.stringify(trace).length).toBeGreaterThan(64 * 1024 * 1024)
+
+ const result = compactTrace(trace)
+
+ expect(JSON.stringify(result).length).toBeLessThanOrEqual(MAX_TRACE_CHARS)
+ expect((result as any)._truncated.totalEvents).toBe(7_000)
+ })
+
it('preserves an own __proto__ key in a trace payload instead of corrupting the clone', () => {
// JSON.parse creates __proto__ as an own enumerable data property.
const trace = JSON.parse('{"id":"trace-1","events":[{"properties":{"payload":{"__proto__":"custom"}}}]}')
@@ -82,6 +125,85 @@ describe('compactTrace', () => {
})
})
+describe('compactTrace summary detail', () => {
+ const trace = {
+ id: 'trace-1',
+ totalCost: 0.42,
+ inputState: { messages: [{ role: 'user', content: 'p'.repeat(5_000) }] },
+ events: [
+ {
+ id: 'e1',
+ event: '$ai_generation',
+ createdAt: '2026-09-02T11:30:23Z',
+ properties: {
+ $ai_model: 'gpt-4',
+ $ai_latency: 1.5,
+ $ai_tools_called: ['search'],
+ $ai_is_error: false,
+ $ai_input: 'i'.repeat(5_000),
+ $ai_output_choices: 'o'.repeat(5_000),
+ custom_payload: 'c'.repeat(5_000),
+ },
+ },
+ ],
+ }
+
+ it('keeps navigation metadata verbatim and previews everything else', () => {
+ const result = compactTrace(trace, MAX_SUMMARY_CHARS, 'summary') as any
+
+ const properties = result.events[0].properties
+ expect(properties.$ai_model).toBe('gpt-4')
+ expect(properties.$ai_latency).toBe(1.5)
+ expect(properties.$ai_tools_called).toEqual(['search'])
+ expect(properties.$ai_is_error).toBe(false)
+ expect(properties.$ai_input).toContain('truncated')
+ expect(properties.$ai_output_choices).toContain('truncated')
+ expect(properties.custom_payload).toContain('truncated')
+ expect(result.events[0].createdAt).toBe('2026-09-02T11:30:23Z')
+ expect(result.totalCost).toBe(0.42)
+ expect(result._detail.mode).toBe('summary')
+ })
+
+ it('previews a structured prompt with readable content, not an empty shell', () => {
+ // `$ai_input` is an array of message objects, so a preview only helps if the
+ // walk's per-item allowances leave room to descend into it.
+ const messages = [
+ { role: 'system', content: 's'.repeat(2_000) },
+ { role: 'user', content: 'Why did the checkout funnel drop?' },
+ ]
+
+ const result = compactTrace(
+ { id: 'trace-1', events: [{ id: 'e1', properties: { $ai_input: messages } }] },
+ MAX_SUMMARY_CHARS,
+ 'summary'
+ ) as any
+
+ const preview = result.events[0].properties.$ai_input
+ expect(preview[0].role).toBe('system')
+ expect(preview[0].content).toContain('sss')
+ expect(preview[0].content).toContain('truncated')
+ })
+
+ it('returns far less than the same trace at full detail', () => {
+ const summary = JSON.stringify(compactTrace(trace, MAX_SUMMARY_CHARS, 'summary')).length
+ const full = JSON.stringify(compactTrace(trace, MAX_TRACE_CHARS, 'full')).length
+
+ expect(summary).toBeLessThan(full / 5)
+ })
+
+ it('still drops events when a summarized trace outgrows the summary cap', () => {
+ const events = Array.from({ length: 5_000 }, (_, i) => ({
+ id: `e${i}`,
+ properties: { $ai_input: 'y'.repeat(PER_VALUE_CHAR_LIMIT) },
+ }))
+
+ const result = compactTrace({ id: 'trace-1', events }, MAX_SUMMARY_CHARS, 'summary') as any
+
+ expect(JSON.stringify(result).length).toBeLessThanOrEqual(MAX_SUMMARY_CHARS)
+ expect(result._truncated.omittedEvents).toBeGreaterThan(0)
+ })
+})
+
describe('compactTraceResults', () => {
it('compacts the single trace returned by query-llm-trace', () => {
const hugeInput = 'z'.repeat(PER_VALUE_CHAR_LIMIT + 1)
@@ -108,6 +230,17 @@ describe('compactTraceResults', () => {
expect(sentinel._truncated.totalTraces).toBe(40)
})
+ it('bounds a summarized list to the tighter summary cap', () => {
+ const traces = Array.from({ length: 200 }, (_, i) => ({
+ id: `t${i}`,
+ events: Array.from({ length: 20 }, () => ({ properties: { $ai_input: 'r'.repeat(5_000) } })),
+ }))
+
+ const results = compactTraceResults(traces, 'summary')
+
+ expect(JSON.stringify(results).length).toBeLessThanOrEqual(MAX_SUMMARY_CHARS)
+ })
+
it('passes a non-array result through untouched', () => {
expect(compactTraceResults(null)).toBeNull()
})