: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): allowlist trace properties in MCP responses (#104965)
posthog[bot]0611c1979c52
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex d360b505f879..1f7cee0ea140 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -123,8 +123,9 @@ jobs:- 'frontend/src/queries/schema.json'# Products changes need to trigger Python CI to validate the json usage is still valid- 'frontend/src/products.json'- # A hand-edit to the generated taxonomy JSON must reach the drift check+ # A hand-edit to either generated taxonomy output must reach the drift check- 'frontend/src/taxonomy/core-filter-definitions-by-group.json'+ - 'services/mcp/src/lib/trace-property-allowlist.generated.ts'# Same for the generated object-tag registries- 'frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts'- 'products/desktop/packages/core/src/inbox/objectKinds.generated.ts'diff --git a/.oxfmtrc.json b/.oxfmtrc.jsonindex dfa0475c0132..66e927d08202 100644--- a/.oxfmtrc.json+++ b/.oxfmtrc.json@@ -135,6 +135,7 @@"services/mcp/src/**/*.md","services/mcp/worker-configuration.d.ts","frontend/src/taxonomy/core-filter-definitions-by-group.json",+ "services/mcp/src/lib/trace-property-allowlist.generated.ts","frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts","products/review_hog/backend/reviewer/prompts/**/schema.json","**/chart/*/templates/**",diff --git a/bin/build-taxonomy-json.py b/bin/build-taxonomy-json.pyindex 23c6d59f840f..af7d977641ba 100755--- a/bin/build-taxonomy-json.py+++ b/bin/build-taxonomy-json.py@@ -1,5 +1,8 @@#!/usr/bin/env python-"""Make CORE_FILTER_DEFINITIONS_BY_GROUP accessible frontend-side.+"""Make CORE_FILTER_DEFINITIONS_BY_GROUP accessible outside Python.++Emits the whole taxonomy for the frontend, and the `$ai_*` event property names+for the MCP server, which allowlists them in trace responses.Run via hogli: `hogli build:taxonomy-json`. `--check` is what ci-python.yml and`hogli ci:preflight` call to fail on drift without writing.@@ -19,6 +22,7 @@ sys.path.insert(0, str(REPO_ROOT))from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP # noqa: E402 — needs the sys.path line aboveOUTPUT = REPO_ROOT / "frontend/src/taxonomy/core-filter-definitions-by-group.json"+MCP_ALLOWLIST_OUTPUT = REPO_ROOT / "services/mcp/src/lib/trace-property-allowlist.generated.ts"def render() -> str:@@ -34,13 +38,51 @@ def render() -> str:return json.dumps(with_comment, indent=4, sort_keys=True)-def check() -> int:+def render_mcp_allowlist() -> str:+ """The `$ai_*` event properties an MCP trace response may carry.++ `query-llm-trace` and `query-llm-traces-list` withhold every property the+ taxonomy does not define, so an application cannot hand a credential back to+ an agent through the event property bag. The rule cannot be a `$ai_` prefix+ test, because capture does not reserve the namespace.+ """+ names = sorted(name for name in CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"] if name.startswith("$ai_"))+ # oxfmt wants single quotes, so format by hand rather than with json.dumps and+ # keep the output byte-stable. A taxonomy name never needs escaping; assert it+ # so one that does fails the build instead of the TypeScript parse.+ for name in names:+ if "'" in name or "\\" in name:+ raise RuntimeError(f"unexpected character in property name: {name!r}")+ body = ",\n".join(f" '{name}'" for name in names)+ return (+ "// THIS FILE IS AUTOGENERATED from posthog/taxonomy/taxonomy.py. DO NOT EDIT\n"+ "// MANUALLY. To update: pnpm run taxonomy:build\n"+ "//\n"+ "// Every other property of a trace event is withheld from MCP responses — see\n"+ "// services/mcp/src/lib/trace-redaction.ts.\n"+ "\n"+ "export const AI_TAXONOMY_EVENT_PROPERTIES = [\n"+ f"{body},\n"+ "] as const\n"+ )+++def outputs() -> list[tuple[Path, str]]:+ return [(OUTPUT, render()), (MCP_ALLOWLIST_OUTPUT, render_mcp_allowlist())]+++def read_bytes(path: Path) -> bytes:# Bytes, not text, so no newline translation can hide or invent a difference.- on_disk = OUTPUT.read_bytes() if OUTPUT.exists() else b""- if on_disk == render().encode():+ return path.read_bytes() if path.exists() else b""+++def check() -> int:+ stale = [path for path, contents in outputs() if read_bytes(path) != contents.encode()]+ if not stale:return 0- # stdout, because ci:preflight reports `result.stdout or result.stderr`.- print(f"{OUTPUT.relative_to(REPO_ROOT)} is out of date with posthog/taxonomy/taxonomy.py.")+ for path in stale:+ # stdout, because ci:preflight reports `result.stdout or result.stderr`.+ print(f"{path.relative_to(REPO_ROOT)} is out of date with posthog/taxonomy/taxonomy.py.")print("Run `hogli build:taxonomy-json` and commit the result.")return 1@@ -60,7 +102,8 @@ def main() -> int:# ci-python.yml cannot flap. The other half of that guarantee is the ignorePatterns# entry in .oxfmtrc.json, which keeps lint-staged's `bin/hogli format:yaml` (oxfmt)# off this file. Keep both.- OUTPUT.write_bytes(render().encode())+ for path, contents in outputs():+ path.write_bytes(contents.encode())return 0diff --git a/posthog/taxonomy/test/test_build_taxonomy_json.py b/posthog/taxonomy/test/test_build_taxonomy_json.pyindex 49a6a44b871a..42e418d8f232 100644--- a/posthog/taxonomy/test/test_build_taxonomy_json.py+++ b/posthog/taxonomy/test/test_build_taxonomy_json.py@@ -19,10 +19,11 @@ def _load_generator() -> ModuleType:def _retarget(module: ModuleType, monkeypatch: pytest.MonkeyPatch, target: Path) -> None:- # REPO_ROOT moves with OUTPUT because the drift branch prints- # OUTPUT.relative_to(REPO_ROOT), which raises for a path outside the repo.+ # REPO_ROOT moves with the outputs because the drift branch prints+ # path.relative_to(REPO_ROOT), which raises for a path outside the repo.monkeypatch.setattr(module, "REPO_ROOT", target.parent)monkeypatch.setattr(module, "OUTPUT", target)+ monkeypatch.setattr(module, "MCP_ALLOWLIST_OUTPUT", target.parent / "trace-property-allowlist.generated.ts")class TestTaxonomyDriftDetection:@@ -39,7 +40,18 @@ class TestTaxonomyDriftDetection:def test_check_accepts_the_rendered_bytes(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:module = _load_generator()target = tmp_path / "core-filter-definitions-by-group.json"- target.write_bytes(module.render().encode())_retarget(module, monkeypatch, target)+ for path, contents in module.outputs():+ path.write_bytes(contents.encode())assert module.check() == 0++ def test_check_reports_drift_in_the_mcp_allowlist_alone(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ module = _load_generator()+ target = tmp_path / "core-filter-definitions-by-group.json"+ _retarget(module, monkeypatch, target)+ target.write_bytes(module.render().encode())++ assert module.check() == 1diff --git a/products/ai_observability/mcp/prompts/query-llm-trace.md b/products/ai_observability/mcp/prompts/query-llm-trace.mdindex 3f72e9067c49..0ccfca269399 100644--- a/products/ai_observability/mcp/prompts/query-llm-trace.md+++ b/products/ai_observability/mcp/prompts/query-llm-trace.md@@ -1,6 +1,6 @@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.+By default the response returns the retained event properties, subject to response size limits. Set `detail` to `"summary"` for metadata alone when browsing a trace, with no prompts or outputs in it.Use cases:@@ -25,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), subject to response size limits. Each event has `properties`, returned in full by default and previewed under `detail: "summary"`.+- `events` — **all** child events in the trace at every nesting depth (not just direct children), subject to response size limits. Each event has `properties`, holding the retained properties in full by default and metadata only 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.@@ -83,14 +83,21 @@ If the trace is old, provide a date range to help the query find it efficiently:`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" }`.+- `"full"` (default) returns every retained property in full, bounded by the response size limit below.+- `"summary"` opts into trace fields, plus each event's `id`, `createdAt`, `event` type, and its metadata: tree position (`$ai_trace_id`, `$ai_span_id`, `$ai_generation_id`, `$ai_parent_id`, `$ai_span_name`), the model (`$ai_model`, `$ai_provider`), timing (`$ai_latency`, `$ai_time_to_first_token`), the whole spend breakdown (every token count, per-token price, and per-modality cost), tool calls, metric and score values, and failure status (`$ai_is_error`, `$ai_http_status`, `$ai_error_type`, `$ai_status`, `$ai_stop_reason`). Everything else is left out, not shortened: their names are listed in `_summaryOmittedKeys` beside the bag. A summarized trace carries `_detail: { "mode": "summary" }`.+- A summary carries no conversation content. Prompts, outputs, span states, `inputState` / `outputState`, `$ai_error`, and `$ai_feedback_text` all need `detail: "full"`. Use `$ai_is_error` and `$ai_http_status` to find the failed events in a summary, then read their messages at full detail. The trace and span names (`traceName`, `$ai_span_name`) do come back, and an SDK can write anything into those.-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.+For a cost or latency survey, request `detail: "summary"`. Find the events that matter from their metadata, then re-run with `detail: "full"` when you need the text. Keep relevant date and property filters when requesting full detail.++# Withheld properties++Only `$ai_*` properties PostHog's taxonomy defines, plus the ones first-party code writes without describing (`$ai_generation_id`, `$ai_cache_read_cost_usd`, `$ai_cache_creation_cost_usd`, `$ai_effort`) and `$session_id`, `$lib`, and `$lib_version`, reach you. Every other event property, and every person property, is withheld whichever `detail` you ask for, and its name is listed in `_redactedKeys` beside the bag. `$ai_base_url` and `$ai_request_url` arrive as the origin and path only, without the query string a provider key often sits in. A value that is not an `http` or `https` URL is withheld instead, because there is no endpoint to keep.++A withheld property is unchanged in PostHog: it still works as a filter here, and you can read its value in the PostHog UI or with `execute-sql`.# 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 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.+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 metadata alone. Summary responses can also omit events.# Remindersdiff --git a/products/ai_observability/mcp/prompts/query-llm-traces-list.md b/products/ai_observability/mcp/prompts/query-llm-traces-list.mdindex c41ee28fb1e3..ce51049cc9a5 100644--- a/products/ai_observability/mcp/prompts/query-llm-traces-list.md+++ b/products/ai_observability/mcp/prompts/query-llm-traces-list.md@@ -1,6 +1,6 @@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.+Set `detail: "summary"` for event metadata without any prompts or outputs when picking candidate traces, then read the one you pick with `query-llm-trace`. Omitting `detail` returns the retained properties in full, subject to size limits.Use 'read-data-schema' to discover available event properties for filtering (e.g. `$ai_model`, `$ai_provider`).@@ -96,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 event data, returned in full by default and previewed under `detail: "summary"`, subject to response size limits. See "Event types and their properties" below.+- `events` — list of direct child events (generations, metrics, feedback). Each event's `properties` contains the retained event data, returned in full by default and reduced to metadata under `detail: "summary"`, subject to response size limits. See "Event types and their properties" below.## Event types and their properties@@ -128,12 +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`.+## Withheld properties++Only `$ai_*` properties PostHog's taxonomy defines, plus the ones first-party code writes without describing (`$ai_generation_id`, `$ai_cache_read_cost_usd`, `$ai_cache_creation_cost_usd`, `$ai_effort`) and `$session_id`, `$lib`, and `$lib_version`, reach you. Every other event property, and every person property, is withheld whichever `detail` you ask for, and its name is listed in `_redactedKeys` beside the bag. `$ai_base_url` and `$ai_request_url` arrive as the origin and path only, without the query string a provider key often sits in. A value that is not an `http` or `https` URL is withheld instead, because there is no endpoint to keep.++A withheld property is unchanged in PostHog: it still works as a filter here, and you can read its value in the PostHog UI or with `execute-sql`.+## 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" }`.+- `"full"` (default) returns every retained property in full, subject to response size limits.+- `"summary"` opts into trace and event metadata only. It carries no conversation content: prompts, outputs, span states, `$ai_error`, and `$ai_feedback_text` are left out, and their names are listed in `_summaryOmittedKeys` beside the bag. The trace and span names (`traceName`, `$ai_span_name`) do come back, and an SDK can write anything into those. Use `$ai_is_error` and `$ai_http_status` to find the failed events, then read their messages with `detail: "full"`. 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.diff --git a/products/ai_observability/skills/exploring-llm-traces/SKILL.md b/products/ai_observability/skills/exploring-llm-traces/SKILL.mdindex 74f4c0e34ddb..66c943cf7028 100644--- a/products/ai_observability/skills/exploring-llm-traces/SKILL.md+++ b/products/ai_observability/skills/exploring-llm-traces/SKILL.md@@ -55,9 +55,10 @@ For exact trace and session URLs, skip schema discovery for the standard `$ai_*`### 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.+Explicitly set `detail: "summary"` when browsing traces.+This returns event metadata and leaves the conversation content out,+so browsing does not spend context on prompts and outputs.+Omitting `detail` still returns full detail for compatibility with existing callers.For a trace URL, call `posthog:query-llm-trace` with:@@ -85,8 +86,11 @@ 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 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.+The result contains trace and event metadata only.+Prompts, outputs, span states, `$ai_error` and `$ai_feedback_text` are left out,+and their names are listed in `_summaryOmittedKeys` beside the property bag.+A trace with `_detail: { "mode": "summary" }` carries no conversation content at all.+Read the content with `detail: "full"`.From the result you get:@@ -113,9 +117,13 @@ Preserve the date range from the original URL or discovery query instead of copyKeep relevant property filters to narrow the read. If the user already identified the trace and needsexact 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.+Both modes enforce response size limits.+Check the omission and truncation markers before drawing conclusions.+A dropped event, a name listed in `_summaryOmittedKeys` or `_redactedKeys`,+or a keyword missing from a summary 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.+Both detail modes also withhold the properties that are not AI payload, described in+[Withheld properties](#withheld-properties) below.### Step 4 — Parse large full-detail results with scripts@@ -137,12 +145,28 @@ SPAN="tool_name" python3 scripts/extract_span.py /path/to/persisted-file.json# 4. Full conversation with thinking blocks and tool callspython3 scripts/extract_conversation.py /path/to/persisted-file.json-# 5. Search for a keyword across all properties+# 5. Search for a keyword across the returned propertiesSEARCH="keyword" python3 scripts/search_traces.py /path/to/persisted-file.json```All scripts support `MAX_LEN=N` env var to control truncation (0 = unlimited).+## Withheld properties++The two trace tools return the AI payload only.+Only the `$ai_*` properties PostHog's taxonomy defines reach you,+plus `$ai_generation_id`, `$ai_cache_read_cost_usd`, `$ai_cache_creation_cost_usd`, `$ai_effort`,+`$session_id`, `$lib` and `$lib_version`.+Every other event property, and every person property, is withheld in both detail modes,+and its name is listed in `_redactedKeys` beside the property bag.+`$ai_base_url` and `$ai_request_url` arrive without their query string.++This covers a project's own custom properties, such as `project_id` or `conversation_id`.+A withheld property is unchanged in PostHog.+It still works as a filter here, and you can read its value in the PostHog UI or with `execute-sql`.+A name in `_redactedKeys` means the property is on the event and only its value is withheld.+`search_traces.py` cannot find a keyword that appears only in a withheld property.+## Investigation patterns### "Did the agent use the tool correctly?"@@ -208,6 +232,7 @@ Before filtering traces, discover what's available:Only then construct the `query-llm-traces-list` call with property filters.This is especially important for custom properties like `project_id`, `conversation_id`, `user_tier`, etc. — these vary per project and cannot be guessed.+A custom property works as a filter even though its value is withheld from the response.Do not confirm `$ai_*` properties, but confirm any other like `email` of a person.@@ -283,8 +308,9 @@ For more complex SQL patterns, read these references:## Parsing large trace resultsTrace 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.+Use a full-detail response for content extraction and keyword searches.+The scripts cannot recover content omitted from a summary, withheld from a property bag,+or dropped by truncation.### Persisted file formatdiff --git a/products/ai_observability/skills/feature-usage-feed/SKILL.md b/products/ai_observability/skills/feature-usage-feed/SKILL.mdindex 01578cf7613e..2d6faf377aa6 100644--- a/products/ai_observability/skills/feature-usage-feed/SKILL.md+++ b/products/ai_observability/skills/feature-usage-feed/SKILL.md@@ -142,7 +142,12 @@ posthog:query-llm-traces-list`randomOrder: true` matters — recency bias produces a non-representative sample. Pick 5-10 traces to test against.-**Output size warning:** `query-llm-traces-list` with `limit: 10` routinely returns 3-6MB of JSON (full input/output per generation). This will blow your context window. **Immediately delegate the summarization to a subagent** the moment you see the "result exceeds maximum allowed tokens" error — ask the subagent to extract, per trace: the trace id, the first user message (truncated to ~300 chars), the sampled `$current_url`, and a one-sentence description of what the conversation was about. Don't try to read the raw file in-line.+**Output size warning:** `query-llm-traces-list` with `limit: 10` routinely returns 3-6MB of JSON (full input/output per generation). This will blow your context window. **Immediately delegate the summarization to a subagent** the moment you see the "result exceeds maximum allowed tokens" error — ask the subagent to extract, per trace: the trace id, the first user message (truncated to ~300 chars), and a one-sentence description of what the conversation was about. Don't try to read the raw file in-line.++The trace tools return the AI payload only.+A custom property such as `$current_url`, `agent_mode` or `ai_product` comes back as a name in `_redactedKeys` with no value,+so read it with `posthog:execute-sql` for the sampled trace ids when a sample needs it.+Filtering on those properties, as both patterns above do, is unaffected.**Watch for topic drift in Pattern B samples.** The `agent_mode` tag reflects the user's mode selection at the time of the turn — but chat state retains the mode even if the user drifts off-topic within the same conversation (e.g. user selected "error tracking" mode, then asked an unrelated pricing question three turns later). Your eval prompt's classification step needs to be permissive about topic-drift: PASS should mean "user is doing something recognizably in-scope for this mode", FAIL should catch the off-topic drift. If you don't, your feed will include irrelevant PASS entries that happen to carry the mode tag.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 93e4a3d5d44d..712a8bc83fad 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 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.",+ "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 the retained event properties, subject to response size limits. Set `detail` to `\"summary\"` for metadata alone when browsing a trace, with no prompts or outputs in it.\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`, holding the retained properties in full by default and metadata only 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 retained property in full, bounded by the response size limit below.\n- `\"summary\"` opts into trace fields, plus each event's `id`, `createdAt`, `event` type, and its metadata: tree position (`$ai_trace_id`, `$ai_span_id`, `$ai_generation_id`, `$ai_parent_id`, `$ai_span_name`), the model (`$ai_model`, `$ai_provider`), timing (`$ai_latency`, `$ai_time_to_first_token`), the whole spend breakdown (every token count, per-token price, and per-modality cost), tool calls, metric and score values, and failure status (`$ai_is_error`, `$ai_http_status`, `$ai_error_type`, `$ai_status`, `$ai_stop_reason`). Everything else is left out, not shortened: their names are listed in `_summaryOmittedKeys` beside the bag. A summarized trace carries `_detail: { \"mode\": \"summary\" }`.\n- A summary carries no conversation content. Prompts, outputs, span states, `inputState` / `outputState`, `$ai_error`, and `$ai_feedback_text` all need `detail: \"full\"`. Use `$ai_is_error` and `$ai_http_status` to find the failed events in a summary, then read their messages at full detail. The trace and span names (`traceName`, `$ai_span_name`) do come back, and an SDK can write anything into those.\n\nFor a cost or latency survey, request `detail: \"summary\"`. Find the events that matter from their metadata, then re-run with `detail: \"full\"` when you need the text. Keep relevant date and property filters when requesting full detail.\n\n# Withheld properties\n\nOnly `$ai_*` properties PostHog's taxonomy defines, plus the ones first-party code writes without describing (`$ai_generation_id`, `$ai_cache_read_cost_usd`, `$ai_cache_creation_cost_usd`, `$ai_effort`) and `$session_id`, `$lib`, and `$lib_version`, reach you. Every other event property, and every person property, is withheld whichever `detail` you ask for, and its name is listed in `_redactedKeys` beside the bag. `$ai_base_url` and `$ai_request_url` arrive as the origin and path only, without the query string a provider key often sits in. A value that is not an `http` or `https` URL is withheld instead, because there is no endpoint to keep.\n\nA withheld property is unchanged in PostHog: it still works as a filter here, and you can read its value in the PostHog UI or with `execute-sql`.\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 metadata alone. 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",@@ -9390,7 +9390,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\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`.",+ "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\"` for event metadata without any prompts or outputs when picking candidate traces, then read the one you pick with `query-llm-trace`. Omitting `detail` returns the retained properties in full, 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 retained event data, returned in full by default and reduced to metadata 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## Withheld properties\n\nOnly `$ai_*` properties PostHog's taxonomy defines, plus the ones first-party code writes without describing (`$ai_generation_id`, `$ai_cache_read_cost_usd`, `$ai_cache_creation_cost_usd`, `$ai_effort`) and `$session_id`, `$lib`, and `$lib_version`, reach you. Every other event property, and every person property, is withheld whichever `detail` you ask for, and its name is listed in `_redactedKeys` beside the bag. `$ai_base_url` and `$ai_request_url` arrive as the origin and path only, without the query string a provider key often sits in. A value that is not an `http` or `https` URL is withheld instead, because there is no endpoint to keep.\n\nA withheld property is unchanged in PostHog: it still works as a filter here, and you can read its value in the PostHog UI or with `execute-sql`.\n\n## Detail level\n\n`detail` controls how much of each event you get back.\n\n- `\"full\"` (default) returns every retained property in full, subject to response size limits.\n- `\"summary\"` opts into trace and event metadata only. It carries no conversation content: prompts, outputs, span states, `$ai_error`, and `$ai_feedback_text` are left out, and their names are listed in `_summaryOmittedKeys` beside the bag. The trace and span names (`traceName`, `$ai_span_name`) do come back, and an SDK can write anything into those. Use `$ai_is_error` and `$ai_http_status` to find the failed events, then read their messages with `detail: \"full\"`. 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.jsonindex 68cad18859fd..77b0545a8613 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 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.",+ "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 the retained event properties, subject to response size limits. Set `detail` to `\"summary\"` for metadata alone when browsing a trace, with no prompts or outputs in it.\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`, holding the retained properties in full by default and metadata only 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 retained property in full, bounded by the response size limit below.\n- `\"summary\"` opts into trace fields, plus each event's `id`, `createdAt`, `event` type, and its metadata: tree position (`$ai_trace_id`, `$ai_span_id`, `$ai_generation_id`, `$ai_parent_id`, `$ai_span_name`), the model (`$ai_model`, `$ai_provider`), timing (`$ai_latency`, `$ai_time_to_first_token`), the whole spend breakdown (every token count, per-token price, and per-modality cost), tool calls, metric and score values, and failure status (`$ai_is_error`, `$ai_http_status`, `$ai_error_type`, `$ai_status`, `$ai_stop_reason`). Everything else is left out, not shortened: their names are listed in `_summaryOmittedKeys` beside the bag. A summarized trace carries `_detail: { \"mode\": \"summary\" }`.\n- A summary carries no conversation content. Prompts, outputs, span states, `inputState` / `outputState`, `$ai_error`, and `$ai_feedback_text` all need `detail: \"full\"`. Use `$ai_is_error` and `$ai_http_status` to find the failed events in a summary, then read their messages at full detail. The trace and span names (`traceName`, `$ai_span_name`) do come back, and an SDK can write anything into those.\n\nFor a cost or latency survey, request `detail: \"summary\"`. Find the events that matter from their metadata, then re-run with `detail: \"full\"` when you need the text. Keep relevant date and property filters when requesting full detail.\n\n# Withheld properties\n\nOnly `$ai_*` properties PostHog's taxonomy defines, plus the ones first-party code writes without describing (`$ai_generation_id`, `$ai_cache_read_cost_usd`, `$ai_cache_creation_cost_usd`, `$ai_effort`) and `$session_id`, `$lib`, and `$lib_version`, reach you. Every other event property, and every person property, is withheld whichever `detail` you ask for, and its name is listed in `_redactedKeys` beside the bag. `$ai_base_url` and `$ai_request_url` arrive as the origin and path only, without the query string a provider key often sits in. A value that is not an `http` or `https` URL is withheld instead, because there is no endpoint to keep.\n\nA withheld property is unchanged in PostHog: it still works as a filter here, and you can read its value in the PostHog UI or with `execute-sql`.\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 metadata alone. 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",@@ -9948,7 +9948,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\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`.",+ "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\"` for event metadata without any prompts or outputs when picking candidate traces, then read the one you pick with `query-llm-trace`. Omitting `detail` returns the retained properties in full, 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 retained event data, returned in full by default and reduced to metadata 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## Withheld properties\n\nOnly `$ai_*` properties PostHog's taxonomy defines, plus the ones first-party code writes without describing (`$ai_generation_id`, `$ai_cache_read_cost_usd`, `$ai_cache_creation_cost_usd`, `$ai_effort`) and `$session_id`, `$lib`, and `$lib_version`, reach you. Every other event property, and every person property, is withheld whichever `detail` you ask for, and its name is listed in `_redactedKeys` beside the bag. `$ai_base_url` and `$ai_request_url` arrive as the origin and path only, without the query string a provider key often sits in. A value that is not an `http` or `https` URL is withheld instead, because there is no endpoint to keep.\n\nA withheld property is unchanged in PostHog: it still works as a filter here, and you can read its value in the PostHog UI or with `execute-sql`.\n\n## Detail level\n\n`detail` controls how much of each event you get back.\n\n- `\"full\"` (default) returns every retained property in full, subject to response size limits.\n- `\"summary\"` opts into trace and event metadata only. It carries no conversation content: prompts, outputs, span states, `$ai_error`, and `$ai_feedback_text` are left out, and their names are listed in `_summaryOmittedKeys` beside the bag. The trace and span names (`traceName`, `$ai_span_name`) do come back, and an SDK can write anything into those. Use `$ai_is_error` and `$ai_http_status` to find the failed events, then read their messages with `detail: \"full\"`. 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/plain-object.ts b/services/mcp/src/lib/plain-object.tsnew file mode 100644index 000000000000..450e2e3fb3ee--- /dev/null+++ b/services/mcp/src/lib/plain-object.ts@@ -0,0 +1,19 @@+/** Helpers for walking arbitrary parsed JSON, where any key or shape is possible. */++export function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++/**+ * Assign a key without triggering the inherited `__proto__` setter. Parsed JSON+ * can legitimately carry an own `__proto__` key (e.g. a tool payload being+ * debugged); a plain `out[key] = v` would set the target's prototype instead of+ * creating an own property, and drop the value from serialization.+ */+export function assignKey(target: Record<string, unknown>, key: string, value: unknown): void {+ if (key === '__proto__') {+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })+ } else {+ target[key] = value+ }+}diff --git a/services/mcp/src/lib/trace-compaction.ts b/services/mcp/src/lib/trace-compaction.tsindex 37e2a43954a6..e192346c7b9a 100644--- a/services/mcp/src/lib/trace-compaction.ts+++ b/services/mcp/src/lib/trace-compaction.ts@@ -1,6 +1,3 @@-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@@ -8,9 +5,9 @@ import { formatResponse } from '@/lib/response'* 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+ * Two layers keep that in check. `summary` detail leaves event content out+ * altogether and reports the omitted names, so the summary response is trace and+ * event metadata an agent reads to decide what to open. 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@@ -26,6 +23,10 @@ import { formatResponse } from '@/lib/response'* PostHog.*/+import { MCP_TOOL_OUTPUT_CHAR_BUDGET } from '@/lib/constants'+import { assignKey, isRecord } from '@/lib/plain-object'+import { formatResponse } from '@/lib/response'+/** Longest single string value kept verbatim; longer values are truncated. */export const PER_VALUE_CHAR_LIMIT = 10_000@@ -38,13 +39,11 @@ export const MAX_TRACE_CHARS = MCP_TOOL_OUTPUT_CHAR_BUDGET*/export const MAX_SUMMARY_CHARS = 60_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.+ * timing, model, cost, tool, and error metadata and omits the content, so a+ * survey of a trace never carries prompts or completions. `full` keeps every+ * retained property, bounded by the compaction budget.*/export type TraceDetail = 'summary' | 'full'@@ -75,11 +74,24 @@ const MAX_FIT_PASSES = 4const 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.+ * Event properties that stay 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 is omitted, name only.+ *+ * A name belongs here when its value is a number, a boolean, a short label, or+ * an identifier — never free text and never a document. That is why the cost,+ * token and timing fields are listed one by one rather than taken from the+ * redaction allowlist wholesale: the allowlist is what a trace may return at+ * all, and most of it is the conversation.+ *+ * `$ai_error` and `$ai_feedback_text` are deliberately absent, though they read+ * as metadata. Both are free text a person or a provider wrote, and a provider+ * error routinely quotes the prompt back, so keeping them would put+ * conversation content in the mode that promises none. `$ai_is_error`,+ * `$ai_http_status`, `$ai_error_type` and `$ai_status` stay, so a survey can+ * still find the failures and then read them at `full` detail.*/-const SUMMARY_METADATA_PROPERTIES = new Set([+export const SUMMARY_METADATA_PROPERTIES = new Set(['$ai_trace_id','$ai_span_id','$ai_generation_id',@@ -88,6 +100,9 @@ const SUMMARY_METADATA_PROPERTIES = new Set(['$ai_session_id','$ai_model','$ai_provider',+ '$ai_temperature',+ '$ai_stream',+ '$ai_effort','$ai_latency','$ai_input_tokens','$ai_output_tokens',@@ -97,19 +112,75 @@ const SUMMARY_METADATA_PROPERTIES = new Set(['$ai_output_cost_usd','$ai_total_cost_usd','$ai_tools_called',+ '$ai_tool_call_count','$ai_is_error',- '$ai_error','$ai_http_status',+ '$ai_error_type',+ '$ai_status',+ '$ai_stop_reason',+ '$ai_time_to_first_token','$ai_metric_name','$ai_metric_value',- '$ai_feedback_text',+ '$ai_score',+ '$ai_score_max',+ '$ai_score_min',+ '$ai_span_type',+ // Spend. A cost or latency survey is what summary detail is for, so the+ // whole breakdown stays: every token count, every per-token price, and the+ // per-modality costs the total is made of.+ '$ai_max_tokens',+ '$ai_total_tokens',+ '$ai_total_input_tokens',+ '$ai_total_output_tokens',+ '$ai_text_input_tokens',+ '$ai_text_output_tokens',+ '$ai_audio_input_tokens',+ '$ai_audio_output_tokens',+ '$ai_image_input_tokens',+ '$ai_image_output_tokens',+ '$ai_video_input_tokens',+ '$ai_video_output_tokens',+ '$ai_cache_creation_input_tokens',+ '$ai_cache_creation_1h_input_tokens',+ '$ai_cache_creation_5m_input_tokens',+ '$ai_cache_read_audio_tokens',+ '$ai_audio_cost_usd',+ '$ai_image_cost_usd',+ '$ai_video_cost_usd',+ '$ai_web_search_cost_usd',+ '$ai_web_search_count',+ '$ai_web_search_price',+ '$ai_request_cost_usd',+ '$ai_request_count',+ '$ai_request_price',+ '$ai_input_token_price',+ '$ai_output_token_price',+ '$ai_cache_read_token_price',+ '$ai_cache_write_token_price',+ '$ai_cache_write_1h_token_price',+ '$ai_cache_read_cost_usd',+ '$ai_cache_creation_cost_usd',+ '$ai_billable',+ '$ai_cost_passthrough',+ '$ai_cost_model_source',+ '$ai_cost_model_provider',+ '$ai_model_cost_used',+ '$ai_cache_reporting_exclusive',+ '$ai_tokens_source',])/** Trace-level fields that carry conversation content rather than metadata. */-const SUMMARY_PREVIEWED_TRACE_FIELDS = new Set(['inputState', 'outputState'])+const SUMMARY_OMITTED_TRACE_FIELDS = new Set(['inputState', 'outputState'])++/**+ * Names of the content fields a summary leaves out, reported in place of their+ * values. It sits beside `properties` rather than inside it, so it cannot+ * collide with a captured property of the same name.+ */+const SUMMARY_OMITTED_KEYS_FIELD = '_summaryOmittedKeys'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.'+ 'Event content is omitted; only the names of the omitted properties are listed. Re-run this tool with detail: "full" for prompts, outputs, error messages, and feedback text, 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))@@ -119,10 +190,6 @@ 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)-}-function serializedLength(value: unknown): number {try {return JSON.stringify(value).length@@ -152,21 +219,6 @@ function encodedStringLength(value: string): number {return serializedLength(value)}-/**- * Assign a key without triggering the inherited `__proto__` setter. Trace- * payloads are arbitrary parsed JSON and can legitimately carry an own- * `__proto__` key (e.g. a tool payload being debugged); a plain `out[key] = v`- * would set the clone's prototype instead of creating an own property and drop- * the value from serialization.- */-function assignKey(target: Record<string, unknown>, key: string, value: unknown): void {- if (key === '__proto__') {- Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })- } else {- target[key] = value- }-}-function truncateString(value: string, budget: number): string {const cap = Math.max(0, budget)if (value.length <= PER_VALUE_CHAR_LIMIT && encodedStringLength(value) <= cap) {@@ -289,16 +341,12 @@ function fitToEncodedBudget<T>(return measure(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)+ return event}const out: Record<string, unknown> = {}+ const omitted: string[] = []for (const [key, value] of Object.entries(event)) {if (key !== 'properties' || !isRecord(value)) {assignKey(out, key, value)@@ -306,29 +354,37 @@ function summarizeEvent(event: unknown): unknown {}const properties: Record<string, unknown> = {}for (const [propertyKey, propertyValue] of Object.entries(value)) {- assignKey(- properties,- propertyKey,- SUMMARY_METADATA_PROPERTIES.has(propertyKey) ? propertyValue : previewValue(propertyValue)- )+ if (SUMMARY_METADATA_PROPERTIES.has(propertyKey)) {+ assignKey(properties, propertyKey, propertyValue)+ } else {+ omitted.push(propertyKey)+ }}assignKey(out, 'properties', properties)}+ if (omitted.length > 0) {+ assignKey(out, SUMMARY_OMITTED_KEYS_FIELD, omitted)+ }return out}-/** Preview the trace-level fields that carry conversation content. */+/** Leave out the trace-level fields that carry conversation content. */function summarizeTraceFields(fields: Record<string, unknown>): void {- for (const key of SUMMARY_PREVIEWED_TRACE_FIELDS) {+ const omitted: string[] = []+ for (const key of SUMMARY_OMITTED_TRACE_FIELDS) {if (key in fields) {- assignKey(fields, key, previewValue(fields[key]))+ delete fields[key]+ omitted.push(key)}}+ if (omitted.length > 0) {+ assignKey(fields, SUMMARY_OMITTED_KEYS_FIELD, omitted)+ }assignKey(fields, '_detail', { mode: 'summary', note: SUMMARY_NOTE })}/**- * Compact a single trace to fit `budget` characters, previewing event content+ * Compact a single trace to fit `budget` characters, dropping 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@@ -389,7 +445,7 @@ function compactTraceWithin(trace: Record<string, unknown>, budget: number, detaif (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.'+ ? 'Re-run with detail: "summary" for metadata alone. 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,diff --git a/services/mcp/src/lib/trace-property-allowlist.generated.ts b/services/mcp/src/lib/trace-property-allowlist.generated.tsnew file mode 100644index 000000000000..b78b181a8d94--- /dev/null+++ b/services/mcp/src/lib/trace-property-allowlist.generated.ts@@ -0,0 +1,137 @@+// THIS FILE IS AUTOGENERATED from posthog/taxonomy/taxonomy.py. DO NOT EDIT+// MANUALLY. To update: pnpm run taxonomy:build+//+// Every other property of a trace event is withheld from MCP responses — see+// services/mcp/src/lib/trace-redaction.ts.++export const AI_TAXONOMY_EVENT_PROPERTIES = [+ '$ai_agent_name',+ '$ai_audio_cost_usd',+ '$ai_audio_input_tokens',+ '$ai_audio_output_tokens',+ '$ai_base_url',+ '$ai_billable',+ '$ai_blob_bytes',+ '$ai_blob_count',+ '$ai_cache_creation_1h_input_tokens',+ '$ai_cache_creation_5m_input_tokens',+ '$ai_cache_creation_input_tokens',+ '$ai_cache_read_audio_tokens',+ '$ai_cache_read_input_tokens',+ '$ai_cache_read_token_price',+ '$ai_cache_reporting_exclusive',+ '$ai_cache_write_1h_token_price',+ '$ai_cache_write_token_price',+ '$ai_cost_model_provider',+ '$ai_cost_model_source',+ '$ai_cost_passthrough',+ '$ai_error',+ '$ai_error_normalized',+ '$ai_error_type',+ '$ai_eval_source',+ '$ai_evaluation_allows_na',+ '$ai_evaluation_applicable',+ '$ai_evaluation_id',+ '$ai_evaluation_key_id',+ '$ai_evaluation_key_type',+ '$ai_evaluation_model',+ '$ai_evaluation_name',+ '$ai_evaluation_provider',+ '$ai_evaluation_reasoning',+ '$ai_evaluation_result',+ '$ai_evaluation_runtime',+ '$ai_evaluation_start_time',+ '$ai_evaluation_type',+ '$ai_expected',+ '$ai_experiment_id',+ '$ai_experiment_item_id',+ '$ai_experiment_item_name',+ '$ai_experiment_name',+ '$ai_feedback_text',+ '$ai_framework',+ '$ai_git_branch',+ '$ai_git_repo',+ '$ai_http_status',+ '$ai_image_cost_usd',+ '$ai_image_input_tokens',+ '$ai_image_output_tokens',+ '$ai_ingestion_source',+ '$ai_input',+ '$ai_input_cost_usd',+ '$ai_input_state',+ '$ai_input_token_price',+ '$ai_input_tokens',+ '$ai_is_error',+ '$ai_latency',+ '$ai_lib',+ '$ai_lib_version',+ '$ai_max_tokens',+ '$ai_metric_name',+ '$ai_metric_value',+ '$ai_metric_version',+ '$ai_model',+ '$ai_model_cost_used',+ '$ai_model_parameters',+ '$ai_output',+ '$ai_output_choices',+ '$ai_output_cost_usd',+ '$ai_output_state',+ '$ai_output_token_price',+ '$ai_output_tokens',+ '$ai_parent_id',+ '$ai_project_name',+ '$ai_prompt_name',+ '$ai_prompt_version',+ '$ai_prompt_version_id',+ '$ai_provider',+ '$ai_reasoning',+ '$ai_reasoning_tokens',+ '$ai_request_cost_usd',+ '$ai_request_count',+ '$ai_request_price',+ '$ai_request_url',+ '$ai_result_type',+ '$ai_score',+ '$ai_score_max',+ '$ai_score_min',+ '$ai_session_id',+ '$ai_span_id',+ '$ai_span_name',+ '$ai_span_type',+ '$ai_status',+ '$ai_stop_reason',+ '$ai_stream',+ '$ai_tag_count',+ '$ai_tag_reasoning',+ '$ai_tagger_id',+ '$ai_tagger_key_id',+ '$ai_tagger_key_type',+ '$ai_tagger_name',+ '$ai_tagger_start_time',+ '$ai_tags',+ '$ai_target_event_id',+ '$ai_target_event_type',+ '$ai_target_id',+ '$ai_target_type',+ '$ai_temperature',+ '$ai_text_input_tokens',+ '$ai_text_output_tokens',+ '$ai_time_to_first_token',+ '$ai_tokens_source',+ '$ai_tool_call_count',+ '$ai_tools',+ '$ai_tools_called',+ '$ai_total_cost_usd',+ '$ai_total_input_tokens',+ '$ai_total_output_tokens',+ '$ai_total_tokens',+ '$ai_trace_id',+ '$ai_trace_name',+ '$ai_user_prompt',+ '$ai_video_cost_usd',+ '$ai_video_input_tokens',+ '$ai_video_output_tokens',+ '$ai_web_search_cost_usd',+ '$ai_web_search_count',+ '$ai_web_search_price',+] as constdiff --git a/services/mcp/src/lib/trace-redaction.ts b/services/mcp/src/lib/trace-redaction.tsnew file mode 100644index 000000000000..ac3d60e0211c--- /dev/null+++ b/services/mcp/src/lib/trace-redaction.ts@@ -0,0 +1,172 @@+/**+ * Withholds everything but the AI payload from `query-llm-trace` and+ * `query-llm-traces-list` responses.+ *+ * An event's `properties` bag is caller-controlled and open-ended: next to the+ * prompts and costs an agent asks for, it carries whatever the calling+ * application and its framework put there, including credentials and user+ * identity. A rule that names what to drop always trails the data, so this is+ * an allowlist. A withheld property is reported by name, so an agent can see+ * that it exists and read it in PostHog.+ *+ * This is a client-boundary safeguard on these two tools only. Stored events,+ * the PostHog UI, and property filters keep the complete bag, so a query can+ * still filter on a property it cannot read back.+ */++import { assignKey, isRecord } from '@/lib/plain-object'+import { AI_TAXONOMY_EVENT_PROPERTIES } from '@/lib/trace-property-allowlist.generated'++const RETAINED_AI_PROPERTIES = new Set<string>(AI_TAXONOMY_EVENT_PROPERTIES)++/**+ * `$ai_*` names first-party code writes that `taxonomy.py` does not describe, so+ * the generator cannot emit them. `$ai_generation_id` identifies a generation+ * node, which both tool descriptions promise. The LLM gateway writes the other+ * three onto generation events, and the personal-spend report reads the two+ * cache costs back, so withholding them would hide part of a trace's spend while+ * `$ai_total_cost_usd` still arrived. Each is a scalar or a short label.+ */+const RETAINED_UNDESCRIBED_AI_PROPERTIES = new Set([+ '$ai_generation_id',+ '$ai_cache_read_cost_usd',+ '$ai_cache_creation_cost_usd',+ '$ai_effort',+])++/** Non-`$ai_*` properties kept so a trace stays navigable and attributable. */+const RETAINED_NAVIGATION_PROPERTIES = new Set(['$session_id', '$lib', '$lib_version'])++/**+ * Endpoint properties kept without their query string. A provider URL routinely+ * carries the API key as a query parameter.+ */+const SANITIZED_URL_PROPERTIES = new Set(['$ai_base_url', '$ai_request_url'])++/**+ * Names of the properties withheld from a bag, reported in place of their+ * values. It sits beside `properties` rather than inside it, so it cannot+ * collide with a captured property of the same name.+ */+const REDACTED_KEYS_FIELD = '_redactedKeys'++/**+ * Reduce an endpoint property to its origin and path, or withhold it. Only an+ * absolute `http:` or `https:` URL has an origin and a path to keep. `URL`+ * accepts an opaque scheme too, and there the whole value sits in the path: a+ * `data:` URL parses, so `origin` is the string `"null"` and `pathname` is the+ * payload, credential and all. Anything else is withheld rather than guessed at.+ */+function sanitizeUrl(value: unknown): string | undefined {+ if (typeof value !== 'string') {+ return undefined+ }+ let url: URL+ try {+ url = new URL(value)+ } catch {+ return undefined+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ return undefined+ }+ return `${url.origin}${url.pathname}`+}++function isRetained(key: string): boolean {+ return (+ RETAINED_AI_PROPERTIES.has(key) ||+ RETAINED_UNDESCRIBED_AI_PROPERTIES.has(key) ||+ RETAINED_NAVIGATION_PROPERTIES.has(key)+ )+}++/**+ * Empty a property bag that is not a record. The filter decides key by key, so an+ * array or a string gives it no keys to decide on. Returning such a bag unchanged+ * would pass every value in it to the client, so it is emptied instead, and the+ * field itself is named as withheld.+ */+function emptiedBag(owner: Record<string, unknown>): Record<string, unknown> {+ return { ...owner, properties: {}, [REDACTED_KEYS_FIELD]: ['properties'] }+}++/**+ * Filter an event property bag. Returns the event unchanged when the bag holds+ * nothing to withhold or sanitize, which is the common shape of an SDK trace.+ */+function redactEventBag(event: Record<string, unknown>): Record<string, unknown> {+ if (!('properties' in event)) {+ return event+ }+ const properties = event.properties+ if (!isRecord(properties)) {+ return emptiedBag(event)+ }+ const keys = Object.keys(properties)+ if (keys.every((key) => isRetained(key) && !SANITIZED_URL_PROPERTIES.has(key))) {+ return event+ }+ const retained: Record<string, unknown> = {}+ const withheld: string[] = []+ for (const key of keys) {+ if (SANITIZED_URL_PROPERTIES.has(key)) {+ const sanitized = sanitizeUrl(properties[key])+ if (sanitized === undefined) {+ withheld.push(key)+ } else {+ assignKey(retained, key, sanitized)+ }+ } else if (isRetained(key)) {+ assignKey(retained, key, properties[key])+ } else {+ withheld.push(key)+ }+ }+ return {+ ...event,+ properties: retained,+ ...(withheld.length > 0 ? { [REDACTED_KEYS_FIELD]: withheld } : {}),+ }+}++/**+ * Withhold every person property value. The allowlist above describes an AI+ * event, and a person bag is not one: its names come from `$set`, so a person+ * carrying `$ai_model` carries whatever the application chose to write there.+ * `uuid` and `distinct_id` sit outside the bag, so the person stays navigable.+ */+function redactPersonBag(person: Record<string, unknown>): Record<string, unknown> {+ if (!('properties' in person)) {+ return person+ }+ const properties = person.properties+ if (!isRecord(properties)) {+ return emptiedBag(person)+ }+ const withheld = Object.keys(properties)+ if (withheld.length === 0) {+ return person+ }+ return { ...person, properties: {}, [REDACTED_KEYS_FIELD]: withheld }+}++/** Redact one trace: every event bag, and the person bag attached to the trace. */+export function redactTrace(trace: unknown): unknown {+ if (!isRecord(trace)) {+ return trace+ }+ const out: Record<string, unknown> = { ...trace }+ if (Array.isArray(trace.events)) {+ out.events = trace.events.map((event) => (isRecord(event) ? redactEventBag(event) : event))+ }+ if (isRecord(trace.person)) {+ out.person = redactPersonBag(trace.person)+ }+ return out+}++/** Redact the `results` array of a trace query, before it is compacted. */+export function redactTraceResults(results: unknown): unknown {+ return Array.isArray(results) ? results.map(redactTrace) : results+}diff --git a/services/mcp/src/tools/query-wrapper-factory.ts b/services/mcp/src/tools/query-wrapper-factory.tsindex 572dfd57cfcc..d9c8274b7218 100644--- a/services/mcp/src/tools/query-wrapper-factory.ts+++ b/services/mcp/src/tools/query-wrapper-factory.ts@@ -1,6 +1,7 @@import { z } from 'zod'import { type TraceDetail, compactTraceResponse } from '@/lib/trace-compaction'+import { redactTraceResults } from '@/lib/trace-redaction'import {POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,POSTHOG_META_KEY,@@ -10,14 +11,16 @@ import {} from '@/tools/types'// LLM trace query kinds return every event with its full properties (entire-// prompts, completions, tool payloads). Their results are bounded before being-// returned so a single huge trace can't blow the caller's context window.+// prompts, completions, tool payloads, and whatever else the calling application+// attached). Their results are redacted down to the AI payload, then bounded, so+// a response carries neither a credential nor enough volume to 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.'+ 'How much of each event to return. "full" (default) returns the retained event properties, subject to response size limits. Set "summary" to browse trace and event metadata (IDs, timestamps, model, latency, tokens, cost, tools called, errors); prompts, outputs, and other content are left out and only their names are listed.'/*** Add the `detail` control to the trace wrappers only. The field is a tool-level@@ -224,14 +227,17 @@ export function createQueryWrapper<T extends ZodObjectAny>(config: QueryWrapperC}const data = await context.api.query({ projectId }).runQuery({ query })- const shouldSurfaceFormatted = effectiveOutputFormat !== 'json' && data.formatted_results+ // The backend renders `formatted_results` from the unredacted results, and+ // some clients read that string in preference to the structured payload, so+ // a trace response never carries it.+ const shouldSurfaceFormatted = !isTraceQuery && effectiveOutputFormat !== 'json' && data.formatted_results// Include `query` in the payload so UI apps (TrendsVisualizer, LifecycleVisualizer)// can honor query-level filters like `lifecycleFilter.toggledLifecycles` and// `trendsFilter.display`.const response = {_posthogUrl: buildInsightUrl('InsightVizNode', query, baseUrl, config.urlPrefix),query,- results: data.results,+ results: isTraceQuery ? redactTraceResults(data.results) : data.results,...(data.warnings ? { warnings: data.warnings } : {}),}if (isTraceQuery) {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.jsonindex c5f01783f774..86ea2f6e8a39 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@@ -39,7 +39,7 @@},"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.",+ "description": "How much of each event to return. \"full\" (default) returns the retained event properties, subject to response size limits. Set \"summary\" to browse trace and event metadata (IDs, timestamps, model, latency, tokens, cost, tools called, errors); prompts, outputs, and other content are left out and only their names are listed.","enum": ["summary", "full"],"type": "string"},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.jsonindex 061cf0f24046..8a7bc9b68b41 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@@ -39,7 +39,7 @@},"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.",+ "description": "How much of each event to return. \"full\" (default) returns the retained event properties, subject to response size limits. Set \"summary\" to browse trace and event metadata (IDs, timestamps, model, latency, tokens, cost, tools called, errors); prompts, outputs, and other content are left out and only their names are listed.","enum": ["summary", "full"],"type": "string"},diff --git a/services/mcp/tests/unit/query-wrapper-factory.test.ts b/services/mcp/tests/unit/query-wrapper-factory.test.tsindex 33689866c120..b9c4d262e4db 100644--- a/services/mcp/tests/unit/query-wrapper-factory.test.ts+++ b/services/mcp/tests/unit/query-wrapper-factory.test.ts@@ -416,7 +416,7 @@ describe('createQueryWrapper filterTestAccounts project default', () => {})})-describe('createQueryWrapper trace compaction', () => {+describe('createQueryWrapper trace redaction and compaction', () => {const schema = z.object({ kind: z.string() })function contextWithResults(results: unknown, warnings?: string[]): Context {@@ -484,12 +484,12 @@ describe('createQueryWrapper trace compaction', () => {})- it.each(['TraceQuery', 'TracesQuery'])('%s preserves full content unless summary is requested', async (kind) => {+ it.each(['TraceQuery', 'TracesQuery'])('%s preserves the AI payload 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) } }],+ events: [{ properties: { $ai_input: 'x'.repeat(5_000), $ai_model: 'gpt-4' } }],}const byDefault = (await tool.handler(contextWithResults([trace]), tool.schema.parse({ kind }))) as any@@ -505,8 +505,53 @@ describe('createQueryWrapper trace compaction', () => {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)+ expect(summary.results[0].inputState).toBeUndefined()+ expect(summary.results[0].events[0].properties.$ai_model).toBe('gpt-4')+ expect(summary.results[0].events[0].properties.$ai_input).toBeUndefined()+ })++ it.each([+ ['TraceQuery', 'full'],+ ['TraceQuery', 'summary'],+ ['TracesQuery', 'full'],+ ['TracesQuery', 'summary'],+ ] as const)('%s at %s detail returns no property outside the allowlist', async (kind, detail) => {+ const secret = 'sk-test-INVENTEDCREDENTIAL0000'+ const trace = {+ id: 'trace-1',+ person: { uuid: 'p1', distinct_id: 'd1', properties: { email: '[email protected]' } },+ events: [{ properties: { $ai_model: 'gpt-4', authorization_header: secret } }],+ }+ const context = contextWithResults([trace])+ const tool = createQueryWrapper({ name: 'test', schema, kind, outputFormat: 'optimized' })()++ const result = (await tool.handler(context, tool.schema.parse({ kind, detail }))) as any++ const serialized = JSON.stringify(result)+ expect(serialized).not.toContain(secret)+ expect(serialized).not.toContain('[email protected]')+ expect(result.results[0].events[0]._redactedKeys).toEqual(['authorization_header'])+ })++ it('never surfaces the formatted string, which the backend renders before redaction', async () => {+ const secret = 'sk-test-INVENTEDCREDENTIAL0000'+ const context = {+ api: {+ query: vi.fn().mockReturnValue({+ runQuery: vi.fn().mockResolvedValue({+ results: [{ id: 'trace-1', events: [] }],+ formatted_results: `api_key: ${secret}`,+ }),+ }),+ 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', outputFormat: 'optimized' })()++ const result = (await tool.handler(context, fullDetailParams)) as any++ expect(result[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]).toBeUndefined()})it('strips detail from the trace query body, which the backend rejects unknown fields on', async () => {diff --git a/services/mcp/tests/unit/trace-compaction.test.ts b/services/mcp/tests/unit/trace-compaction.test.tsindex 9b8878cd4d44..b227a381f5f1 100644--- a/services/mcp/tests/unit/trace-compaction.test.ts+++ b/services/mcp/tests/unit/trace-compaction.test.ts@@ -138,9 +138,19 @@ describe('compactTrace summary detail', () => {createdAt: '2026-09-02T11:30:23Z',properties: {$ai_model: 'gpt-4',+ $ai_temperature: 0.7,+ $ai_stream: false,+ $ai_effort: 'high',$ai_latency: 1.5,+ $ai_time_to_first_token: 0.3,+ $ai_request_cost_usd: 0.02,+ $ai_total_tokens: 1_200,+ $ai_stop_reason: 'end_turn',$ai_tools_called: ['search'],- $ai_is_error: false,+ $ai_is_error: true,+ $ai_http_status: 429,+ $ai_error: 'rate limited while sending: Why did the checkout funnel drop?',+ $ai_feedback_text: 'It never answered why the checkout funnel dropped.',$ai_input: 'i'.repeat(5_000),$ai_output_choices: 'o'.repeat(5_000),custom_payload: 'c'.repeat(5_000),@@ -149,27 +159,52 @@ describe('compactTrace summary detail', () => {],}- it('keeps navigation metadata verbatim and previews everything else', () => {+ it('keeps navigation metadata verbatim and leaves out everything else', () => {const result = compactTrace(trace, MAX_SUMMARY_CHARS, 'summary') as anyconst properties = result.events[0].propertiesexpect(properties.$ai_model).toBe('gpt-4')+ // How the model was called is a scalar setting, not conversation+ // content, so a survey of it does not have to fall back to full detail.+ expect(properties.$ai_temperature).toBe(0.7)+ expect(properties.$ai_stream).toBe(false)+ expect(properties.$ai_effort).toBe('high')expect(properties.$ai_latency).toBe(1.5)+ // Cost and latency are what a summary survey is for, so the scalars it+ // reads stay whole rather than being omitted as content.+ expect(properties.$ai_time_to_first_token).toBe(0.3)+ expect(properties.$ai_request_cost_usd).toBe(0.02)+ expect(properties.$ai_total_tokens).toBe(1_200)+ expect(properties.$ai_stop_reason).toBe('end_turn')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(properties.$ai_is_error).toBe(true)+ expect(properties.$ai_http_status).toBe(429)+ expect(properties.$ai_input).toBeUndefined()+ expect(properties.$ai_output_choices).toBeUndefined()+ expect(properties.custom_payload).toBeUndefined()+ // A provider error and a feedback note are free text, and an error+ // routinely quotes the prompt back, so a summary keeps the flags that+ // locate a failed event and drops the words.+ expect(properties.$ai_error).toBeUndefined()+ expect(properties.$ai_feedback_text).toBeUndefined()+ expect(JSON.stringify(result)).not.toContain('checkout funnel')+ expect(result.events[0]._summaryOmittedKeys).toEqual([+ '$ai_error',+ '$ai_feedback_text',+ '$ai_input',+ '$ai_output_choices',+ 'custom_payload',+ ])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.+ it('carries no fragment of a prompt, however it is structured', () => {+ // A summary is for a cost or latency survey. Neither a plain string nor a+ // message array may leak a readable piece of the conversation into one.const messages = [- { role: 'system', content: 's'.repeat(2_000) },+ { role: 'system', content: 'You are a helpful assistant.' },{ role: 'user', content: 'Why did the checkout funnel drop?' },]@@ -179,21 +214,15 @@ describe('compactTrace summary detail', () => {'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')+ expect(JSON.stringify(result)).not.toContain('checkout funnel')+ expect(result.events[0]._summaryOmittedKeys).toEqual(['$ai_input'])})- 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+ it('leaves out trace-level input and output state', () => {+ const result = compactTrace(trace, MAX_SUMMARY_CHARS, 'summary') as any- expect(result.events[0].properties.$ai_input).toBe(content)+ expect(result.inputState).toBeUndefined()+ expect(result._summaryOmittedKeys).toEqual(['inputState'])})it('returns far less than the same trace at full detail', () => {diff --git a/services/mcp/tests/unit/trace-redaction.test.ts b/services/mcp/tests/unit/trace-redaction.test.tsnew file mode 100644index 000000000000..bec14516ea92--- /dev/null+++ b/services/mcp/tests/unit/trace-redaction.test.ts@@ -0,0 +1,220 @@+import { describe, expect, it } from 'vitest'++import { SUMMARY_METADATA_PROPERTIES, compactTraceResponse } from '@/lib/trace-compaction'+import { redactTrace, redactTraceResults } from '@/lib/trace-redaction'++// Invented values, one per property class the redactor must withhold. Each one+// is a distinctive string, so a test can assert it appears nowhere in the+// serialized response rather than checking one key at a time.+const SECRETS = {+ credential: 'sk-test-INVENTEDCREDENTIAL0000',+ authState: 'INVENTEDAUTHSTATE1111',+ header: 'INVENTEDCOOKIEHEADER2222',+ identity: '[email protected]',+ location: 'INVENTEDCITY3333',+ permissions: 'INVENTEDPERMISSION4444',+ budget: 'INVENTEDBUDGET5555',+ custom: 'INVENTEDCUSTOM6666',+ personSet: 'INVENTEDPERSONSET7777',+}++function traceWithSecrets(): Record<string, unknown> {+ return {+ id: 'trace-1',+ totalCost: 0.42,+ inputState: { messages: [{ role: 'user', content: 'Why did checkout drop?' }] },+ person: {+ uuid: 'person-1',+ distinct_id: 'distinct-1',+ properties: {+ email: SECRETS.identity,+ $geoip_city_name: SECRETS.location,+ // Names the event allowlist retains. A person bag is written+ // with `$set`, so these hold whatever the application chose.+ $ai_model: SECRETS.personSet,+ $session_id: SECRETS.personSet,+ },+ },+ events: [+ {+ id: 'e1',+ event: '$ai_generation',+ createdAt: '2026-09-02T11:30:23Z',+ properties: {+ $ai_generation_id: 'generation-1',+ $ai_model: 'gpt-4',+ $ai_total_cost_usd: 0.42,+ $ai_cache_read_cost_usd: 0.01,+ $ai_input: [{ role: 'user', content: 'Why did checkout drop?' }],+ $ai_output_choices: [{ role: 'assistant', content: 'Payments timed out.' }],+ $session_id: 'session-1',+ api_key: SECRETS.credential,+ auth: { method: 'oauth', token: SECRETS.authState },+ request_headers: { cookie: SECRETS.header },+ user_email: SECRETS.identity,+ $geoip_city_name: SECRETS.location,+ permissions: [SECRETS.permissions],+ budget_remaining_usd: SECRETS.budget,+ prompt_version: SECRETS.custom,+ $ai_debug_data: { headers: { authorization: SECRETS.header } },+ },+ },+ ],+ }+}++function secretsIn(value: unknown): string[] {+ const serialized = JSON.stringify(value)+ return Object.entries(SECRETS)+ .filter(([, secret]) => serialized.includes(secret))+ .map(([name]) => name)+}++describe('trace redaction', () => {+ it('keeps the AI payload of an event', () => {+ const properties = (redactTrace(traceWithSecrets()) as any).events[0].properties++ expect(properties.$ai_model).toBe('gpt-4')+ expect(properties.$ai_total_cost_usd).toBe(0.42)+ // The gateway writes this one and `taxonomy.py` does not describe it, so+ // the generated allowlist alone would withhold part of the trace's spend.+ expect(properties.$ai_cache_read_cost_usd).toBe(0.01)+ expect(properties.$ai_input).toEqual([{ role: 'user', content: 'Why did checkout drop?' }])+ expect(properties.$ai_output_choices).toEqual([{ role: 'assistant', content: 'Payments timed out.' }])+ expect(properties.$session_id).toBe('session-1')+ })++ it('withholds every non-AI property value and reports its name instead', () => {+ const event = (redactTrace(traceWithSecrets()) as any).events[0]++ expect(secretsIn(event)).toEqual([])+ expect(event._redactedKeys).toEqual([+ 'api_key',+ 'auth',+ 'request_headers',+ 'user_email',+ '$geoip_city_name',+ 'permissions',+ 'budget_remaining_usd',+ 'prompt_version',+ '$ai_debug_data',+ ])+ })++ it('withholds every person property, including names the event allowlist keeps', () => {+ const person = (redactTrace(traceWithSecrets()) as any).person++ expect(person.uuid).toBe('person-1')+ expect(person.distinct_id).toBe('distinct-1')+ expect(secretsIn(person)).toEqual([])+ expect(person.properties).toEqual({})+ expect(person._redactedKeys).toEqual(['email', '$geoip_city_name', '$ai_model', '$session_id'])+ })++ it.each([+ ['a custom property in the $ai_ namespace', '$ai_authorization'],+ ['a property named like a taxonomy property', '$ai_model_secret'],+ ])('withholds %s, which the namespace does not reserve', (_label, key) => {+ const trace = { id: 't1', events: [{ id: 'e1', properties: { [key]: SECRETS.credential } }] }++ const event = (redactTrace(trace) as any).events[0]++ expect(secretsIn(event)).toEqual([])+ expect(event._redactedKeys).toEqual([key])+ })++ it.each([+ ['$ai_base_url', 'https://api.example.com/v1?api_key=sk-test-INVENTEDCREDENTIAL0000'],+ ['$ai_request_url', 'https://api.example.com/v1/messages#api_key=sk-test-INVENTEDCREDENTIAL0000'],+ ])('strips the query string from %s, where a key is often passed', (key, url) => {+ const trace = { id: 't1', events: [{ id: 'e1', properties: { [key]: url } }] }++ const properties = (redactTrace(trace) as any).events[0].properties++ expect(secretsIn(properties)).toEqual([])+ expect(properties[key]).toContain('https://api.example.com/v1')+ })++ it.each([+ ['a structured value', { url: `https://api.example.com/v1?api_key=${SECRETS.credential}` }],+ // `URL` accepts an opaque scheme, and there the whole value is the path,+ // so an endpoint built from it returns the credential it meant to strip.+ ['an opaque scheme', `data:text/plain,api_key=${SECRETS.credential}`],+ ['a value that is not an absolute URL', `api.example.com/v1?api_key=${SECRETS.credential}`],+ ])('withholds a URL property that is %s, having no endpoint to keep', (_label, value) => {+ const trace = { id: 't1', events: [{ id: 'e1', properties: { $ai_request_url: value } }] }++ const event = (redactTrace(trace) as any).events[0]++ expect(secretsIn(event)).toEqual([])+ expect(event._redactedKeys).toEqual(['$ai_request_url'])+ })++ it.each([+ ['an array', [{ authorization: SECRETS.credential }]],+ ['a string', SECRETS.credential],+ ])('empties an event property bag that arrives as %s', (_label, properties) => {+ const event = (redactTrace({ id: 't1', events: [{ id: 'e1', properties }] }) as any).events[0]++ expect(secretsIn(event)).toEqual([])+ expect(event.properties).toEqual({})+ expect(event._redactedKeys).toEqual(['properties'])+ })++ it('empties a person property bag that is not a record', () => {+ const trace = { id: 't1', person: { uuid: 'person-1', properties: [{ email: SECRETS.identity }] } }++ const person = (redactTrace(trace) as any).person++ expect(secretsIn(person)).toEqual([])+ expect(person.properties).toEqual({})+ expect(person._redactedKeys).toEqual(['properties'])+ })++ it('returns a bag that holds only retained properties unchanged', () => {+ const trace = { id: 't1', events: [{ id: 'e1', properties: { $ai_model: 'gpt-4' } }] }++ expect(redactTrace(trace)).toEqual(trace)+ })++ it('leaves a trace without a properties bag alone', () => {+ expect(redactTraceResults([{ id: 't1' }, 'not-a-trace'])).toEqual([{ id: 't1' }, 'not-a-trace'])+ expect(redactTraceResults(null)).toBeNull()+ })+})++describe('trace redaction through the response pipeline', () => {+ it.each(['full', 'summary'] as const)('withholds every secret at %s detail, for one trace and a list', (detail) => {+ const single = compactTraceResponse({ results: redactTraceResults([traceWithSecrets()]) }, detail)+ const list = compactTraceResponse(+ { results: redactTraceResults([traceWithSecrets(), { ...traceWithSecrets(), id: 'trace-2' }]) },+ detail+ )++ expect(secretsIn(single)).toEqual([])+ expect(secretsIn(list)).toEqual([])+ })++ it('keeps every property the summary metadata set names', () => {+ // The two modules hold separate lists, and redaction runs first. A name+ // the summary set has but redaction withholds is a dead entry: the field+ // vanishes from summary and nothing says so. A typo reads the same way.+ const properties = Object.fromEntries([...SUMMARY_METADATA_PROPERTIES].map((key, i) => [key, i]))++ const { results } = compactTraceResponse(+ { results: redactTraceResults([{ id: 't1', events: [{ id: 'e1', properties }] }]) },+ 'summary'+ ) as any+ const [trace] = results++ expect(trace.events[0].properties).toEqual(properties)+ expect(trace.events[0]._summaryOmittedKeys).toBeUndefined()+ expect(trace.events[0]._redactedKeys).toBeUndefined()+ })++ it.each(['full', 'summary'] as const)('keeps the generation identifier at %s detail', (detail) => {+ const { results } = compactTraceResponse({ results: redactTraceResults([traceWithSecrets()]) }, detail) as any++ expect(results[0].events[0].properties.$ai_generation_id).toBe('generation-1')+ })+})diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex 61f0c7cdcb76..5a59fc6e2051 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -285,6 +285,7 @@ DIFF_CHECKS: list[DiffCheck] = [*BUILD_TRIGGERS["build:taxonomy-json"],"bin/build-taxonomy-json.py","frontend/src/taxonomy/core-filter-definitions-by-group.json",+ "services/mcp/src/lib/trace-property-allowlist.generated.ts",],verify=["hogli", "build:taxonomy-json", "--check"],fix=["hogli", "build:taxonomy-json"],