:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): bound complete mcp trace responses (#98100)
posthog[bot]14ef424bf0c2
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex bf63d9fa8755..a9af7dbe46ec 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -446,6 +446,13 @@ and [`services/mcp/scripts/yaml-config-schema.ts`](https://github.com/PostHog/po## Testing+The `query-llm-trace` and `query-llm-traces-list` wrappers bound the complete response to 80,000 characters for full detail and 60,000 characters for summary detail.+The limit includes the echoed query, warnings, and serialization of the MCP text content blocks, in either TOON or JSON output.+Summary previews use a 600-character budget per value.+These character budgets reduce response size but do not guarantee a token count; client limits and tokenization vary, so clients may still truncate responses or save them to a file.+Both modes can omit events, and large echoed filters or warnings can also be shortened.+Omission markers direct the agent to narrow the query or open the complete trace in PostHog.+See [How to develop and test](/handbook/engineering/ai/implementation#how-to-develop-and-test)for instructions on running the MCP server locally and verifying tools end-to-end.diff --git a/products/ai_observability/mcp/prompts/query-llm-trace.md b/products/ai_observability/mcp/prompts/query-llm-trace.mdindex e14c9ebb2ea9..3f72e9067c49 100644--- a/products/ai_observability/mcp/prompts/query-llm-trace.md+++ b/products/ai_observability/mcp/prompts/query-llm-trace.md@@ -90,7 +90,7 @@ For an overview, explicitly request `detail: "summary"`, find the events that ma# 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. Both detail modes enforce size limits; `detail: "full"` does not guarantee that every event or property fits.+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 limit the complete response, including echoed filters and warnings, which can also be shortened with omission markers. Neither mode guarantees that every event or property fits. When a full-detail read drops events, re-run with `detail: "summary"` for smaller previews. Summary responses can also omit events.# Remindersdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 3ba0e2987ef1..c626c28b6876 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -9375,7 +9375,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 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.",+ "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 limit the complete response, including echoed filters and warnings, which can also be shortened with omission markers. Neither mode guarantees that every event or property fits. When a full-detail read drops events, re-run with `detail: \"summary\"` for smaller previews. Summary responses can also omit events.\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",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 6fa6b7f78cfc..f9b799fd07f7 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9933,7 +9933,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 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.",+ "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 limit the complete response, including echoed filters and warnings, which can also be shortened with omission markers. Neither mode guarantees that every event or property fits. When a full-detail read drops events, re-run with `detail: \"summary\"` for smaller previews. Summary responses can also omit events.\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",diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.tsindex 49eef3e1d74b..89e50dbcd97a 100644--- a/services/mcp/src/lib/constants.ts+++ b/services/mcp/src/lib/constants.ts@@ -28,6 +28,9 @@ export const MCP_ANALYTICS_SOURCE = 'posthog_mcp_analytics'// fit, and the tool-domain index absorbs whatever budget the fixed sections leave.export const MCP_INSTRUCTIONS_CHAR_BUDGET = 2048+// Response policy, not a token limit: client limits and tokenization vary.+export const MCP_TOOL_OUTPUT_CHAR_BUDGET = 80_000+// Ceiling for the tool-domain index inside the claude.ai exec command reference. That reference// lives in the `command` description, whose serialized schema claude.ai silently drops past// ~16,384 chars, and the index is the only part of it that grows with the tool catalog — one newdiff --git a/services/mcp/src/lib/trace-compaction.ts b/services/mcp/src/lib/trace-compaction.tsindex a578b694b828..37e2a43954a6 100644--- a/services/mcp/src/lib/trace-compaction.ts+++ b/services/mcp/src/lib/trace-compaction.ts@@ -1,3 +1,6 @@+import { MCP_TOOL_OUTPUT_CHAR_BUDGET } from '@/lib/constants'+import { formatResponse } from '@/lib/response'+/*** Bounds the size of LLM trace results before they are serialized toward the MCP* client. `query-llm-trace` returns every event in a trace at every nesting@@ -11,32 +14,29 @@* 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.+ * pass measures the text the client actually receives and shrinks again if the+ * walk's estimate was wrong, so the response cannot breach the cap.+ *+ * Clients can truncate oversized responses or replace them with file references.+ * Truncating here keeps the response parseable and says what was dropped.** Compaction is a client-boundary safeguard only — the underlying query and the* 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.+ * or drops is flagged so the agent can narrow the query or open the trace in+ * PostHog.*//** Longest single string value kept verbatim; longer values are truncated. */export const PER_VALUE_CHAR_LIMIT = 10_000-/**- * Hard cap on the serialized size of a single trace, and on the combined size of- * a trace-list response (~125K tokens at the ~4-chars-per-token heuristic).- * Comfortably below any agent context window while still large enough to inspect- * a real multi-step trace.- */-export const MAX_TRACE_CHARS = 500_000+export const MAX_TRACE_CHARS = MCP_TOOL_OUTPUT_CHAR_BUDGET/**- * Cap for `summary` detail (~30K tokens). Much tighter than the full-detail cap,+ * Cap for `summary` detail. 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+export const MAX_SUMMARY_CHARS = 60_000/** How much of each previewed value a summary keeps. */export const SUMMARY_PREVIEW_CHARS = 600@@ -125,21 +125,31 @@ function isRecord(value: unknown): value is Record<string, unknown> {function serializedLength(value: unknown): number {try {- return JSON.stringify(value)?.length ?? 0+ return JSON.stringify(value).length} catch {return 0}}/**- * Length of a string once encoded as a JSON value, including its quotes. JSON+ * Include text-block escaping because clients also use serialized result size+ * to decide whether to replace the content with a file reference.+ */+function deliveredLength(value: unknown, outputFormat?: 'optimized' | 'json'): number {+ const text = outputFormat === 'json' ? JSON.stringify(value) : formatResponse(value)+ // boffin: Measure the complete response so echoed filters cannot bypass the cap.+ return serializedLength([{ type: 'text', text }])+}++/**+ * Character count of a string 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+ return serializedLength(value)}/**@@ -260,18 +270,23 @@ function compactValue(value: unknown, budget: number): Compacted {* 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 {+function fitToEncodedBudget<T>(+ budget: number,+ compact: (walkBudget: number) => T,+ fallback: T,+ measure: (value: T) => number = serializedLength+): T {let walkBudget = budgetlet out = compact(walkBudget)for (let pass = 0; pass < MAX_FIT_PASSES; pass++) {- const encoded = serializedLength(out)+ const encoded = measure(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+ return measure(out) <= budget ? out : fallback}/** Shorten one value to a preview an agent can scan without reading it in full. */@@ -372,11 +387,15 @@ function compactTraceWithin(trace: Record<string, unknown>, budget: number, detaassignKey(base, 'events', kept)const omitted = events.length - kept.lengthif (omitted > 0) {+ const note =+ detail === 'full'+ ? 'Re-run with detail: "summary" for smaller previews. Summary responses can also omit events; narrow the query or open the trace in PostHog for the complete data.'+ : 'Open the trace in PostHog for the complete, untruncated data, or narrow the query to the events you need.'assignKey(base, '_truncated', {omittedEvents: omitted,totalEvents: events.length,reason: 'Trace exceeded the response size limit; some events were dropped and large values were shortened.',- note: 'Open the trace in PostHog for the complete, untruncated data, or narrow the query to the events you need.',+ note,})}return base@@ -386,7 +405,7 @@ function compactTraceWithin(trace: Record<string, unknown>, budget: number, detafunction minimalTracePlaceholder(trace: Record<string, unknown>): Record<string, unknown> {const events = Array.isArray(trace.events) ? trace.events : []return {- ...(typeof trace.id === 'string' ? { id: trace.id } : {}),+ ...(typeof trace.id === 'string' ? { id: truncateString(trace.id, MIN_ITEM_BUDGET) } : {}),events: [],_truncated: {omittedEvents: events.length,@@ -398,23 +417,38 @@ function minimalTracePlaceholder(trace: Record<string, unknown>): Record<string,}/**- * 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`- * returns many traces, so a single total budget is shared across them and- * 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.+ * Bound the complete trace response in its selected output format. Echoed+ * filters and warnings share a fifth of the walk budget so they cannot crowd+ * out the trace data. The final check includes serialization overhead.*/-export function compactTraceResults(results: unknown, detail: TraceDetail = 'full'): unknown {- if (!Array.isArray(results)) {- return results- }+export function compactTraceResponse(+ response: { results: unknown; [key: string]: unknown },+ detail: TraceDetail = 'full',+ outputFormat?: 'optimized' | 'json'+): Record<string, unknown> {+ const { results, ...envelope } = responseconst budget = detail === 'summary' ? MAX_SUMMARY_CHARS : MAX_TRACE_CHARS- if (results.length <= 1) {- return results.map((trace) => compactTrace(trace, budget, detail))- }- return fitToEncodedBudget(budget, (walkBudget) => compactTraceList(results, walkBudget, detail), [- listTruncationSentinel(results.length, results.length),- ])+ const traces = Array.isArray(results) ? results : []+ const single = traces.length === 1 && isRecord(traces[0]) ? traces[0] : null+ return fitToEncodedBudget(+ budget,+ (walkBudget) => {+ const base = compactValue(envelope, Math.floor(walkBudget / 5))+ const resultsBudget = Math.max(MIN_TRACE_BUDGET, walkBudget - base.cost)+ return {+ ...(base.value as Record<string, unknown>),+ results: Array.isArray(results)+ ? compactTraceList(results, resultsBudget, detail)+ : compactValue(results, resultsBudget).value,+ }+ },+ {+ results: single+ ? [minimalTracePlaceholder(single)]+ : [listTruncationSentinel(traces.length, traces.length)],+ },+ (value) => deliveredLength(value, outputFormat)+ )}function compactTraceList(results: unknown[], budget: number, detail: TraceDetail): unknown[] {diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.tsindex c5f910d79aa0..572dfd57cfcc 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 { type TraceDetail, compactTraceResults } from '@/lib/trace-compaction'+import { type TraceDetail, compactTraceResponse } from '@/lib/trace-compaction'import {POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,POSTHOG_META_KEY,@@ -225,15 +225,20 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperCconst data = await context.api.query({ projectId }).runQuery({ query })const shouldSurfaceFormatted = effectiveOutputFormat !== 'json' && data.formatted_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`.- return {- query,- results,+ const response = {_posthogUrl: buildInsightUrl('InsightVizNode', query, baseUrl, config.urlPrefix),+ query,+ results: data.results,...(data.warnings ? { warnings: data.warnings } : {}),+ }+ if (isTraceQuery) {+ return compactTraceResponse(response, traceDetail, effectiveOutputFormat)+ }+ return {+ ...response,...(shouldSurfaceFormatted ? { [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: data.formatted_results } : {}),}},diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.tsindex 2b674b353eae..33689866c120 100644--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts@@ -1,6 +1,8 @@import { describe, expect, it, vi } from 'vitest'import { z } from 'zod'+import { buildToolResultPayload } from '@/lib/build-tool-result'+import { MCP_TOOL_OUTPUT_CHAR_BUDGET } from '@/lib/constants'import { createQueryWrapper } from '@/tools/query-wrapper-factory'import type { Context } from '@/tools/types'import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_META_KEY } from '@/tools/types'@@ -417,10 +419,10 @@ describe('createQueryWrapper filterTestAccounts project default', () => {describe('createQueryWrapper trace compaction', () => {const schema = z.object({ kind: z.string() })- function contextWithResults(results: unknown): Context {+ function contextWithResults(results: unknown, warnings?: string[]): Context {return {api: {- query: vi.fn().mockReturnValue({ runQuery: vi.fn().mockResolvedValue({ results }) }),+ query: vi.fn().mockReturnValue({ runQuery: vi.fn().mockResolvedValue({ results, warnings }) }),getProjectBaseUrl: vi.fn().mockReturnValue('http://localhost:8010/project/1'),},stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },@@ -450,6 +452,38 @@ describe('createQueryWrapper trace compaction', () => {expect(result.results[0].events[0].properties.$ai_input).toBe('x'.repeat(20_000))})+ it.each(['optimized', 'json'] as const)(+ 'bounds the entire %s response without changing the executed query',+ async (outputFormat) => {+ const tool = createQueryWrapper({+ name: 'query-llm-trace',+ schema: schema.extend({ properties: z.array(z.record(z.string(), z.unknown())) }),+ kind: 'TraceQuery',+ urlPrefix: '/ai-observability/traces',+ outputFormat,+ })()+ const params = {+ kind: 'TraceQuery',+ properties: [+ { key: '$ai_input', type: 'event', operator: 'not_icontains', value: 'filter'.repeat(15_000) },+ ],+ }+ const context = contextWithResults([oversizedTrace], ['warning'.repeat(15_000)])++ const result = await tool.handler(context, params)+ const payload = buildToolResultPayload({+ handlerResult: result,+ toolMeta: tool._meta,+ toolName: tool.name,+ params,+ })++ expect(JSON.stringify(payload.content).length).toBeLessThanOrEqual(MCP_TOOL_OUTPUT_CHAR_BUDGET)+ expect(result).toMatchObject({ _posthogUrl: 'http://localhost:8010/project/1/ai-observability/traces' })+ expect(context.api.query({ projectId: '1' }).runQuery).toHaveBeenCalledWith({ query: params })+ }+ )+it.each(['TraceQuery', 'TracesQuery'])('%s preserves full content unless summary is requested', async (kind) => {const tool = createQueryWrapper({ name: 'test', schema, kind })()const trace = {diff --git a/services/mcp/tests/unit/trace-compaction.test.ts b/services/mcp/tests/unit/trace-compaction.test.tsindex 18e02ee0e9c2..9b8878cd4d44 100644--- a/services/mcp/tests/unit/trace-compaction.test.ts+++ b/services/mcp/tests/unit/trace-compaction.test.ts@@ -1,11 +1,12 @@import { describe, expect, it } from 'vitest'+import { formatResponse } from '@/lib/response'import {MAX_SUMMARY_CHARS,MAX_TRACE_CHARS,PER_VALUE_CHAR_LIMIT,compactTrace,- compactTraceResults,+ compactTraceResponse,} from '@/lib/trace-compaction'describe('compactTrace', () => {@@ -184,6 +185,17 @@ describe('compactTrace summary detail', () => {expect(preview[0].content).toContain('truncated')})+ it.each(['a', '界'])('preserves a 400-character %s preview', (character) => {+ const content = character.repeat(400)+ const result = compactTrace(+ { id: 'trace-1', events: [{ id: 'e1', properties: { $ai_input: content } }] },+ MAX_SUMMARY_CHARS,+ 'summary'+ ) as any++ expect(result.events[0].properties.$ai_input).toBe(content)+ })+it('returns far less than the same trace at full detail', () => {const summary = JSON.stringify(compactTrace(trace, MAX_SUMMARY_CHARS, 'summary')).lengthconst full = JSON.stringify(compactTrace(trace, MAX_TRACE_CHARS, 'full')).length@@ -204,10 +216,12 @@ describe('compactTrace summary detail', () => {})})-describe('compactTraceResults', () => {+describe('compactTraceResponse', () => {it('compacts the single trace returned by query-llm-trace', () => {const hugeInput = 'z'.repeat(PER_VALUE_CHAR_LIMIT + 1)- const results = compactTraceResults([{ id: 't1', events: [{ properties: { $ai_input: hugeInput } }] }]) as any[]+ const results = compactTraceResponse({+ results: [{ id: 't1', events: [{ properties: { $ai_input: hugeInput } }] }],+ }).results as any[]expect(results[0].events[0].properties.$ai_input as string).toContain('truncated')})@@ -222,7 +236,7 @@ describe('compactTraceResults', () => {id: `t${i}`,events: [{ id: `e${i}`, properties: { $ai_input: [chunk, chunk, chunk, chunk] } }],}))- const results = compactTraceResults(traces) as any[]+ const results = compactTraceResponse({ results: traces }).results as any[]expect(JSON.stringify(results).length).toBeLessThanOrEqual(MAX_TRACE_CHARS + 5_000)const sentinel = results[results.length - 1]@@ -236,12 +250,87 @@ describe('compactTraceResults', () => {events: Array.from({ length: 20 }, () => ({ properties: { $ai_input: 'r'.repeat(5_000) } })),}))- const results = compactTraceResults(traces, 'summary')+ const results = compactTraceResponse({ results: traces }, 'summary').resultsexpect(JSON.stringify(results).length).toBeLessThanOrEqual(MAX_SUMMARY_CHARS)})it('passes a non-array result through untouched', () => {- expect(compactTraceResults(null)).toBeNull()+ expect(compactTraceResponse({ results: null }).results).toBeNull()+ })++ // These measure the TOON text the client receives, not the JSON size the walk+ // budgets against, because TOON runs larger for a nested trace.+ describe('delivered response size', () => {+ const message = (role: string, repeat: number): unknown => ({+ role,+ content: 'Some conversation text about the user request. '.repeat(repeat),+ })+ const largeTrace = {+ id: 'trace-1',+ inputState: { messages: [message('user', 40)] },+ outputState: { messages: [message('assistant', 40)] },+ events: Array.from({ length: 40 }, (_, i) => ({+ id: `e${i}`,+ event: '$ai_generation',+ properties: {+ $ai_span_id: `span-${i}`,+ $ai_parent_id: 'root',+ $ai_model: 'gpt-4o',+ $ai_input: [message('system', 30), message('user', 40)],+ $ai_output_choices: [message('assistant', 35)],+ },+ })),+ }++ it.each(['a', '界'])('retains a 40-event summary with %s content', (character) => {+ const trace = {+ ...largeTrace,+ events: largeTrace.events.map((event) => ({+ ...event,+ properties: {+ ...event.properties,+ $ai_input: [{ role: 'user', content: character.repeat(2_000) }],+ $ai_output_choices: [{ role: 'assistant', content: character.repeat(2_000) }],+ },+ })),+ }+ const response = compactTraceResponse({ results: [trace] }, 'summary')+ const [result] = response.results as any[]++ expect(result.events.map((event: { id: string }) => event.id)).toEqual(+ trace.events.map((event) => event.id)+ )+ expect(result._truncated).toBeUndefined()+ })++ it.each(+ (['full', 'summary'] as const).flatMap((detail) =>+ ['Some conversation text. ', '分析結果を説明してください。', '"quoted"\n\\'].map((content) => ({+ detail,+ content,+ }))+ )+ )('bounds the complete response for $detail detail with $content', ({ detail, content }) => {+ const trace = {+ ...largeTrace,+ events: largeTrace.events.map((event) => ({+ ...event,+ properties: { ...event.properties, $ai_input: content.repeat(500) },+ })),+ }+ const response = compactTraceResponse({ results: [trace] }, detail)+ const contentBlocks = [{ type: 'text', text: formatResponse(response) }]++ expect(JSON.stringify(contentBlocks).length).toBeLessThanOrEqual(detail === 'summary' ? 60_000 : 80_000)+ })++ it('points a truncated full-detail read at summary detail', () => {+ const [result] = compactTraceResponse({ results: [largeTrace] }, 'full').results as any[]++ expect(result._truncated.totalEvents).toBe(40)+ expect(result._truncated.note).toContain('summary')+ expect(result._truncated.note).toContain('can also omit events')+ })})})