Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(logs): integrate the logs viewer with PostHog AI (#93582)

Frank Hamand4d23916c78e2
diff --git a/products/logs/frontend/LogsAgentIntegration.tsx b/products/logs/frontend/LogsAgentIntegration.tsx
new file mode 100644
index 000000000000..1827f9ff78f7
--- /dev/null
+++ b/products/logs/frontend/LogsAgentIntegration.tsx
@@ -0,0 +1,48 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
+import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'
+
+import { useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+
+import { buildLogsAgentContext, LOGS_AGENT_HEADLINES, logsQueryToViewerFilters } from './logsAgentContext'
+import { LOGS_SCENE_VIEWER_ID, logsSceneLogic } from './logsSceneLogic'
+
+/**
+ * Scene-level PostHog AI integration for the logs viewer. Attaches the investigating-logs skill, the
+ * logs MCP tool catalog, and the live viewer filter state as agent context, and mirrors a query-logs
+ * tool call back onto the open viewer so the user sees the agent's query both in chat and on screen.
+ * Renders nothing.
+ */
+export function LogsAgentIntegration({ activeTabIsViewer }: { activeTabIsViewer: boolean }): null {
+ const { filters } = useValues(logsSceneLogic)
+ const { setFilters } = useActions(logsSceneLogic)
+
+ // Debounced so per-keystroke search edits don't re-serialize the filter state on every change.
+ const debouncedFilters = useDebouncedValue(filters, 500)
+
+ const contextItems = useMemo(() => buildLogsAgentContext(debouncedFilters), [debouncedFilters])
+
+ useSceneAgentPanel({
+ sceneKey: 'logs',
+ contextItems,
+ headlines: LOGS_AGENT_HEADLINES,
+ })
+
+ useMcpToolApplyBack({
+ tools: ['query-logs'],
+ targetKey: `logs-viewer:${LOGS_SCENE_VIEWER_ID}`,
+ // Only mirror onto the viewer while the user is looking at it, so a query the agent runs while
+ // the user is on the SQL or alerts tab does not silently rewrite the hidden viewer's filters.
+ active: activeTabIsViewer,
+ onApply: (_event, { innerInput }) => {
+ if (!innerInput) {
+ return
+ }
+ setFilters(logsQueryToViewerFilters(innerInput))
+ },
+ })
+
+ return null
+}
diff --git a/products/logs/frontend/LogsScene.tsx b/products/logs/frontend/LogsScene.tsx
index 35572b8b46a8..8d0ffee46fc8 100644
--- a/products/logs/frontend/LogsScene.tsx
+++ b/products/logs/frontend/LogsScene.tsx
@@ -24,6 +24,7 @@ import { LogsViewer } from 'products/logs/frontend/components/LogsViewer'
import { LogsViewerModal } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal'
import { logsEmptyState } from './emptyState/logsEmptyState'
+import { LogsAgentIntegration } from './LogsAgentIntegration'
import { LogsAnomalies } from './LogsAnomalies'
import { LOGS_SCENE_VIEWER_ID, LogsSceneActiveTab, logsSceneLogic } from './logsSceneLogic'
@@ -66,6 +67,7 @@ const LogsSceneTabbedContent = (): JSX.Element => {
return (
<>
+ <LogsAgentIntegration activeTabIsViewer={activeTab === 'viewer'} />
<SceneTitleSection
name={sceneConfigurations[Scene.Logs].name}
resourceType={{
diff --git a/products/logs/frontend/generated/agentContext.ts b/products/logs/frontend/generated/agentContext.ts
new file mode 100644
index 000000000000..565d4b10af7d
--- /dev/null
+++ b/products/logs/frontend/generated/agentContext.ts
@@ -0,0 +1,128 @@
+// AUTO-GENERATED by services/mcp/scripts/build-scene-tool-context.ts.
+// Regenerate with `hogli build:openapi`. Do not edit.
+//
+// Static agent-context payloads for scene-level PostHog AI integration: the enabled
+// MCP tool catalog (names + live descriptions) and embedded skill bodies, attached
+// as context by `useSceneAgentPanel` callers so the agent starts with everything it
+// needs instead of discovering tools and reading skills at run time.
+
+export interface McpToolSummary {
+ name: string
+ description: string
+}
+
+export interface EmbeddedSkill {
+ name: string
+ description: string
+ content: string
+}
+
+export const LOGS_MCP_TOOLS: McpToolSummary[] = [
+ {
+ name: 'logs-alerts-create',
+ description:
+ 'Create a threshold-based alert on log streams. The alert periodically counts log entries matching the given filters and fires when the count crosses the threshold. Maximum 20 alerts per project.',
+ },
+ {
+ name: 'logs-alerts-destinations-create',
+ description:
+ 'Attach a Slack, webhook, or Microsoft Teams notification destination to a log alert. Without a destination an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken, errored) atomically. The returned hog_function_ids identify the destination group.',
+ },
+ {
+ name: 'logs-alerts-destinations-delete-create',
+ description:
+ 'Remove a notification destination from a log alert by passing the hog_function_ids returned from logs-alerts-destinations-create. Destinations are deleted as one atomic group — partial deletion fails the call.',
+ },
+ {
+ name: 'logs-alerts-destroy',
+ description: 'Permanently delete a log alert configuration by ID.',
+ },
+ {
+ name: 'logs-alerts-events-list',
+ description:
+ 'List historical events for a log alert — fires, resolves, errors, enable/disable toggles, threshold changes. Use to evaluate how an existing alert has behaved (firing cadence, error rate, flap pattern) before tuning thresholds. Quiet no-op check rows are filtered out server-side. Optional `kind` query param narrows to a single event kind.',
+ },
+ {
+ name: 'logs-alerts-list',
+ description:
+ 'List log alert configurations in the current project, newest first. Returns alert name, state, threshold, filters, and scheduling details. Use this to review existing alerts before creating or modifying them.',
+ },
+ {
+ name: 'logs-alerts-partial-update',
+ description:
+ 'Update a log alert configuration by ID. Only the fields you provide are changed. Use this to adjust thresholds, filters, quiet hours, enable/disable alerts, or snooze them.',
+ },
+ {
+ name: 'logs-alerts-retrieve',
+ description:
+ 'Get a log alert configuration by ID. Returns full details including current state, threshold settings, filters, and scheduling information.',
+ },
+ {
+ name: 'logs-alerts-simulate-create',
+ description:
+ 'Run a draft alert configuration against historical logs and return per-bucket results from the full state machine — count, threshold_breached, state, notification (none/fire/resolve), reason. Use to validate threshold + N-of-M settings before creating an alert. Read-only; no alert records are written. Aim for fire_count between 0 and 3 over a `-7d` lookback for a healthy threshold.',
+ },
+ {
+ name: 'logs-anomalies-scan',
+ description:
+ "Run anomaly detection on demand over one service's log volume for a time window of up to 7 days. Learns per-severity baselines from up to 6 weeks of history and returns spike, drop, and silence issues plus per-severity learning status. Requires a serviceName (use logs-services-list or the resource attribute values tool to discover services). Experimental; synchronous and read only, so prefer windows of a few hours to a day. Per-bucket band evidence is omitted from the tool response to save tokens; the API endpoint returns it for charts.",
+ },
+ {
+ name: 'logs-attribute-values-list',
+ description:
+ 'List values for a specific log attribute key. Use to discover what values exist before building filters. Defaults to attribute_type "log" (log-level attributes). To get values for resource-level attributes (e.g. service.name, k8s.pod.name), you MUST explicitly pass attribute_type: "resource". Accepts optional serviceNames, dateRange, and filterGroup to narrow which logs are scanned.',
+ },
+ {
+ name: 'logs-attributes-list',
+ description:
+ 'List available log attribute names for filtering. Defaults to attribute_type "log" (log-level attributes). To search resource-level attributes (e.g. k8s.pod.name, k8s.namespace.name), you MUST explicitly pass attribute_type: "resource" — it will NOT return resource attributes unless you do. Accepts optional serviceNames, dateRange, and filterGroup to narrow which logs are scanned.',
+ },
+ {
+ name: 'logs-count',
+ description:
+ 'Return a scalar count of log entries matching a filter set. Use this as a cheap pre-flight before `query-logs` — if the count exceeds `query-logs`\'s max `limit` of 1000, narrow the filters before pulling rows.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- Before `query-logs`, to confirm the filter set returns a tractable number of rows. If the count is above `query-logs`\'s max `limit` of 1000, narrow the filters.\n- When the user asks "how many X logs are there?" and you don\'t need to see individual rows.\n- To check whether a filter combination matches anything at all before committing to a full query.\n\nTo find **when** the volume is concentrated within the window (rather than just the total), follow up with `logs-count-ranges` — it returns time-bucketed counts with explicit `date_from`/`date_to` per bucket so you can drill into a sub-range without reasoning about interval width.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the count. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for "now".\n\n## query.serviceNames\n\nFilter by service names. Unlike `query-logs`, this tool does NOT require `serviceNames` — an unfiltered count is cheap and often useful for sizing up a filter before narrowing.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.searchTerm\n\nFull-text search across log bodies.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n# Examples\n\n## Count errors in a service over the last day\n\n```json\n{\n "query": {\n "serviceNames": ["api-gateway"],\n "severityLevels": ["error", "fatal"],\n "dateRange": { "date_from": "-1d" }\n }\n}\n```\n\n## Confirm a k8s namespace is producing logs at all\n\n```json\n{\n "query": {\n "dateRange": { "date_from": "-1h" },\n "filterGroup": [\n { "key": "k8s.namespace.name", "operator": "exact", "type": "log_resource_attribute", "value": "payments" }\n ]\n }\n}\n```',
+ },
+ {
+ name: 'logs-count-ranges',
+ description:
+ 'Get adaptive-interval bucket counts for a filtered log stream. Returns a flat list of `{date_from, date_to, count}` buckets covering the requested window. Modeled on Elasticsearch\'s `auto_date_histogram` — caller specifies a target bucket count, the engine picks the interval.\n\nUse this to find **where the volume is concentrated** before pulling rows. Cheaper than `query-logs`, more agent-friendly than `logs-sparkline-query` (each bucket carries explicit `date_from`/`date_to` you can feed straight back as the next call\'s `dateRange` to drill in).\n\n# When to use this vs other tools\n\n- **`logs-count`** — total volume in a window. Scalar.\n- **`logs-count-ranges`** (this tool) — _when_ in the window the volume sits. Time-bucketed.\n- **`query-logs`** — pull individual log rows. Most expensive; only call after counts confirm the window is right-sized.\n\n# Recursion pattern (the main reason this tool exists)\n\nUse the response to narrow into a sub-range without reasoning about interval width:\n\n1. Call `logs-count-ranges` with the user\'s window (e.g. last 24h).\n2. Pick the bucket(s) of interest (densest, an obvious spike, an unexpectedly empty stretch).\n3. Call `logs-count-ranges` again with that bucket\'s `date_from` and `date_to` as the next `dateRange`.\n4. Repeat up to ~3–4 levels — stop when buckets are shorter than your precision goal (e.g. 1 minute).\n5. Once narrowed, call `query-logs` for the actual rows.\n\nThis is the same pattern Elasticsearch users follow with `auto_date_histogram`. Keep recursion shallow — every call is cheap individually but they multiply quickly.\n\n# Parameters\n\nAll parameters must be nested inside a `query` object.\n\n## query.dateRange\n\nWindow to bucket. Defaults to the last hour (`-1h`). Same format as `query-logs`.\n\n## query.targetBuckets\n\nApproximate bucket count. Defaults to **10**, max 100. The engine picks the interval adaptively from a fixed list (1/5/10s, 1/2/5/10/15/30/60/120/240/360/720/1440m) to land near this target — actual count may differ slightly. Empty buckets are dropped, so the response can have fewer rows than `targetBuckets`.\n\nPick a value based on what you\'re doing:\n\n- **10** (default) — overview, finding spikes, "is this concentrated or spread out?"\n- **20–30** — characterising a known busy window\n- **50+** — high-resolution drill-down, only when you know the window is small\n\n## query.severityLevels, query.serviceNames, query.searchTerm, query.filterGroup\n\nSame shape as `query-logs`. Applied **before** bucketing.\n\n# Response\n\n```json\n{\n "ranges": [\n { "date_from": "2026-04-26T00:00:00Z", "date_to": "2026-04-26T02:24:00Z", "count": 1024 },\n { "date_from": "2026-04-26T02:24:00Z", "date_to": "2026-04-26T04:48:00Z", "count": 47 }\n ],\n "interval": "2h"\n}\n```\n\n- `ranges` — buckets ordered by `date_from` ascending. **Empty buckets are omitted** — infer gaps by comparing each bucket\'s `date_to` to the next bucket\'s `date_from`.\n- `interval` — short-form duration of the chosen bucket width (`1s` / `5m` / `1h` / `1d`). Informational only — for follow-up queries, use the per-bucket `date_from`/`date_to`.\n\n# Examples\n\n## Find when errors spiked over the last day\n\n```json\n{\n "query": {\n "dateRange": { "date_from": "-1d" },\n "targetBuckets": 24,\n "serviceNames": ["api-gateway"],\n "severityLevels": ["error", "fatal"]\n }\n}\n```\n\n## Drill into the densest hour from a previous call\n\nAfter picking the densest bucket from the response above (say `{date_from: "2026-04-26T15:00:00Z", date_to: "2026-04-26T16:00:00Z", count: 894}`):\n\n```json\n{\n "query": {\n "dateRange": {\n "date_from": "2026-04-26T15:00:00Z",\n "date_to": "2026-04-26T16:00:00Z"\n },\n "targetBuckets": 12,\n "serviceNames": ["api-gateway"],\n "severityLevels": ["error", "fatal"]\n }\n}\n```\n\n# Reminders\n\n- Cap recursion at ~3–4 levels. If your bucket width drops below your precision goal (e.g. 1 minute), stop and call `query-logs`.\n- Empty windows return `{"ranges": [], "interval": "..."}` — that\'s not an error, it\'s "I asked, nothing matched."\n- Always include `serviceNames` or a resource attribute filter, just like `query-logs`. Don\'t bucket the entire team\'s log stream.',
+ },
+ {
+ name: 'logs-facet-values-create',
+ description:
+ 'Return per-value counts for a single facet — the distribution of a log dimension across a filter set, ordered by count descending. This is the cheap way to see the _shape_ of a log stream (e.g. "which services produce the errors?") without pulling raw rows.\n\nCounts are cross-filtered: every active filter is applied _except the faceted field\'s own filter_, so you see the full distribution rather than collapsing to your own selection. Faceting `service_name` with `serviceNames: ["api"]` still returns every service, not just `api`.\n\nAll parameters must be nested inside a `query` object. You must provide **exactly one** of `query.facetField` or `query.facetResourceAttribute` — not both, not neither.\n\n# When to use\n\n- To find how log volume is distributed across severity or service under a filter — e.g. "of the logs matching \'timeout\', which services emit them?" Facet `service_name` with `searchTerm: "timeout"`.\n- As the drill-down loop for an investigation: facet `service_name` filtered to `severity=error` → find the hot service → add it to `serviceNames` → facet a resource attribute like `k8s.pod.name` → find the bad pod. Each call is one cheap aggregation that narrows the search space before you pull raw rows with `query-logs`.\n- To confirm the severity mix in a window before committing to a query: facet `severity_text`.\n\n## Pick the right tool\n\n- Counts for an arbitrary **attribute** value (any log or resource attribute key) → use `logs-attribute-values-list`. It returns `{value, count}` for any key and is the general-purpose choice for attributes.\n- Per-service log/error counts and error rates with a sparkline → use `logs-services-create`.\n- Use **this** tool for `severity_text` / `service_name` distribution cross-filtered by the full query (severity + body `searchTerm` + `filterGroup`) — the one thing the tools above can\'t do.\n\n# Parameters\n\n## query.facetField\n\nTop-level column to facet on: `severity_text` or `service_name`. Provide this OR `facetResourceAttribute`, not both. Counts are grouped on the raw logs table with all _other_ filters applied — so this path honors `severityLevels`, `serviceNames`, `searchTerm`, and `filterGroup`.\n\n## query.facetResourceAttribute\n\nResource attribute key to facet on, e.g. `k8s.namespace.name`, `k8s.pod.name`, `host.name`. Provide this OR `facetField`, not both.\n\n**Limitation:** this path is served from a pre-aggregated rollup that has no severity or body dimension. It honors only `serviceNames` and other resource-attribute filters — `severityLevels`, `searchTerm`, and log-attribute filters are **ignored**. If you need those applied, facet a column instead, or narrow with `logs-attribute-values-list`.\n\n## query.facetSearch\n\nCase-insensitive substring match over the faceted field\'s _own_ values (e.g. return only service names containing `kafka`). Distinct from `searchTerm`, which searches log bodies. Use it to search past the 100-value result cap.\n\n## query.dateRange\n\nDate range for the counts. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for "now".\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels. Ignored when faceting on `severity_text` (that field\'s own filter is excluded) and when faceting a resource attribute (rollup has no severity dimension).\n\n## query.serviceNames\n\nFilter by service names. Ignored when faceting on `service_name` (that field\'s own filter is excluded).\n\n## query.searchTerm\n\nFull-text search across log bodies. Ignored when faceting a resource attribute.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n# Examples\n\n## Severity distribution in the last hour\n\n```json\n{\n "query": {\n "facetField": "severity_text",\n "dateRange": { "date_from": "-1h" }\n }\n}\n```\n\n## Which services produce errors over the last day\n\n```json\n{\n "query": {\n "facetField": "service_name",\n "severityLevels": ["error", "fatal"],\n "dateRange": { "date_from": "-1d" }\n }\n}\n```\n\n## Which pods a service\'s logs come from\n\n```json\n{\n "query": {\n "facetResourceAttribute": "k8s.pod.name",\n "serviceNames": ["checkout"],\n "dateRange": { "date_from": "-6h" }\n }\n}\n```\n\n## Which services emit a specific error message\n\n```json\n{\n "query": {\n "facetField": "service_name",\n "searchTerm": "connection reset",\n "dateRange": { "date_from": "-1d" }\n }\n}\n```',
+ },
+ {
+ name: 'logs-patterns',
+ description:
+ 'Mine recurring log templates ("patterns") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what\'s new or dominant during an incident window: mine with `severityLevels: ["error", "fatal"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern\'s lines, pre-validated against the raw bodies of the pattern\'s own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern\'s raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ "key": "message", "value": "<match_regex>", "operator": "regex", "type": "log" }`\n- Else if `match_literal` is set: `{ "key": "message", "value": "<match_literal>", "operator": "icontains", "type": "log" }`\n\nAlso pass the pattern\'s `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for "now".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service\'s templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ "query": { "dateRange": { "date_from": "-1h" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n "query": {\n "severityLevels": ["error", "fatal"],\n "dateRange": { "date_from": "2024-01-15T09:00:00Z", "date_to": "2024-01-15T11:00:00Z" }\n }\n}\n```\n\n## Mine one service\'s logs around a keyword\n\n```json\n{\n "query": {\n "serviceNames": ["checkout"],\n "searchTerm": "payment",\n "dateRange": { "date_from": "-6h" }\n }\n}\n```',
+ },
+ {
+ name: 'logs-patterns-diff',
+ description:
+ 'Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — "what is different about now vs. before it broke" in one round trip, instead of mining two windows yourself and hand-matching templates.\n\nAll parameters must be nested inside a `query` object, with an optional sibling `baselineDateRange`.\n\n# When to use\n\n- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.\n- **Explain a spike:** when a count or sparkline shows a spike (e.g. from `logs-count-ranges`), set `query.dateRange` to the spike window and `baselineDateRange` to the window just before it — the top `new` and `rate_shift` entries are the explanation. This is one call; do not mine the two windows separately and diff them yourself.\n- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.\n- **"What changed this week?"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.\n\n## Pick the right tool\n\n- Just summarize one window\'s content → `logs-patterns`.\n- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).\n- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.\n\n# Reading the response\n\nEntries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.\n\n- `classification` — trust the labels; the thresholds already handle sampling honesty:\n - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.\n - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.\n - `unchanged` means "no confident claim", not "provably identical".\n- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.\n- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern\'s services/severities).\n- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn\'t exist last week) makes everything look new.\n- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.\n\nTemplate identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.\n\n# Parameters\n\n## query.dateRange\n\nThe current (foreground) window — the period you are investigating. Same format as `logs-patterns`.\n\n## baselineDateRange\n\nOptional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.\n\n## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup\n\nSame as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.\n\n# Examples\n\n## What changed during the incident vs. just before it\n\n```json\n{\n "query": {\n "dateRange": { "date_from": "2026-07-07T09:30:00Z", "date_to": "2026-07-07T10:30:00Z" },\n "serviceNames": ["checkout"]\n },\n "baselineDateRange": { "date_from": "2026-07-07T08:00:00Z", "date_to": "2026-07-07T09:00:00Z" }\n}\n```\n\n## What is new or different today vs. the same time last week\n\n```json\n{ "query": { "dateRange": { "date_from": "-1d" } } }\n```\n\n## Did the deploy change what the service logs?\n\n```json\n{\n "query": {\n "dateRange": { "date_from": "2026-07-07T14:00:00Z" },\n "serviceNames": ["api"]\n },\n "baselineDateRange": { "date_from": "2026-07-07T10:00:00Z", "date_to": "2026-07-07T14:00:00Z" }\n}\n```',
+ },
+ {
+ name: 'logs-services-create',
+ description:
+ 'Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate, plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking attribute-values + per-service counts.',
+ },
+ {
+ name: 'logs-sparkline-query',
+ description:
+ 'Get a time-bucketed sparkline of log volume, broken down by severity or service. Use this to understand log volume patterns before querying individual log entries — it is much cheaper than a full log query.\n\nAll parameters must be nested inside a `query` object.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the sparkline. Defaults to the last hour (`-1h`).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for "now".\n\n## query.serviceNames\n\nFilter by service names.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.searchTerm\n\nFull-text search across log bodies.\n\n## query.filterGroup\n\nProperty filters to narrow results. Same format as `query-logs` filters.\n\n## query.sparklineBreakdownBy\n\nBreak down the sparkline by `"severity"` (default) or `"service"`. Use `"service"` to see which services are producing the most logs.\n\n# Examples\n\n## Error volume over the last day\n\n```json\n{\n "query": {\n "serviceNames": ["api-gateway"],\n "severityLevels": ["error", "fatal"],\n "dateRange": { "date_from": "-1d" }\n }\n}\n```\n\n## Log volume by service\n\n```json\n{\n "query": {\n "serviceNames": ["api-gateway"],\n "sparklineBreakdownBy": "service",\n "dateRange": { "date_from": "-6h" }\n }\n}\n```\n\n## Log volume by severity\n\n```json\n{\n "query": {\n "serviceNames": ["api-gateway"],\n "sparklineBreakdownBy": "severity",\n "dateRange": { "date_from": "-1d" }\n }\n}\n```',
+ },
+ {
+ name: 'query-logs',
+ description:
+ 'Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool\'s typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: "service.name"` and `attribute_type: "resource"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: "resource"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: "resource"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`\'s max `limit` of 1000 — or if the user\'s question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call\'s `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\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\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn\'t specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ "date_from": "-1h" }`). Omitting it fails with a 400 `parse_error` ("Input should be a valid dictionary or instance of DateRange") — the server does not fall back to a default window.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user\'s question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key "message" for this type.\n - `log_attribute` — filters log-level attributes (e.g. "k8s.container.name", "http.method").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: "log"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: "resource"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `["posthogDistinctId"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n "query": {\n "serviceNames": ["<service>"],\n "filterGroup": [\n {\n "key": "posthogDistinctId",\n "operator": "exact",\n "type": "log_attribute",\n "value": ["<distinct_id_1>", "<distinct_id_2>"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer\'s logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn\'t mention time, use the last hour: `{ "date_from": "-1h" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response\'s `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `"ERROR"`, `"Warning"`, `"err"`), `severityLevels: ["error"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: "severity_text" }` and either filter on the value you find or fall back to a `searchTerm`. See "Severity fields in the response" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: "service.name"` and `attribute_type: "resource"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the "Property filters" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ "date_from": "-1h" }` when the question doesn\'t mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for "now".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n "query": {\n "severityLevels": ["error", "fatal"],\n "serviceNames": ["<service>"],\n "dateRange": { "date_from": "-1h" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n "query": {\n "searchTerm": "connection refused",\n "serviceNames": ["<service>"],\n "dateRange": { "date_from": "-6h" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n "query": {\n "serviceNames": ["api-gateway"],\n "dateRange": { "date_from": "-1d" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n "query": {\n "serviceNames": ["<service>"],\n "filterGroup": [{ "key": "http.status_code", "operator": "exact", "type": "log_attribute", "value": "500" }],\n "dateRange": { "date_from": "-1d" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n "query": {\n "severityLevels": ["error"],\n "filterGroup": [\n { "key": "k8s.container.name", "operator": "exact", "type": "log_resource_attribute", "value": "web" }\n ],\n "dateRange": { "date_from": "-12h" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n "query": {\n "serviceNames": ["<service>"],\n "filterGroup": [{ "key": "message", "operator": "icontains", "type": "log", "value": "timeout" }],\n "dateRange": { "date_from": "-1h" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n "query": {\n "serviceNames": ["<service>"],\n "filterGroup": [{ "key": "trace_id", "operator": "is_set", "type": "log_attribute" }],\n "dateRange": { "date_from": "-1h" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for "warnings and above", that is `severityLevels: ["warn", "error", "fatal"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: "log"`. Pass `attribute_type: "resource"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user\'s question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.',
+ },
+]
+
+export const INVESTIGATING_LOGS_SKILL: EmbeddedSkill = {
+ name: 'investigating-logs',
+ description:
+ 'Investigate logs in a PostHog project: verify a service or deployment is healthy, explain an error spike, triage an incident, or understand what a log stream is saying. Use when the user asks to "check the logs", asks whether a service, deploy, release, or change is working or broke anything, asks why errors are up or what changed, or wants the root cause of failures visible in logs. Routes the logs MCP tools (services overview, pattern mining, before/after pattern diffing, bucketed counts, facets, raw rows) so investigations start from summaries instead of raw rows or hand-written SQL over the logs table.\n',
+ content:
+ '# Investigating logs\n\nInvestigation is a narrowing problem: **summarize before you read**.\nOne `posthog:logs-patterns` call compresses millions of lines into at most 200 templates,\nand one `posthog:logs-patterns-diff` call answers "what is different about now vs. before" directly.\nRaw rows (`posthog:query-logs`) are the last step of an investigation, never the first.\n\n## When to use this skill\n\n- "Check the logs" / "is service X healthy?" / "did my deploy (or model bump, config change, migration) break anything?"\n- "Why are errors up?" / "explain this spike" / incident triage — "what changed?"\n- "What is this service logging?" — orienting in an unfamiliar or noisy stream.\n- Finding the log evidence for a failure reported elsewhere (an alert, an error-tracking issue, a user complaint).\n\n## When _not_ to use this skill\n\n- Creating or tuning log alerts — that\'s `authoring-log-alerts`.\n- Analytics over product events, persons, or insights — that\'s `querying-posthog-data`.\n- HogQL exposes a `logs` table via `posthog:execute-sql`, but do not investigate through it:\n hand-written SQL over logs routinely hits read-byte caps and re-derives what the tools below do in one cheap call.\n Reserve SQL for the rare case of joining log-derived facts with non-log data.\n\n## Tools\n\n| Tool | Job |\n| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |\n| `posthog:logs-services-create` | Top-25 services with log_count, error_count, error_rate, sparkline. Orientation. |\n| `posthog:logs-patterns` | Mine one window\'s message templates, ordered by frequency. "What is this stream saying?" |\n| `posthog:logs-patterns-diff` | Diff templates between two windows: new / rate-shifted / gone. "What changed?" |\n| `posthog:logs-count` / `posthog:logs-count-ranges` | Scalar and time-bucketed counts for a filter. Localize volume before pulling rows. |\n| `posthog:logs-sparkline-query` | Volume over time broken down by severity or service (the one bucketed view with a breakdown). |\n| `posthog:logs-facet-values-create` | Distribution of severity/service (or a resource attribute) under a filter. |\n| `posthog:logs-attributes-list` / `posthog:logs-attribute-values-list` | Discover attribute keys and values before building filters. |\n| `posthog:query-logs` | Raw rows. Endpoint of every drill-down, entry point of none. |\n\nEach tool\'s own description documents its parameters and response shape — read it before calling.\n\n## Pick the workflow by question shape\n\n### "Is it healthy?" — post-deploy / post-change verification\n\nThe user changed something (deploy, model bump, config, migration) and wants to know the logs still look right.\n\n1. Pin down the change time and the affected service(s). Ask if the user hasn\'t said; the diff is meaningless without a boundary.\n2. Orient with `posthog:logs-services-create`: is the service still logging at all, and what is its error_rate now?\n A service that went silent fails verification just as hard as one that started erroring.\n3. `posthog:logs-patterns-diff` with `query.dateRange` from the change time to now and `baselineDateRange`\n set to a comparable window just before the change, scoped to `serviceNames`.\n New error/fatal templates right after a change are the classic regression signature;\n large `rate_ratio` shifts on existing error templates are the second thing to check.\n4. Check volume continuity with `posthog:logs-count-ranges` spanning before and after the boundary:\n a rate discontinuity (crash loop, restart storm, silence) shows up here even when message content looks unchanged.\n5. Drill only the suspects: pivot each suspicious pattern to raw lines via its `match_regex` with `posthog:query-logs`.\n\nA pass verdict needs all three: no new error templates, no large error rate_ratio shifts, and continuous volume.\nSay which windows you compared — "healthy" is only as strong as the baseline.\n\n### "Explain this spike"\n\n1. Localize it: `posthog:logs-count-ranges` over the user\'s window, then recurse into the dense bucket(s) — each bucket\'s\n `date_from`/`date_to` feeds the next call. Stop after 3–4 levels.\n2. Explain it: `posthog:logs-patterns-diff` with the spike as `query.dateRange` and the window just before as\n `baselineDateRange`. The top `new` and `rate_shift` entries are the explanation. Do not mine both windows\n separately and diff by hand — the diff is one call.\n\n### Incident triage — "what broke?"\n\n`posthog:logs-patterns-diff` first: incident window vs. a known-good window just before (or omit the baseline for\nsame-window-last-week). Suspects are `new` entries and the biggest `rate_ratio` shifts; pivot each to raw lines.\nIf the failing service is unknown, find it first with `posthog:logs-facet-values-create` faceting `service_name`\nunder `severityLevels: ["error", "fatal"]`.\n\n### "What is this stream saying?" — unfamiliar service\n\n`posthog:logs-patterns` over the last hour, scoped to the service. Scan templates by `estimated_count` and\nnon-zero error share in `severity_counts`. Widen the window or add `searchTerm` only if the answer isn\'t there.\n\n### Known needle — a specific message, attribute, or person\n\nWhen the target is already precise (an error string, a request id, a distinct_id), skip pattern mining:\ndiscover the right keys with `posthog:logs-attributes-list` / `posthog:logs-attribute-values-list`,\nsize the result with `posthog:logs-count`, then pull rows with `posthog:query-logs`.\n\n## Rules that keep investigations honest and cheap\n\n- Scope `serviceNames` (or a resource-attribute filter) on every call once the target service is known.\n Unscoped calls scan the whole team\'s stream and starve the pattern sample budget.\n- `posthog:query-logs` requires an explicit `query.dateRange` — omitting it is a 400, not a default window.\n- Pattern counts are sampled estimates (`sampled: true`); templates rarer than ~1 in 10,000 rows can be invisible.\n Absence of a rare template is not evidence it stopped.\n- Before trusting a wall of `new` entries in a diff, check `baseline.total_count` —\n a tiny or empty baseline (logging only just started) makes everything look new.\n- `severityLevels` matches the six canonical lowercase buckets against `severity_text` exactly.\n Zero rows on a severity filter → check the stored values with `posthog:logs-attribute-values-list { key: "severity_text" }`.\n- Budget: one services call, at most one patterns-diff per window pair, 3–4 count-ranges levels,\n and `query-logs` only for confirmed suspects with `limit` ≤ 100.\n\n## Output\n\nLead with the verdict, then the evidence:\n\n- **Verdict**: healthy / regressed / inconclusive, with the windows compared.\n- **Suspects** (if any): template, classification (`new` / `rate_shift`), estimated counts or `rate_ratio`, services, and 1–2 sample raw lines.\n- **What was checked and what wasn\'t**: services covered, windows, and any sampling or baseline caveats that limit confidence.\n\nThe user should be able to act on the verdict without re-running the investigation.\n\n## Related skills\n\n- **`authoring-log-alerts`** — turn the check behind a verdict into a continuous, low-noise alert\n- **`exploring-apm-traces`** — follow a suspicious log line into the request traces around it',
+}
diff --git a/products/logs/frontend/logsAgentContext.test.ts b/products/logs/frontend/logsAgentContext.test.ts
new file mode 100644
index 000000000000..035d9d4ded03
--- /dev/null
+++ b/products/logs/frontend/logsAgentContext.test.ts
@@ -0,0 +1,90 @@
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
+
+import { DEFAULT_DATE_RANGE } from './components/LogsViewer/Filters/logsViewerFiltersLogic'
+import { logsQueryToViewerFilters } from './logsAgentContext'
+
+describe('logsAgentContext', () => {
+ const innerValues = (filterGroup: UniversalFiltersGroup): any[] =>
+ (filterGroup.values[0] as UniversalFiltersGroup).values
+
+ it('unwraps the query object and mirrors date range and search term', () => {
+ const result = logsQueryToViewerFilters({
+ query: { dateRange: { date_from: '-6h' }, searchTerm: 'connection refused' },
+ })
+
+ expect(result.dateRange).toEqual({ date_from: '-6h' })
+ expect(result.searchTerm).toBe('connection refused')
+ })
+
+ it('falls back to the default date range and empty search when omitted', () => {
+ const result = logsQueryToViewerFilters({ query: {} })
+
+ expect(result.dateRange).toEqual(DEFAULT_DATE_RANGE)
+ expect(result.searchTerm).toBe('')
+ })
+
+ it('accepts a raw input that is not wrapped in a query object', () => {
+ const result = logsQueryToViewerFilters({ dateRange: { date_from: '-1d' } })
+
+ expect(result.dateRange).toEqual({ date_from: '-1d' })
+ })
+
+ it('defaults type and operator on raw agent filters that omit them', () => {
+ const result = logsQueryToViewerFilters({
+ query: { filterGroup: [{ key: 'http.status_code', value: '500' }] },
+ })
+
+ expect(innerValues(result.filterGroup!)).toEqual([
+ {
+ key: 'http.status_code',
+ value: '500',
+ type: PropertyFilterType.LogAttribute,
+ operator: PropertyOperator.Exact,
+ },
+ ])
+ })
+
+ it('preserves an explicit type and operator on a raw filter', () => {
+ const result = logsQueryToViewerFilters({
+ query: {
+ filterGroup: [{ key: 'message', value: 'timeout', type: 'log', operator: 'icontains' }],
+ },
+ })
+
+ expect(innerValues(result.filterGroup!)[0]).toMatchObject({
+ key: 'message',
+ operator: 'icontains',
+ type: 'log',
+ })
+ })
+
+ it('folds service names and severity levels into the filter group', () => {
+ const result = logsQueryToViewerFilters({
+ query: { serviceNames: ['api-gateway'], severityLevels: ['error', 'fatal'] },
+ })
+
+ const serialized = JSON.stringify(result.filterGroup)
+ expect(serialized).toContain('api-gateway')
+ expect(serialized).toContain('error')
+ expect(serialized).toContain('fatal')
+ })
+
+ it('drops severity values outside the canonical buckets', () => {
+ const result = logsQueryToViewerFilters({
+ query: { severityLevels: ['error', 'ERROR', 'nonsense'] },
+ })
+
+ const serialized = JSON.stringify(result.filterGroup)
+ expect(serialized).toContain('error')
+ expect(serialized).not.toContain('nonsense')
+ })
+
+ it('produces the empty default group when no filters are given', () => {
+ const result = logsQueryToViewerFilters({ query: {} })
+
+ expect(result.filterGroup).toEqual({
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [] }],
+ })
+ })
+})
diff --git a/products/logs/frontend/logsAgentContext.ts b/products/logs/frontend/logsAgentContext.ts
new file mode 100644
index 000000000000..1f9dd881daad
--- /dev/null
+++ b/products/logs/frontend/logsAgentContext.ts
@@ -0,0 +1,156 @@
+import { DateRange, LogsQuery } from '~/queries/schema/schema-general'
+import {
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ UniversalFiltersGroup,
+ UniversalFiltersGroupValue,
+} from '~/types'
+
+import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
+
+import { LogsViewerFilters } from './components/LogsViewer/config/types'
+import {
+ DEFAULT_DATE_RANGE,
+ foldLegacyColumnFilters,
+ isValidSeverityLevel,
+} from './components/LogsViewer/Filters/logsViewerFiltersLogic'
+import { INVESTIGATING_LOGS_SKILL, LOGS_MCP_TOOLS } from './generated/agentContext'
+
+// Each visible chip and the hidden payload items it stands for share a dismiss group, so closing
+// the chip actually detaches the payload instead of only hiding the chip.
+const SKILL_DISMISS_GROUP = 'logs-scene-skill'
+const VIEWER_STATE_DISMISS_GROUP = 'logs-scene-viewer-state'
+
+// All static strings below are build-time constants from our own repo (skill markdown + tool
+// descriptions), which is what makes them safe to attach as trusted `instructions` items.
+const PREAMBLE_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: SKILL_DISMISS_GROUP,
+ value:
+ 'The user has the PostHog logs viewer open. The full investigating-logs skill and the complete ' +
+ 'logs MCP tool catalog are included in this context - you already have everything needed to act. ' +
+ 'Do not spend turns discovering tools or reading skill files: call the listed tools directly, and use ' +
+ 'the exec `info <tool>` command only when you need a full input schema.',
+}
+
+const SKILL_CONTENT_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: SKILL_DISMISS_GROUP,
+ value: `Skill ${INVESTIGATING_LOGS_SKILL.name} (embedded): ${INVESTIGATING_LOGS_SKILL.content}`,
+}
+
+const TOOL_CONTEXT_ITEMS: AttachedContextItem[] = LOGS_MCP_TOOLS.map((tool) => ({
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: SKILL_DISMISS_GROUP,
+ value: `MCP tool ${tool.name}: ${tool.description}`,
+}))
+
+const SKILL_CHIP_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'skill',
+ key: INVESTIGATING_LOGS_SKILL.name,
+ label: 'Investigating logs skill',
+ dismissGroup: SKILL_DISMISS_GROUP,
+}
+
+// Static: names the field the live state carries, so no user-entered filter value reaches trusted
+// context. The viewer-state item's value changes with the filters, so it always re-sends.
+const APPLY_BACK_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: VIEWER_STATE_DISMISS_GROUP,
+ value:
+ 'The logs_viewer_state item is the current filter state of the open logs viewer (date range, ' +
+ 'search term, and filter group with severity and service selections folded in as chips). When you ' +
+ 'call query-logs, the query filters (serviceNames, severityLevels, searchTerm, filterGroup, ' +
+ 'dateRange) are also applied to the open viewer, so the user sees matching logs both in this chat ' +
+ 'and on screen. Read logs_viewer_state to see what the user is already filtering on.',
+}
+
+export const LOGS_AGENT_HEADLINES: string[] = [
+ 'How can I help you investigate these logs?',
+ 'What are you trying to find in the logs?',
+]
+
+// The viewer filter state the agent cannot fetch: what the user is currently filtering on. Small by
+// construction (a date range, a search term, and a filter group), so it rides along whole with no
+// budgeting. It is an untrusted item, so user-typed search terms and values stay intact.
+function serializeViewerState(filters: LogsViewerFilters): string {
+ return JSON.stringify({
+ dateRange: filters.dateRange,
+ searchTerm: filters.searchTerm ?? '',
+ filterGroup: filters.filterGroup,
+ })
+}
+
+/**
+ * The default agent context for the logs viewer: the embedded investigating-logs skill, the logs MCP
+ * tool catalog, an instruction that query-logs calls reflect onto the open page, and the live viewer
+ * filter state so the agent can read what the user is filtering on without a fetch.
+ */
+export function buildLogsAgentContext(filters: LogsViewerFilters): AttachedContextItem[] {
+ return [
+ PREAMBLE_CONTEXT_ITEM,
+ SKILL_CHIP_CONTEXT_ITEM,
+ SKILL_CONTENT_CONTEXT_ITEM,
+ ...TOOL_CONTEXT_ITEMS,
+ APPLY_BACK_CONTEXT_ITEM,
+ {
+ type: 'logs_viewer_state',
+ hidden: true,
+ dismissGroup: VIEWER_STATE_DISMISS_GROUP,
+ value: serializeViewerState(filters),
+ },
+ ]
+}
+
+function asStringArray(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
+}
+
+/**
+ * Map a query-logs tool input onto the viewer's filter fields, mirroring what the tool queried onto
+ * the open page. The args are raw agent-sent JSON (never zod-validated), so every field is coerced
+ * and defaulted. Severity and service selections are folded into the filter group the same way the
+ * viewer keeps them, and an omitted field resets that facet so the page shows the query's results
+ * exactly - the same complete-query semantics the tool ran with.
+ */
+export function logsQueryToViewerFilters(input: Record<string, unknown>): Partial<LogsViewerFilters> {
+ // All query-logs params are nested inside `query`; fall back to the raw input defensively.
+ const query = (input.query && typeof input.query === 'object' ? input.query : input) as Record<string, unknown>
+
+ const flatValues: UniversalFiltersGroup['values'] = (Array.isArray(query.filterGroup) ? query.filterGroup : []).map(
+ (filter) => {
+ const f = filter as Record<string, unknown>
+ return {
+ ...f,
+ type: (f.type as PropertyFilterType) || PropertyFilterType.LogAttribute,
+ operator: (f.operator as PropertyOperator) || PropertyOperator.Exact,
+ } as UniversalFiltersGroupValue
+ }
+ )
+
+ const baseGroup: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: flatValues }],
+ }
+
+ const severityLevels = asStringArray(query.severityLevels).filter(isValidSeverityLevel)
+ const serviceNames = asStringArray(query.serviceNames)
+
+ // No `filterGroup` key in the folded-in fields, so empty arrays clear that facet rather than
+ // being treated as a no-op against an authoritative group.
+ const filterGroup = foldLegacyColumnFilters(baseGroup, {
+ severityLevels: severityLevels as LogsQuery['severityLevels'],
+ serviceNames: serviceNames as LogsQuery['serviceNames'],
+ })
+
+ return {
+ dateRange: (query.dateRange as DateRange) ?? DEFAULT_DATE_RANGE,
+ searchTerm: typeof query.searchTerm === 'string' ? query.searchTerm : '',
+ filterGroup,
+ }
+}
diff --git a/services/mcp/scripts/build-scene-tool-context.ts b/services/mcp/scripts/build-scene-tool-context.ts
index 8b3da1370a5a..9632ae270ae9 100644
--- a/services/mcp/scripts/build-scene-tool-context.ts
+++ b/services/mcp/scripts/build-scene-tool-context.ts
@@ -85,6 +85,17 @@ const CONFIGS: SceneContextConfig[] = [
},
],
},
+ {
+ output: 'products/logs/frontend/generated/agentContext.ts',
+ tools: [{ constName: 'LOGS_MCP_TOOLS', yamlPath: 'products/logs/mcp/tools.yaml' }],
+ skills: [
+ {
+ constName: 'INVESTIGATING_LOGS_SKILL',
+ skillDir: 'products/logs/skills/investigating-logs',
+ files: ['SKILL.md'],
+ },
+ ],
+ },
]
interface ToolDefinition {